DB viewer + query editor enhancements (home-screen-ux-query-editor) (#4)

* feat: add query_history table migration (v5) (Task 1)

* feat: add isDestructiveQuery utility (Task 2)

* feat: add tabType discriminator and openQueryTab to dbViewerStore (Task 3)

* feat: add execute_query command with pagination and query history (Task 4)

* feat: add typed wrappers for executeQuery, getQueryHistory, clearQueryHistory (Task 5)

* fix: global search bypasses folder scope when filters active (Task 6)

* feat: add TagFilterDropdown with checkboxes and empty state (Task 7)

* feat: add DbTypeFilterDropdown with checkboxes and clear all (Task 8)

* feat: wire TagFilterDropdown/DbTypeFilterDropdown into ActionRow, add inline tag creation (Task 9)

* feat: add Name input to GeneralTab for connection editing (Task 10)

* feat: add QueryEditor Monaco wrapper with SQL mode and Cmd+Enter (Task 11)

* feat: add DestructiveQueryDialog with SQL preview and confirmation (Task 12)

* feat: integrate query tabs, Monaco editor, destructive guard into DbViewerScreen (Task 13)

* fix: harden moveConnection against race conditions on rapid drags (Task 14)

* docs: update AGENTS.md implementation status for Home Screen UX + Query Editor (Task 15)

* feat: switch tag filter to OR semantics, add environment filter (F-T16)

* feat: add activeEnvironment filter state to uiStore and useFilteredConnections (F-T17)

* feat: add environment filter select to Filters dropdown (F-T18)

* feat: filter folder cards by tag match or contained connections (F-T19)

* fix: keep grid header width to content, border last column

* fix: hide select-all checkbox and empty-state when no table open

* fix: filter folder cards by any active filter, show global search results (F-T20)

* feat: show 'Showing Search Results' breadcrumb with clear button (F-T21)

* docs: update README + AGENTS.md for Query Editor, filters, and planned AI integration (BYOK)

* feat: refresh indicator with spinning icon and pulse, defer auto-refresh on tab switch

* feat: smart default schema selection, refresh schemas on database switch

* fix: auto-refresh waits for in-flight refresh to complete before next tick

* style: shrink db viewer sidebar nav icons from 20px to 16px

* style: shrink db viewer sidebar nav buttons to 32px (8px padding)

* style: make Tables panel title xs, regular weight, muted

* style: bump Tables panel title back to sm, keep regular weight and muted

* feat: export schema diagram as PNG/JPEG/SVG (entire schema or viewport)

* chore: lockfile for html-to-image

* fix: raise schema visualizer toolbar above legend so export menu isn't hidden

* feat: schema export via save dialog, transparent background option, save notification

* fix: render nothing in tab bar when no tabs are open

* style: reduce tab bar height from 40px to 36px

* style: reduce tab bar height to 32px

* style: revert tab bar height to 36px

* feat: split tab bar with fixed +Query and Changes actions on the right

* style: blue play-icon Query button in tab bar

* refactor: remove sidebar New Query button (now in tab bar)

* style: conditional bottom padding in sidebar toolbar when nothing is below

* feat: distinguish table and query tabs with icons

* style: tab icons follow active/inactive state, muted colors

* feat: query tab toolbar (run/format/dialect badge) + bare transparent editor

* style: blue rounded Run Query button in query toolbar

* feat: smart platform-aware shortcut tooltip on Run Query (⌘+⏎ / Ctrl+Enter)

* style: show only the shortcut in the Run Query tooltip

* fix: Cmd+Enter keybinding stale closure; add run pulse to query toolbar; bundle monaco locally (offline)

* feat: show placeholder text in empty query editor

* feat: SQL autocomplete — keywords + table names from active schema

* feat: per-table column autocomplete on 'table.' + docs update

* feat: query-variant result toolbar — export/refresh/columns left, smart-unit execution time right

* fix: populate execution_time_ms on query results so the toolbar can show time taken

* fix: re-measure monaco fonts after async font load to stop cursor drift

* feat: resizable + collapsible query results panel

* refactor: move results caret onto the resize handle (centered), bottom caret when collapsed

* style: thin drag strip with caret on its own centered pill

* refactor: remove Queue button from table toolbar (Changes lives in tab bar)

* style: changes button becomes bordered rounded icon with count badge

* docs: mark tab-bar Changes queue button in AGENTS.md and README
This commit is contained in:
2026-08-01 05:56:47 +08:00
committed by GitHub
parent 4f18993e70
commit 80962d7d11
66 changed files with 5681 additions and 509 deletions
+398 -20
View File
@@ -1,28 +1,406 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import { render, screen, fireEvent, waitFor, act } from "@testing-library/react";
import { DbViewerScreen } from "./DbViewerScreen";
import { useDbViewerStore } from "../../stores/dbViewerStore";
import * as commands from "../../lib/commands";
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: () => ({
getVirtualItems: () => [],
getTotalSize: () => 0,
measureElement: () => {},
}),
vi.mock("../../hooks/useDbConnection", () => ({
useDbConnection: (_connectionId: string) => ({
connectionError: null,
connect: vi.fn(),
}),
}));
describe("DbViewerScreen", () => {
beforeEach(() => {
useDbViewerStore.setState({
tabs: [], activeTabId: null, changesQueue: [],
databases: ["mydb"], schemas: ["public"],
tables: [{ name: "users", schema: "public", table_type: "TABLE" }],
currentDatabase: "mydb", currentSchema: "public",
});
});
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: () => ({
getVirtualItems: () => [],
getTotalSize: () => 0,
measureElement: () => {},
}),
}));
it("renders the sidebar", () => {
render(<DbViewerScreen connectionId="c1" onHome={() => {}} onSettings={() => {}} />);
expect(screen.getByLabelText(/home/i)).toBeInTheDocument();
});
const { registeredActions } = vi.hoisted(() => ({
registeredActions: [] as Array<{ run: () => void }>,
}));
// monaco-editor's global font re-measure — stub so jsdom stays light
vi.mock("monaco-editor", () => ({
editor: { remeasureFonts: vi.fn() },
}));
vi.mock("@monaco-editor/react", async () => {
const { useEffect } = await import("react");
return {
default: ({ value, onChange, onMount }: any) => {
useEffect(() => {
onMount?.({
addAction: (action: any) => registeredActions.push(action),
getValue: () => value,
setValue: (v: string) => onChange?.(v),
focus: () => {},
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div data-testid="monaco-editor">
<textarea
data-testid="monaco-textarea"
value={value}
onChange={(e) => onChange?.(e.target.value)}
/>
</div>
);
},
};
});
const mockQueryResult = {
columns: [
{
name: "id",
data_type: "integer",
is_nullable: false,
is_pk: true,
is_fk: false,
fk_ref: null,
default_value: null,
},
],
rows: [[1]],
total_rows: 1,
page: 1,
page_size: 50,
execution_time_ms: 42,
};
describe("DbViewerScreen", () => {
beforeEach(() => {
useDbViewerStore.getState().reset();
useDbViewerStore.setState({
databases: ["mydb"],
schemas: ["public"],
tables: [
{ name: "users", schema: "public", table_type: "TABLE" },
],
currentDatabase: "mydb",
currentSchema: "public",
});
vi.resetAllMocks();
});
it("renders the sidebar", () => {
render(
<DbViewerScreen
connectionId="c1"
onHome={() => {}}
onSettings={() => {}}
/>,
);
expect(screen.getByLabelText(/home/i)).toBeInTheDocument();
});
it("renders the New Query button", () => {
render(
<DbViewerScreen
connectionId="c1"
onHome={() => {}}
onSettings={() => {}}
/>,
);
expect(screen.getByRole("button", { name: /new query/i })).toBeInTheDocument();
});
it("opens a query tab when New Query is clicked", () => {
render(
<DbViewerScreen
connectionId="c1"
onHome={() => {}}
onSettings={() => {}}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /new query/i }));
expect(screen.getByRole("tab", { name: "Query" })).toBeInTheDocument();
});
it("renders the query editor inside a query tab", async () => {
render(
<DbViewerScreen
connectionId="c1"
onHome={() => {}}
onSettings={() => {}}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /new query/i }));
await waitFor(() => {
expect(screen.getByTestId("monaco-editor")).toBeInTheDocument();
});
expect(screen.getByRole("button", { name: /run query/i })).toBeInTheDocument();
});
it("executes a non-destructive query when Run is clicked", async () => {
const executeQuery = vi
.spyOn(commands, "executeQuery")
.mockResolvedValue(mockQueryResult as any);
render(
<DbViewerScreen
connectionId="c1"
onHome={() => {}}
onSettings={() => {}}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /new query/i }));
const textarea = await waitFor(() =>
screen.getByTestId("monaco-textarea"),
);
fireEvent.change(textarea, { target: { value: "SELECT 1" } });
fireEvent.click(screen.getByRole("button", { name: /run query/i }));
await waitFor(() =>
expect(executeQuery).toHaveBeenCalledWith("c1", "SELECT 1", 1, 50),
);
// query variant toolbar shows the execution time from the result
await waitFor(() => expect(screen.getByText("42.00ms")).toBeInTheDocument());
expect(screen.getByLabelText(/execution time/i)).toBeInTheDocument();
});
it("shows a destructive-query confirmation dialog and executes on confirm", async () => {
const executeQuery = vi
.spyOn(commands, "executeQuery")
.mockResolvedValue({
columns: [],
rows: [],
total_rows: 0,
page: 1,
page_size: 50,
} as any);
render(
<DbViewerScreen
connectionId="c1"
onHome={() => {}}
onSettings={() => {}}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /new query/i }));
const textarea = await waitFor(() =>
screen.getByTestId("monaco-textarea"),
);
fireEvent.change(textarea, {
target: { value: "DELETE FROM users" },
});
fireEvent.click(screen.getByRole("button", { name: /run query/i }));
await waitFor(() => {
expect(screen.getByText("Destructive Query")).toBeInTheDocument();
});
expect(executeQuery).not.toHaveBeenCalled();
fireEvent.click(screen.getByText("Execute"));
await waitFor(() =>
expect(executeQuery).toHaveBeenCalledWith(
"c1",
"DELETE FROM users",
1,
50,
),
);
});
it("formats the query SQL when Auto format is clicked", async () => {
render(
<DbViewerScreen
connectionId="c1"
onHome={() => {}}
onSettings={() => {}}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /new query/i }));
const textarea = await waitFor(() =>
screen.getByTestId("monaco-textarea"),
);
fireEvent.change(textarea, {
target: { value: "select * from users where id = 1" },
});
fireEvent.click(screen.getByRole("button", { name: /auto format/i }));
await waitFor(() => {
expect((textarea as HTMLTextAreaElement).value).toMatch(/\n/);
});
});
it("runs the current query when the Cmd+Enter action fires", async () => {
const executeQuery = vi
.spyOn(commands, "executeQuery")
.mockResolvedValue(mockQueryResult as any);
render(
<DbViewerScreen
connectionId="c1"
onHome={() => {}}
onSettings={() => {}}
/>,
);
registeredActions.length = 0;
fireEvent.click(screen.getByRole("button", { name: /new query/i }));
const textarea = await waitFor(() =>
screen.getByTestId("monaco-textarea"),
);
fireEvent.change(textarea, {
target: { value: "SELECT 42" },
});
expect(registeredActions).toHaveLength(1);
registeredActions[0].run();
await waitFor(() =>
expect(executeQuery).toHaveBeenCalledWith("c1", "SELECT 42", 1, 50),
);
});
it("shows the pulse while a query is running and hides it after", async () => {
let resolveRun!: (v: unknown) => void;
const pending = new Promise<unknown>((r) => {
resolveRun = r;
});
vi.spyOn(commands, "executeQuery").mockReturnValue(pending as any);
render(
<DbViewerScreen
connectionId="c1"
onHome={() => {}}
onSettings={() => {}}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /new query/i }));
const textarea = await waitFor(() =>
screen.getByTestId("monaco-textarea"),
);
fireEvent.change(textarea, { target: { value: "SELECT 1" } });
fireEvent.click(screen.getByRole("button", { name: /run query/i }));
await waitFor(() =>
expect(screen.getByTestId("query-run-pulse")).toBeInTheDocument(),
);
resolveRun(mockQueryResult);
await waitFor(() =>
expect(screen.queryByTestId("query-run-pulse")).toBeNull(),
);
});
it("collapses and re-expands the query results via the caret", async () => {
const executeQuery = vi
.spyOn(commands, "executeQuery")
.mockResolvedValue(mockQueryResult as any);
render(
<DbViewerScreen
connectionId="c1"
onHome={() => {}}
onSettings={() => {}}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /new query/i }));
const textarea = await waitFor(() =>
screen.getByTestId("monaco-textarea"),
);
fireEvent.change(textarea, { target: { value: "SELECT 1" } });
fireEvent.click(screen.getByRole("button", { name: /run query/i }));
await waitFor(() => expect(screen.getByText("42.00ms")).toBeInTheDocument());
expect(screen.getByTestId("query-results")).toBeInTheDocument();
fireEvent.click(screen.getByLabelText(/hide results/i));
expect(screen.queryByTestId("query-results")).toBeNull();
expect(screen.queryByText("42.00ms")).toBeNull();
fireEvent.click(screen.getByLabelText(/show results/i));
expect(screen.getByTestId("query-results")).toBeInTheDocument();
expect(executeQuery).toHaveBeenCalledTimes(1);
});
it("resizes the results panel with a drag handle, clamped to min/max", async () => {
vi.spyOn(commands, "executeQuery").mockResolvedValue(
mockQueryResult as any,
);
render(
<DbViewerScreen
connectionId="c1"
onHome={() => {}}
onSettings={() => {}}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /new query/i }));
const textarea = await waitFor(() =>
screen.getByTestId("monaco-textarea"),
);
fireEvent.change(textarea, { target: { value: "SELECT 1" } });
fireEvent.click(screen.getByRole("button", { name: /run query/i }));
await waitFor(() => expect(screen.getByText("42.00ms")).toBeInTheDocument());
const results = screen.getByTestId("query-results");
const initial = parseFloat(results.style.height);
const handle = screen.getByTestId("query-results-resize");
// Drag up: results grow
fireEvent.mouseDown(handle, { clientY: 200 });
fireEvent.mouseMove(document, { clientY: 100 });
fireEvent.mouseUp(document);
await waitFor(() =>
expect(parseFloat(results.style.height)).toBeGreaterThan(initial),
);
// Drag far down: clamps to the 120px minimum
fireEvent.mouseDown(handle, { clientY: 200 });
fireEvent.mouseMove(document, { clientY: 5000 });
fireEvent.mouseUp(document);
await waitFor(() => expect(parseFloat(results.style.height)).toBe(120));
});
it("re-fetches the active table and shows the refresh indicator when refresh is clicked", async () => {
let resolveFetch!: (v: unknown) => void;
const pendingFetch = new Promise<unknown>((r) => {
resolveFetch = r;
});
const getTableData = vi
.spyOn(commands, "getTableData")
.mockReturnValue(pendingFetch as any);
useDbViewerStore.setState({
tabs: [
{
id: "tab-1",
schema: "public",
table: "users",
page: 1,
pageSize: 50,
loading: false,
error: null,
data: mockQueryResult,
filterRules: [],
sortRules: [],
hiddenColumns: [],
smartSortApplied: true,
tabType: "table",
},
],
activeTabId: "tab-1",
});
render(
<DbViewerScreen
connectionId="c1"
onHome={() => {}}
onSettings={() => {}}
/>,
);
// Tab already has data and is not loading → no fetch on mount
expect(getTableData).not.toHaveBeenCalled();
fireEvent.click(screen.getByLabelText(/refresh table/i));
// Refetch triggered for the active tab
await waitFor(() => expect(getTableData).toHaveBeenCalledTimes(1));
// Indicator visible while the fetch is in flight
await waitFor(() =>
expect(screen.getByTestId("refresh-pulse")).toBeInTheDocument(),
);
act(() => {
resolveFetch({ ...mockQueryResult });
});
await waitFor(() =>
expect(
screen.queryByTestId("refresh-pulse"),
).not.toBeInTheDocument(),
);
});
});