Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(sql-editor): maximize the query result pane (#21459)

Danny Xufb448a80475e
diff --git a/frontend/src/modules/sql-editor/components/ResultPanel/MaximizeToggle.test.tsx b/frontend/src/modules/sql-editor/components/ResultPanel/MaximizeToggle.test.tsx
new file mode 100644
index 0000000000..5414267afd
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/ResultPanel/MaximizeToggle.test.tsx
@@ -0,0 +1,145 @@
+import type { ReactElement } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ state: { resultPanelMaximized: false },
+ setResultPanelMaximized: vi.fn((value: boolean) => {
+ mocks.state.resultPanelMaximized = value;
+ }),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/modules/sql-editor/store", () => {
+ const state = {
+ get resultPanelMaximized() {
+ return mocks.state.resultPanelMaximized;
+ },
+ setResultPanelMaximized: mocks.setResultPanelMaximized,
+ };
+ return {
+ useSQLEditorStore: Object.assign(
+ (selector: (s: typeof state) => unknown) => selector(state),
+ { getState: () => state }
+ ),
+ };
+});
+
+// The shared Tooltip renders a floating popup through a portal, which this
+// test doesn't need; only the trigger it wraps matters here.
+vi.mock("@/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: { children: ReactElement }) => children,
+}));
+
+import { MaximizeToggle } from "./MaximizeToggle";
+
+let container: HTMLDivElement;
+let root: ReturnType<typeof createRoot> | undefined;
+
+const render = () => {
+ container = document.createElement("div");
+ document.body.append(container);
+ const mounted = createRoot(container);
+ root = mounted;
+ act(() => {
+ mounted.render(<MaximizeToggle />);
+ });
+};
+
+const button = () => container.querySelector("button") as HTMLButtonElement;
+
+const pressEscape = () => {
+ act(() => {
+ window.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true })
+ );
+ });
+};
+
+beforeEach(() => {
+ document.body.innerHTML = "";
+ mocks.state.resultPanelMaximized = false;
+ mocks.setResultPanelMaximized.mockClear();
+});
+
+// Unmount between tests: a mounted toggle keeps its window keydown listener,
+// and a leftover one would answer the next test's Escape.
+afterEach(() => {
+ if (!root) return;
+ const mounted = root;
+ root = undefined;
+ act(() => {
+ mounted.unmount();
+ });
+});
+
+describe("MaximizeToggle", () => {
+ test("offers Maximize while the pane is docked", () => {
+ render();
+ expect(button().getAttribute("aria-label")).toBe("common.maximize");
+ expect(button().getAttribute("aria-pressed")).toBe("false");
+
+ act(() => {
+ button().click();
+ });
+ expect(mocks.setResultPanelMaximized).toHaveBeenCalledWith(true);
+ });
+
+ test("offers Restore while the pane is maximized", () => {
+ mocks.state.resultPanelMaximized = true;
+ render();
+ expect(button().getAttribute("aria-label")).toBe("common.restore");
+ expect(button().getAttribute("aria-pressed")).toBe("true");
+
+ act(() => {
+ button().click();
+ });
+ expect(mocks.setResultPanelMaximized).toHaveBeenCalledWith(false);
+ });
+
+ test("Escape restores a maximized pane", () => {
+ mocks.state.resultPanelMaximized = true;
+ render();
+ pressEscape();
+ expect(mocks.setResultPanelMaximized).toHaveBeenCalledWith(false);
+ });
+
+ test("Escape does nothing while the pane is docked", () => {
+ render();
+ pressEscape();
+ expect(mocks.setResultPanelMaximized).not.toHaveBeenCalled();
+ });
+
+ test("Escape leaves the pane alone while a dialog is open", () => {
+ mocks.state.resultPanelMaximized = true;
+ render();
+ const dialog = document.createElement("div");
+ dialog.setAttribute("role", "dialog");
+ document.body.append(dialog);
+
+ pressEscape();
+ expect(mocks.setResultPanelMaximized).not.toHaveBeenCalled();
+ });
+
+ test("Escape restores past a dialog kept mounted while closed", () => {
+ mocks.state.resultPanelMaximized = true;
+ render();
+ for (const closedAttribute of ["hidden", "data-closed"]) {
+ const closed = document.createElement("div");
+ closed.setAttribute("role", "dialog");
+ closed.setAttribute(closedAttribute, "");
+ document.body.append(closed);
+ }
+
+ pressEscape();
+ expect(mocks.setResultPanelMaximized).toHaveBeenCalledWith(false);
+ });
+});
diff --git a/frontend/src/modules/sql-editor/components/ResultPanel/MaximizeToggle.tsx b/frontend/src/modules/sql-editor/components/ResultPanel/MaximizeToggle.tsx
new file mode 100644
index 0000000000..5919b202ab
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/ResultPanel/MaximizeToggle.tsx
@@ -0,0 +1,64 @@
+import { Maximize2, Minimize2 } from "lucide-react";
+import { useEffect } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/components/ui/button";
+import { Tooltip } from "@/components/ui/tooltip";
+import { useSQLEditorStore } from "@/modules/sql-editor/store";
+
+const OVERLAY_SELECTOR = '[role="dialog"], [role="alertdialog"], [role="menu"]';
+
+/**
+ * Whether an overlay is on screen to own the Escape key. A popup kept in the
+ * DOM while closed carries `hidden` or Base UI's `data-closed`, and matching
+ * one of those would disable Escape for good.
+ */
+const hasOpenOverlay = () =>
+ Array.from(document.querySelectorAll(OVERLAY_SELECTOR)).some(
+ (el) => !el.hasAttribute("hidden") && !el.hasAttribute("data-closed")
+ );
+
+/**
+ * Fills the editor area with the result pane, and back.
+ *
+ * It sits beside the query tabs rather than inside a result view, so every
+ * result — rows, an error, a query plan later — gets the same control.
+ *
+ * Escape restores, except while a dialog or menu is open: that surface owns
+ * the key, and restoring underneath it would close two things with one press.
+ */
+export function MaximizeToggle() {
+ const { t } = useTranslation();
+ const maximized = useSQLEditorStore((s) => s.resultPanelMaximized);
+ const setMaximized = useSQLEditorStore((s) => s.setResultPanelMaximized);
+
+ useEffect(() => {
+ if (!maximized) return;
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "Escape" || event.defaultPrevented) return;
+ if (hasOpenOverlay()) return;
+ setMaximized(false);
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, [maximized, setMaximized]);
+
+ const label = maximized ? t("common.restore") : t("common.maximize");
+ return (
+ <Tooltip content={label} side="bottom">
+ <Button
+ size="sm"
+ appearance="secondary"
+ className="mr-1 shrink-0"
+ aria-label={label}
+ aria-pressed={maximized}
+ onClick={() => setMaximized(!maximized)}
+ >
+ {maximized ? (
+ <Minimize2 className="size-4" />
+ ) : (
+ <Maximize2 className="size-4" />
+ )}
+ </Button>
+ </Tooltip>
+ );
+}
diff --git a/frontend/src/modules/sql-editor/components/ResultPanel/ResultPanel.test.tsx b/frontend/src/modules/sql-editor/components/ResultPanel/ResultPanel.test.tsx
new file mode 100644
index 0000000000..11e3c40bcd
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/ResultPanel/ResultPanel.test.tsx
@@ -0,0 +1,169 @@
+import type { ReactElement } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import type { SQLEditorDatabaseQueryContext } from "@/types";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ setResultPanelMaximized: vi.fn(),
+ state: {
+ resultPanelMaximized: false,
+ databaseQueryContexts: new Map<string, unknown[]>(),
+ },
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/lib/utils", () => ({
+ cn: (...classes: Array<string | false | undefined>) =>
+ classes.filter(Boolean).join(" "),
+}));
+
+vi.mock("@/components/ui/alert", () => ({ Alert: () => <div /> }));
+vi.mock("@/components/ui/context-menu", () => ({
+ ContextMenu: ({ children }: { children: ReactElement }) => children,
+ ContextMenuContent: () => null,
+ ContextMenuItem: () => null,
+ ContextMenuTrigger: ({ render }: { render: ReactElement }) => render,
+}));
+vi.mock("@/components/ui/tabs", () => ({
+ Tabs: ({ children }: { children: ReactElement | ReactElement[] }) => (
+ <div>{children}</div>
+ ),
+ TabsList: ({ children }: { children: ReactElement | ReactElement[] }) => (
+ <div>{children}</div>
+ ),
+ TabsPanel: ({ children }: { children: ReactElement | ReactElement[] }) => (
+ <div>{children}</div>
+ ),
+ TabsTrigger: ({ children }: { children: ReactElement | ReactElement[] }) => (
+ <div>{children}</div>
+ ),
+}));
+vi.mock("@/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: { children: ReactElement }) => children,
+}));
+
+// The real selector picks a database in an effect of its own; leaving it inert
+// reproduces the window right after a remount, when nothing is selected yet.
+vi.mock("./BatchQuerySelect", () => ({
+ BatchQuerySelect: () => <div>batch-query-select</div>,
+}));
+vi.mock("./DatabaseQueryContext", () => ({
+ DatabaseQueryContext: () => <div>database-query-context</div>,
+}));
+vi.mock("./MaximizeToggle", () => ({
+ MaximizeToggle: () => <div>maximize-toggle</div>,
+}));
+
+vi.mock("@/modules/sql-editor/store", () => {
+ const state = {
+ get resultPanelMaximized() {
+ return mocks.state.resultPanelMaximized;
+ },
+ setResultPanelMaximized: mocks.setResultPanelMaximized,
+ };
+ return {
+ useSQLEditorStore: (selector: (s: typeof state) => unknown) =>
+ selector(state),
+ };
+});
+
+vi.mock("@/modules/sql-editor/store/tab", () => ({
+ getSQLEditorTabsState: vi.fn(),
+ useCurrentSQLEditorTab: () => ({ id: "tab-1" }),
+ useIsInBatchMode: () => false,
+ useSQLEditorTabState: (selector: (s: unknown) => unknown) =>
+ selector({
+ currentTabId: "tab-1",
+ tabsById: new Map([
+ ["tab-1", { databaseQueryContexts: mocks.state.databaseQueryContexts }],
+ ]),
+ }),
+}));
+
+vi.mock("@/types", () => ({ getDataSourceTypeI18n: () => "" }));
+vi.mock("@/utils", () => ({
+ formatAbsoluteDateTime: () => "now",
+ getInstanceResource: () => ({ dataSources: [] }),
+}));
+
+import { ResultPanel } from "./ResultPanel";
+
+const aContext = () =>
+ ({
+ id: "ctx-1",
+ status: "DONE",
+ params: { statement: "SELECT 1", connection: { dataSourceId: "ds" } },
+ }) as unknown as SQLEditorDatabaseQueryContext;
+
+let container: HTMLDivElement;
+let root: ReturnType<typeof createRoot> | undefined;
+
+const render = () => {
+ container = document.createElement("div");
+ document.body.append(container);
+ const mounted = createRoot(container);
+ root = mounted;
+ act(() => {
+ mounted.render(<ResultPanel />);
+ });
+};
+
+beforeEach(() => {
+ document.body.innerHTML = "";
+ mocks.setResultPanelMaximized.mockClear();
+ mocks.state.resultPanelMaximized = false;
+ mocks.state.databaseQueryContexts = new Map();
+});
+
+afterEach(() => {
+ if (!root) return;
+ const mounted = root;
+ root = undefined;
+ act(() => {
+ mounted.unmount();
+ });
+});
+
+describe("ResultPanel maximized handoff", () => {
+ // Hiding every batch result behind the empty-results filter clears the
+ // selection while the stored contexts stay put — the strip and its control
+ // go, so counting contexts would leave a collapsed pane with no way out.
+ test("restores the editor when no result is selectable", () => {
+ mocks.state.resultPanelMaximized = true;
+ mocks.state.databaseQueryContexts = new Map([["db-1", [aContext()]]]);
+ render();
+
+ expect(mocks.setResultPanelMaximized).toHaveBeenCalledWith(false);
+ });
+
+ test("restores the editor once the tab holds no results", () => {
+ mocks.state.resultPanelMaximized = true;
+ render();
+
+ expect(mocks.setResultPanelMaximized).toHaveBeenCalledWith(false);
+ });
+
+ // Closing contexts one by one leaves the database key behind with an empty
+ // array, so a key alone does not mean there is a strip to restore from.
+ test("restores the editor when every database is emptied", () => {
+ mocks.state.resultPanelMaximized = true;
+ mocks.state.databaseQueryContexts = new Map([["db-1", []]]);
+ render();
+
+ expect(mocks.setResultPanelMaximized).toHaveBeenCalledWith(false);
+ });
+
+ test("leaves a docked pane alone", () => {
+ render();
+
+ expect(mocks.setResultPanelMaximized).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/modules/sql-editor/components/ResultPanel/ResultPanel.tsx b/frontend/src/modules/sql-editor/components/ResultPanel/ResultPanel.tsx
index 24867a6a4e..44ff1e59ac 100644
--- a/frontend/src/modules/sql-editor/components/ResultPanel/ResultPanel.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultPanel/ResultPanel.tsx
@@ -11,6 +11,7 @@ import {
import { Tabs, TabsList, TabsPanel, TabsTrigger } from "@/components/ui/tabs";
import { Tooltip } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
+import { useSQLEditorStore } from "@/modules/sql-editor/store";
import {
getSQLEditorTabsState,
useCurrentSQLEditorTab,
@@ -23,6 +24,7 @@ import type { Database } from "@/types/proto-es/v1/database_service_pb";
import { formatAbsoluteDateTime, getInstanceResource } from "@/utils";
import { BatchQuerySelect } from "./BatchQuerySelect";
import { DatabaseQueryContext } from "./DatabaseQueryContext";
+import { MaximizeToggle } from "./MaximizeToggle";
/**
* Hosts the batch-query database selector at the top, then a card-style
@@ -73,6 +75,23 @@ export function ResultPanel() {
const hasMultipleContexts = (queryContexts?.length ?? 0) > 1;
+ const showTabStrip =
+ selectedDatabase !== undefined && (queryContexts?.length ?? 0) > 0;
+ const resultPanelMaximized = useSQLEditorStore((s) => s.resultPanelMaximized);
+ const setResultPanelMaximized = useSQLEditorStore(
+ (s) => s.setResultPanelMaximized
+ );
+ // The maximize control lives in the tab strip, so whatever takes the strip
+ // away takes the only way back with it: closing the last result, or hiding
+ // every batch result behind the empty-results filter, which leaves stored
+ // contexts but nothing selectable. Hand the editor back instead of leaving
+ // it collapsed behind a pane with no control on it. The strip is also
+ // briefly absent while the selector picks a database, which costs nothing:
+ // maximizing does not survive a remount anyway.
+ useEffect(() => {
+ if (!showTabStrip && resultPanelMaximized) setResultPanelMaximized(false);
+ }, [showTabStrip, resultPanelMaximized, setResultPanelMaximized]);
+
// When the head of the contexts list changes, switch the active tab to
// it (newest run becomes selected).
const headId = queryContexts?.[0]?.id;
@@ -150,7 +169,7 @@ export function ResultPanel() {
onSelectedDatabaseChange={setSelectedDatabase}
/>
</div>
- {selectedDatabase && queryContexts && queryContexts.length > 0 && (
+ {showTabStrip && selectedDatabase && queryContexts && (
<Tabs
value={selectedTab ?? ""}
onValueChange={(v) => setSelectedTab(v as string)}
@@ -159,64 +178,67 @@ export function ResultPanel() {
isBatchQuery ? "pt-0" : "pt-2"
)}
>
- <TabsList className="shrink-0 gap-x-1 border-b border-control-border overflow-x-auto overflow-y-hidden">
- {queryContexts.map((context) => (
- // Order matters: `Tooltip` MUST wrap `TabContextMenu`, not the
- // other way around. `ContextMenuTrigger` uses Base UI's
- // `render` prop, which clones the given element and attaches
- // `onContextMenu` / `ref` to it — that only works when the
- // rendered element forwards unknown props onto its DOM
- // (`TabsTrigger` does, our `Tooltip` wrapper doesn't). With
- // Tooltip on the outside, the trigger renders `TabsTrigger`
- // directly and the right-click handler reaches the DOM.
- <Tooltip
- key={context.id}
- content={context.params.statement}
- popupClassName="ph-no-capture"
- >
- <TabContextMenu
- onSelect={(action) => {
- switch (action) {
- case "CLOSE":
- closeTab(context.id);
- break;
- case "CLOSE_OTHERS":
- closeOthers(context.id);
- break;
- case "CLOSE_TO_THE_RIGHT":
- closeToTheRight(context.id);
- break;
- case "CLOSE_ALL":
- closeAll();
- break;
- }
- }}
+ <div className="shrink-0 flex items-center gap-x-2 border-b border-control-border">
+ <TabsList className="min-w-0 flex-1 gap-x-1 overflow-x-auto overflow-y-hidden">
+ {queryContexts.map((context) => (
+ // Order matters: `Tooltip` MUST wrap `TabContextMenu`, not the
+ // other way around. `ContextMenuTrigger` uses Base UI's
+ // `render` prop, which clones the given element and attaches
+ // `onContextMenu` / `ref` to it — that only works when the
+ // rendered element forwards unknown props onto its DOM
+ // (`TabsTrigger` does, our `Tooltip` wrapper doesn't). With
+ // Tooltip on the outside, the trigger renders `TabsTrigger`
+ // directly and the right-click handler reaches the DOM.
+ <Tooltip
+ key={context.id}
+ content={context.params.statement}
+ popupClassName="ph-no-capture"
>
- <TabsTrigger
- value={context.id}
- className="flex items-center gap-x-2 px-3 py-1 shrink-0"
- >
- <span className="truncate">{tabName(context)}</span>
- {context.resultSet?.error && (
- <CircleAlert className="size-4 text-error shrink-0" />
- )}
- {context.status === "EXECUTING" && (
- <Loader2 className="size-3 animate-spin shrink-0" />
- )}
- {hasMultipleContexts && (
- <X
- className="size-4 text-control-light hover:text-control shrink-0"
- onClick={(e) => {
- e.stopPropagation();
+ <TabContextMenu
+ onSelect={(action) => {
+ switch (action) {
+ case "CLOSE":
closeTab(context.id);
- }}
- />
- )}
- </TabsTrigger>
- </TabContextMenu>
- </Tooltip>
- ))}
- </TabsList>
+ break;
+ case "CLOSE_OTHERS":
+ closeOthers(context.id);
+ break;
+ case "CLOSE_TO_THE_RIGHT":
+ closeToTheRight(context.id);
+ break;
+ case "CLOSE_ALL":
+ closeAll();
+ break;
+ }
+ }}
+ >
+ <TabsTrigger
+ value={context.id}
+ className="flex items-center gap-x-2 px-3 py-1 shrink-0"
+ >
+ <span className="truncate">{tabName(context)}</span>
+ {context.resultSet?.error && (
+ <CircleAlert className="size-4 text-error shrink-0" />
+ )}
+ {context.status === "EXECUTING" && (
+ <Loader2 className="size-3 animate-spin shrink-0" />
+ )}
+ {hasMultipleContexts && (
+ <X
+ className="size-4 text-control-light hover:text-control shrink-0"
+ onClick={(e) => {
+ e.stopPropagation();
+ closeTab(context.id);
+ }}
+ />
+ )}
+ </TabsTrigger>
+ </TabContextMenu>
+ </Tooltip>
+ ))}
+ </TabsList>
+ <MaximizeToggle />
+ </div>
{queryContexts.map((context, i) => (
<TabsPanel
key={context.id}
diff --git a/frontend/src/modules/sql-editor/components/SQLEditorHomePage.test.tsx b/frontend/src/modules/sql-editor/components/SQLEditorHomePage.test.tsx
index 13cb8146e4..f56faf3671 100644
--- a/frontend/src/modules/sql-editor/components/SQLEditorHomePage.test.tsx
+++ b/frontend/src/modules/sql-editor/components/SQLEditorHomePage.test.tsx
@@ -8,6 +8,10 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
setPendingInsertAtCaret: vi.fn(),
+ state: { resultPanelMaximized: false },
+ collapse: vi.fn(),
+ expand: vi.fn(),
+ separatorDisabled: undefined as boolean | undefined,
}));
vi.mock("react-i18next", () => ({
@@ -19,10 +23,22 @@ vi.mock("react-resizable-panels", () => ({
Group: ({ children }: { children: ReactElement | ReactElement[] }) => (
<div>{children}</div>
),
- Panel: ({ children }: { children: ReactElement | ReactElement[] }) => (
- <div>{children}</div>
- ),
- Separator: () => <div />,
+ Panel: ({
+ children,
+ panelRef,
+ }: {
+ children: ReactElement | ReactElement[];
+ panelRef?: { current: unknown };
+ }) => {
+ if (panelRef) {
+ panelRef.current = { collapse: mocks.collapse, expand: mocks.expand };
+ }
+ return <div>{children}</div>;
+ },
+ Separator: ({ disabled }: { disabled?: boolean }) => {
+ mocks.separatorDisabled = disabled;
+ return <div />;
+ },
}));
vi.mock("@/app/router", () => ({
@@ -93,7 +109,10 @@ vi.mock("@/modules/sql-editor/model/events", () => ({
vi.mock("@/modules/sql-editor/store", () => ({
useSQLEditorStore: (selector: (state: unknown) => unknown) =>
- selector({ setPendingInsertAtCaret: mocks.setPendingInsertAtCaret }),
+ selector({
+ setPendingInsertAtCaret: mocks.setPendingInsertAtCaret,
+ resultPanelMaximized: mocks.state.resultPanelMaximized,
+ }),
}));
vi.mock("@/modules/sql-editor/store/editor", () => ({
@@ -125,10 +144,22 @@ import { SQLEditorHomePage } from "./SQLEditorHomePage";
let container: HTMLDivElement;
let root: ReturnType<typeof createRoot>;
+const setWindowWidth = (width: number) => {
+ Object.defineProperty(window, "innerWidth", {
+ value: width,
+ configurable: true,
+ });
+};
+
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
+ setWindowWidth(1440);
+ mocks.state.resultPanelMaximized = false;
+ mocks.collapse.mockClear();
+ mocks.expand.mockClear();
+ mocks.separatorDisabled = undefined;
});
afterEach(() => {
@@ -147,3 +178,60 @@ describe("SQLEditorHomePage guide", () => {
expect(container.textContent).toContain("unified-guide");
});
});
+
+// The sidebar goes away for two unrelated reasons, and only a narrow window
+// wants the phone treatment: a floating toggle over a drawer. A maximized
+// result pane must not drag that onto a desktop window.
+describe("SQLEditorHomePage sidebar", () => {
+ const sidebarToggles = () =>
+ document.querySelectorAll(
+ 'button[aria-label="Expand sidebar"], button[aria-label="Collapse sidebar"]'
+ );
+ const sidebarDrawers = () =>
+ document.querySelectorAll('[role="dialog"][aria-label="Sidebar"]');
+
+ test("leaves the phone drawer out of a maximized desktop window", () => {
+ mocks.state.resultPanelMaximized = true;
+ render();
+
+ expect(sidebarToggles()).toHaveLength(0);
+ expect(sidebarDrawers()).toHaveLength(0);
+ });
+
+ test("keeps the phone toggle in a narrow window", () => {
+ setWindowWidth(600);
+ render();
+
+ expect(sidebarToggles()).toHaveLength(1);
+ });
+
+ // Dragging a collapsed sidebar open would leave the result pane short of the
+ // width its control still claims.
+ test("locks the sidebar separator while the pane is maximized", () => {
+ mocks.state.resultPanelMaximized = true;
+ render();
+
+ expect(mocks.separatorDisabled).toBe(true);
+ });
+
+ test("leaves the sidebar separator draggable while the pane is docked", () => {
+ render();
+
+ expect(mocks.separatorDisabled).toBe(false);
+ });
+
+ test("collapses the sidebar a maximized narrow window grows into", () => {
+ setWindowWidth(600);
+ mocks.state.resultPanelMaximized = true;
+ render();
+ // The desktop panel the collapse acts on does not exist while narrow.
+ expect(mocks.collapse).not.toHaveBeenCalled();
+
+ act(() => {
+ setWindowWidth(1440);
+ window.dispatchEvent(new Event("resize"));
+ });
+
+ expect(mocks.collapse).toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsx b/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsx
index c155cd6863..11f16a7cc9 100644
--- a/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsx
+++ b/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsx
@@ -1,10 +1,11 @@
import { ChevronLeft } from "lucide-react";
-import { useEffect, useState } from "react";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import {
Panel,
Group as PanelGroup,
+ type PanelImperativeHandle,
Separator as PanelResizeHandle,
} from "react-resizable-panels";
import { useNavigate } from "@/app/router";
@@ -86,7 +87,26 @@ export function SQLEditorHomePage() {
window.addEventListener("resize", handler);
return () => window.removeEventListener("resize", handler);
}, []);
- const hideSidebar = windowWidth < 800;
+ // Two separate reasons to give up the sidebar, and only one of them wants
+ // the phone treatment. A narrow window moves the tree into a drawer behind a
+ // floating toggle; a maximized result pane collapses it in place, so the
+ // tree keeps its scroll position and its dragged width for the trip back.
+ const isNarrowWindow = windowWidth < 800;
+ const collapseSidebar = useSQLEditorStore((s) => s.resultPanelMaximized);
+
+ const sidebarPanelRef = useRef<PanelImperativeHandle | null>(null);
+ // `isNarrowWindow` is a dependency because the panel it drives only exists on
+ // the desktop layout: widening the window past the breakpoint mounts a fresh
+ // panel that still has to be collapsed for a pane maximized while narrow.
+ useLayoutEffect(() => {
+ const panel = sidebarPanelRef.current;
+ if (!panel) return;
+ if (collapseSidebar) {
+ panel.collapse();
+ } else {
+ panel.expand();
+ }
+ }, [collapseSidebar, isNarrowWindow]);
const [sidebarExpanded, setSidebarExpanded] = useState(false);
@@ -156,7 +176,7 @@ export function SQLEditorHomePage() {
};
}, [setPendingInsertAtCaret]);
- const mobileToggle = hideSidebar
+ const mobileToggle = isNarrowWindow
? createPortal(
<SQLEditorThemeScope theme={theme} asContents>
<button
@@ -189,7 +209,7 @@ export function SQLEditorHomePage() {
<div className="sqleditor--wrapper w-full flex-1 overflow-hidden flex flex-col bg-background text-main">
<SQLEditorHeader />
{mobileToggle}
- {hideSidebar &&
+ {isNarrowWindow &&
sidebarExpanded &&
createPortal(
<SQLEditorThemeScope theme={theme} asContents>
@@ -214,14 +234,24 @@ export function SQLEditorHomePage() {
getLayerRoot("overlay")
)}
<PanelGroup orientation="horizontal" className="h-full">
- {!hideSidebar && (
+ {!isNarrowWindow && (
<>
- <Panel defaultSize="25%" minSize="10%" maxSize="40%">
+ <Panel
+ panelRef={sidebarPanelRef}
+ collapsible
+ collapsedSize="0%"
+ defaultSize="25%"
+ minSize="10%"
+ maxSize="40%"
+ >
<div className="h-full">
<AsidePanel />
</div>
</Panel>
+ {/* Dragging a collapsed sidebar back open would leave the result
+ pane short of the width its control still claims. */}
<PanelResizeHandle
+ disabled={collapseSidebar}
className={resizeHandleClass("vertical", "w-0.5")}
/>
</>
diff --git a/frontend/src/modules/sql-editor/components/StandardPanel/StandardPanel.test.tsx b/frontend/src/modules/sql-editor/components/StandardPanel/StandardPanel.test.tsx
new file mode 100644
index 0000000000..b36e1673c9
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/StandardPanel/StandardPanel.test.tsx
@@ -0,0 +1,226 @@
+import type { ReactElement, RefObject } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+type PanelHandle = { collapse: () => void; expand: () => void };
+
+const mocks = vi.hoisted(() => ({
+ collapse: vi.fn(),
+ expand: vi.fn(),
+ // The editor pane's `onResize`, captured so a test can replay the layout
+ // report the group sends on mount.
+ onEditorResize: undefined as
+ | ((size: { asPercentage: number }) => void)
+ | undefined,
+ separatorDisabled: undefined as boolean | undefined,
+ state: {
+ showAIPanel: false,
+ resultPanelSize: 0.4,
+ resultPanelMaximized: false,
+ disconnected: false,
+ setResultPanelMaximized: vi.fn(),
+ handleResultPanelResize: vi.fn(),
+ handleEditorPanelResize: vi.fn(),
+ setAsidePanelTab: vi.fn(),
+ setShowConnectionPanel: vi.fn(),
+ },
+}));
+
+vi.mock("react-resizable-panels", () => ({
+ Group: ({ children }: { children: ReactElement | ReactElement[] }) => (
+ <div>{children}</div>
+ ),
+ Panel: ({
+ children,
+ panelRef,
+ onResize,
+ }: {
+ children?: ReactElement | ReactElement[];
+ panelRef?: RefObject<PanelHandle | null>;
+ onResize?: (size: { asPercentage: number }) => void;
+ }) => {
+ if (panelRef) {
+ panelRef.current = { collapse: mocks.collapse, expand: mocks.expand };
+ mocks.onEditorResize = onResize;
+ }
+ return <div>{children}</div>;
+ },
+ Separator: ({ disabled }: { disabled?: boolean }) => {
+ mocks.separatorDisabled = disabled;
+ return <div />;
+ },
+}));
+
+vi.mock("@/modules/ai/components", () => ({
+ AIChatToSQL: () => <div />,
+ AIContextProvider: ({ children }: { children: ReactElement }) => children,
+}));
+
+vi.mock("@/modules/schema-editor/resize", () => ({
+ resizeHandleClass: () => "resize-handle",
+}));
+
+vi.mock("@/modules/sql-editor/components/ResultPanel/ResultPanel", () => ({
+ ResultPanel: () => <div>result-panel</div>,
+}));
+
+vi.mock("./EditorMain", () => ({
+ EditorMain: () => <div>editor-main</div>,
+}));
+
+vi.mock("@/modules/sql-editor/hooks/useSQLEditorState", () => ({
+ useConnectionOfCurrentSQLEditorTab: () => ({ instance: {} }),
+}));
+
+vi.mock("@/modules/sql-editor/store", () => ({
+ MINIMUM_RESULT_PANEL_SIZE: 0.2,
+ MAXIMUM_RESULT_PANEL_SIZE: 0.8,
+ selectEditorPanelSize: () => ({ size: 1, min: 0.5, max: 1 }),
+ useSQLEditorStore: Object.assign(
+ (selector: (state: typeof mocks.state) => unknown) =>
+ selector(mocks.state),
+ { getState: () => mocks.state }
+ ),
+}));
+
+vi.mock("@/modules/sql-editor/store/tab", () => ({
+ useCurrentSQLEditorTab: () => ({ id: "tab-1", mode: "SAVED_QUERY" }),
+ useIsDisconnected: () => mocks.state.disconnected,
+}));
+
+vi.mock("@/utils", () => ({
+ instanceV1HasReadonlyMode: () => true,
+}));
+
+import { StandardPanel } from "./StandardPanel";
+
+let container: HTMLDivElement;
+let root: ReturnType<typeof createRoot> | undefined;
+
+const render = () => {
+ container = document.createElement("div");
+ document.body.append(container);
+ const mounted = createRoot(container);
+ root = mounted;
+ act(() => {
+ mounted.render(<StandardPanel />);
+ });
+};
+
+beforeEach(() => {
+ document.body.innerHTML = "";
+ mocks.collapse.mockClear();
+ mocks.expand.mockClear();
+ mocks.onEditorResize = undefined;
+ mocks.state.showAIPanel = false;
+ mocks.state.resultPanelSize = 0.4;
+ mocks.state.resultPanelMaximized = false;
+ mocks.state.disconnected = false;
+ mocks.state.setResultPanelMaximized.mockClear();
+ mocks.state.handleResultPanelResize.mockClear();
+ mocks.separatorDisabled = undefined;
+});
+
+afterEach(() => {
+ if (!root) return;
+ const mounted = root;
+ root = undefined;
+ act(() => {
+ mounted.unmount();
+ });
+});
+
+describe("StandardPanel result pane", () => {
+ test("collapses the editor while the result pane is maximized", () => {
+ mocks.state.resultPanelMaximized = true;
+ render();
+
+ expect(mocks.collapse).toHaveBeenCalled();
+ expect(mocks.expand).not.toHaveBeenCalled();
+ });
+
+ test("expands the editor while the result pane is docked", () => {
+ render();
+
+ expect(mocks.expand).toHaveBeenCalled();
+ expect(mocks.collapse).not.toHaveBeenCalled();
+ });
+
+ // The group reports its default layout once on mount, before the collapse
+ // lands. Reading "maximized" back out of that report cancelled it on every
+ // remount — and the panel remounts on each tab switch.
+ test("keeps a maximized pane through the group's first layout report", () => {
+ mocks.state.resultPanelMaximized = true;
+ render();
+
+ act(() => {
+ mocks.onEditorResize?.({ asPercentage: 60 });
+ });
+
+ expect(mocks.state.setResultPanelMaximized).not.toHaveBeenCalled();
+ });
+
+ test("reports the result pane's share of a resize", () => {
+ render();
+
+ act(() => {
+ mocks.onEditorResize?.({ asPercentage: 75 });
+ });
+
+ expect(mocks.state.handleResultPanelResize).toHaveBeenCalledWith(0.25);
+ });
+
+ test("ignores a resize that reports no usable size", () => {
+ render();
+
+ act(() => {
+ mocks.onEditorResize?.({ asPercentage: Number.NaN });
+ });
+
+ expect(mocks.state.handleResultPanelResize).not.toHaveBeenCalled();
+ });
+
+ // Maximizing lasts as long as the pane it belongs to: no result pane means
+ // no restore control, so the state cannot outlive it.
+ test("clears a maximized pane once the connection is gone", () => {
+ mocks.state.disconnected = true;
+ mocks.state.resultPanelMaximized = true;
+ render();
+
+ expect(mocks.state.setResultPanelMaximized).toHaveBeenCalledWith(false);
+ });
+
+ test("clears a maximized pane on unmount", () => {
+ mocks.state.resultPanelMaximized = true;
+ render();
+ expect(mocks.state.setResultPanelMaximized).not.toHaveBeenCalled();
+
+ const mounted = root;
+ root = undefined;
+ act(() => {
+ mounted?.unmount();
+ });
+
+ expect(mocks.state.setResultPanelMaximized).toHaveBeenCalledWith(false);
+ });
+
+ // Dragging back to a half-state would leave the editor visible under a
+ // sidebar that is still hidden.
+ test("locks the separator while the pane is maximized", () => {
+ mocks.state.resultPanelMaximized = true;
+ render();
+
+ expect(mocks.separatorDisabled).toBe(true);
+ });
+
+ test("leaves the separator draggable while the pane is docked", () => {
+ render();
+
+ expect(mocks.separatorDisabled).toBe(false);
+ });
+});
diff --git a/frontend/src/modules/sql-editor/components/StandardPanel/StandardPanel.tsx b/frontend/src/modules/sql-editor/components/StandardPanel/StandardPanel.tsx
index 391fc2f968..fbebebfceb 100644
--- a/frontend/src/modules/sql-editor/components/StandardPanel/StandardPanel.tsx
+++ b/frontend/src/modules/sql-editor/components/StandardPanel/StandardPanel.tsx
@@ -1,8 +1,10 @@
import { Loader2 } from "lucide-react";
-import { Suspense } from "react";
+import type { ReactNode } from "react";
+import { Suspense, useEffect, useLayoutEffect, useRef, useState } from "react";
import {
Panel,
Group as PanelGroup,
+ type PanelImperativeHandle,
Separator as PanelResizeHandle,
} from "react-resizable-panels";
import { useShallow } from "zustand/react/shallow";
@@ -11,6 +13,8 @@ import { resizeHandleClass } from "@/modules/schema-editor/resize";
import { ResultPanel } from "@/modules/sql-editor/components/ResultPanel/ResultPanel";
import { useConnectionOfCurrentSQLEditorTab } from "@/modules/sql-editor/hooks/useSQLEditorState";
import {
+ MAXIMUM_RESULT_PANEL_SIZE,
+ MINIMUM_RESULT_PANEL_SIZE,
selectEditorPanelSize,
useSQLEditorStore,
} from "@/modules/sql-editor/store";
@@ -21,6 +25,9 @@ import {
import { instanceV1HasReadonlyMode } from "@/utils";
import { EditorMain } from "./EditorMain";
+/** Panel sizes are CSS percentages; round so 1 - 0.8 reads as "20%". */
+const percent = (fraction: number) => `${Math.round(fraction * 1000) / 10}%`;
+
const AIPaneFallback = () => (
<div className="w-full h-full grow flex flex-col items-center justify-center">
<Loader2 className="size-6 animate-spin text-control-light" />
@@ -56,14 +63,29 @@ export function StandardPanel() {
const isDisconnected = useIsDisconnected();
const showAIPanel = useSQLEditorStore((s) => s.showAIPanel);
const editorPanelSize = useSQLEditorStore(useShallow(selectEditorPanelSize));
+ const setResultPanelMaximized = useSQLEditorStore(
+ (s) => s.setResultPanelMaximized
+ );
const instanceHasReadonly = instanceV1HasReadonlyMode(instance);
+ // Derived above the early return below so the effect stays unconditional.
+ const isSavedQueryTab = !tab || tab.mode === "SAVED_QUERY";
+ const showResultPanel =
+ isSavedQueryTab && !isDisconnected && instanceHasReadonly;
+
+ // Maximizing is a momentary view of one result, not a remembered preference:
+ // it lasts as long as the pane it belongs to. Switching tabs remounts this
+ // component and losing the connection takes the pane away; either would
+ // otherwise leave a collapsed editor and a hidden sidebar with no control on
+ // screen to undo them.
+ useEffect(() => {
+ if (!showResultPanel) setResultPanelMaximized(false);
+ return () => setResultPanelMaximized(false);
+ }, [showResultPanel, setResultPanelMaximized]);
- if (tab && tab.mode !== "SAVED_QUERY") {
+ if (!isSavedQueryTab) {
return null;
}
- const showResultPanel = !isDisconnected && instanceHasReadonly;
-
const handleAiPanelResize = (sizePct: number) => {
// react-resizable-panels reports a `PanelSize` struct
// ({ asPercentage, inPixels }) on resize. The store keeps a 0-1
@@ -119,13 +141,74 @@ export function StandardPanel() {
return <div className="h-full">{editorWithAi}</div>;
}
+ return <EditorResultSplit>{editorWithAi}</EditorResultSplit>;
+}
+
+/**
+ * The editor / result split.
+ *
+ * Owns the remembered height, read once when this group mounts rather than
+ * when `StandardPanel` does: the group alone comes and goes with the
+ * connection, and a height dragged before it went away is the one to come
+ * back to. Reading it live instead would feed `defaultSize` a new value on
+ * every frame of a drag.
+ */
+function EditorResultSplit({ children }: { children: ReactNode }) {
+ const [initialResultPanelSize] = useState(
+ () => useSQLEditorStore.getState().resultPanelSize
+ );
+ const resultPanelMaximized = useSQLEditorStore((s) => s.resultPanelMaximized);
+ const handleResultPanelResize = useSQLEditorStore(
+ (s) => s.handleResultPanelResize
+ );
+ // The editor pane is collapsed rather than unmounted, so Monaco keeps its
+ // cursor, scroll and undo history while the result pane is maximized.
+ const editorPanelRef = useRef<PanelImperativeHandle | null>(null);
+
+ // Before paint, so a group that mounts maximized never shows the editor for
+ // a frame first.
+ useLayoutEffect(() => {
+ const panel = editorPanelRef.current;
+ if (!panel) return;
+ if (resultPanelMaximized) {
+ panel.collapse();
+ } else {
+ panel.expand();
+ }
+ }, [resultPanelMaximized]);
+
return (
<PanelGroup orientation="vertical" className="h-full">
- <Panel defaultSize="60%" minSize="20%" maxSize="80%">
- {editorWithAi}
+ <Panel
+ panelRef={editorPanelRef}
+ collapsible
+ collapsedSize="0%"
+ defaultSize={percent(1 - initialResultPanelSize)}
+ minSize={percent(1 - MAXIMUM_RESULT_PANEL_SIZE)}
+ maxSize={percent(1 - MINIMUM_RESULT_PANEL_SIZE)}
+ onResize={(size) => {
+ const editorShare = size.asPercentage / 100;
+ if (!Number.isFinite(editorShare)) return;
+ // Height only. Whether the pane is maximized is the reader's
+ // decision, taken through the toggle: deriving it from the layout
+ // would let the group's first report — the default size, sent
+ // before the effect above can collapse — cancel it on every mount.
+ handleResultPanelResize(1 - editorShare);
+ }}
+ >
+ {children}
</Panel>
- <PanelResizeHandle className={resizeHandleClass("horizontal", "h-0.5")} />
- <Panel defaultSize="40%" minSize="20%">
+ {/* A maximized pane owns the whole area; dragging it back to a
+ half-state would leave the editor visible under a sidebar that is
+ still hidden. Restore first. */}
+ <PanelResizeHandle
+ disabled={resultPanelMaximized}
+ className={resizeHandleClass("horizontal", "h-0.5")}
+ />
+ <Panel
+ defaultSize={percent(initialResultPanelSize)}
+ minSize={percent(MINIMUM_RESULT_PANEL_SIZE)}
+ >
<div className="relative h-full">
<ResultPanel />
</div>
diff --git a/frontend/src/modules/sql-editor/store/index.ts b/frontend/src/modules/sql-editor/store/index.ts
index 9759d7fef2..49a8afe745 100644
--- a/frontend/src/modules/sql-editor/store/index.ts
+++ b/frontend/src/modules/sql-editor/store/index.ts
@@ -17,7 +17,11 @@ export {
selectQueryHistoryEntry,
} from "./queryHistory";
export { idForSQLEditorTreeNodeTarget, selectAllTreeNodeKeys } from "./tree";
-export { selectEditorPanelSize } from "./uiState";
+export {
+ MAXIMUM_RESULT_PANEL_SIZE,
+ MINIMUM_RESULT_PANEL_SIZE,
+ selectEditorPanelSize,
+} from "./uiState";
export { createWebTerminalQueryItemV1 } from "./webTerminal";
export const useSQLEditorStore = create<SQLEditorStoreState>()((...args) => ({
diff --git a/frontend/src/modules/sql-editor/store/queryHistory.test.ts b/frontend/src/modules/sql-editor/store/queryHistory.test.ts
index 056d832c87..a968de83f1 100644
--- a/frontend/src/modules/sql-editor/store/queryHistory.test.ts
+++ b/frontend/src/modules/sql-editor/store/queryHistory.test.ts
@@ -37,6 +37,8 @@ const stubUIStateSlice = (): UIStateSlice => ({
highlightAccessGrantName: undefined,
isShowingCode: false,
aiPanelSize: 0.3,
+ resultPanelSize: 0.4,
+ resultPanelMaximized: false,
linkedQueryHistory: undefined,
linkedQueryHistoryTabId: undefined,
linkedQueryHistoryBaseline: undefined,
@@ -48,6 +50,8 @@ const stubUIStateSlice = (): UIStateSlice => ({
setHighlightAccessGrantName: vi.fn(),
setIsShowingCode: vi.fn(),
handleEditorPanelResize: vi.fn(),
+ setResultPanelMaximized: vi.fn(),
+ handleResultPanelResize: vi.fn(),
});
const stubTreeSlice = (): TreeSlice => ({
diff --git a/frontend/src/modules/sql-editor/store/savedQuery.test.ts b/frontend/src/modules/sql-editor/store/savedQuery.test.ts
index 775a35d272..6f133e5e33 100644
--- a/frontend/src/modules/sql-editor/store/savedQuery.test.ts
+++ b/frontend/src/modules/sql-editor/store/savedQuery.test.ts
@@ -22,6 +22,8 @@ const stubUIStateSlice = (): UIStateSlice => ({
highlightAccessGrantName: undefined,
isShowingCode: false,
aiPanelSize: 0.3,
+ resultPanelSize: 0.4,
+ resultPanelMaximized: false,
linkedQueryHistory: undefined,
linkedQueryHistoryTabId: undefined,
linkedQueryHistoryBaseline: undefined,
@@ -33,6 +35,8 @@ const stubUIStateSlice = (): UIStateSlice => ({
setHighlightAccessGrantName: vi.fn(),
setIsShowingCode: vi.fn(),
handleEditorPanelResize: vi.fn(),
+ setResultPanelMaximized: vi.fn(),
+ handleResultPanelResize: vi.fn(),
});
const stubQueryHistorySlice = (): QueryHistorySlice => ({
diff --git a/frontend/src/modules/sql-editor/store/types.ts b/frontend/src/modules/sql-editor/store/types.ts
index 959238d17d..ba8a28728c 100644
--- a/frontend/src/modules/sql-editor/store/types.ts
+++ b/frontend/src/modules/sql-editor/store/types.ts
@@ -27,6 +27,13 @@ export interface UIStateSlice {
// Persisted fraction of the editor width given to the AI side pane when it
// is shown. Stored in localStorage and re-read on store creation.
aiPanelSize: number;
+ // Persisted fraction of the editor height given to the result pane, so a
+ // reader who drags it taller keeps that height on the next query.
+ resultPanelSize: number;
+ // True while the result pane fills the editor: the editor pane is collapsed
+ // and the sidebar is hidden, giving rows and plans the whole area. Momentary
+ // — `StandardPanel` clears it when the pane it belongs to goes away.
+ resultPanelMaximized: boolean;
// The query history opened from a deep link this session. Surfaced as the
// "Opened from link" section atop the history pane until dismissed or until
// its draft tab is edited.
@@ -48,6 +55,8 @@ export interface UIStateSlice {
setHighlightAccessGrantName: (value: string | undefined) => void;
setIsShowingCode: (value: boolean) => void;
handleEditorPanelResize: (size: number) => void;
+ setResultPanelMaximized: (value: boolean) => void;
+ handleResultPanelResize: (size: number) => void;
}
export interface QueryHistoryFilter {
diff --git a/frontend/src/modules/sql-editor/store/uiState.test.ts b/frontend/src/modules/sql-editor/store/uiState.test.ts
index 80e256b403..273ce317cd 100644
--- a/frontend/src/modules/sql-editor/store/uiState.test.ts
+++ b/frontend/src/modules/sql-editor/store/uiState.test.ts
@@ -1,7 +1,10 @@
// @vitest-environment node
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { create, type StoreApi } from "zustand";
-import { STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE } from "@/utils/storage-keys";
+import {
+ STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE,
+ STORAGE_KEY_SQL_EDITOR_RESULT_PANEL_SIZE,
+} from "@/utils/storage-keys";
import type {
QueryHistorySlice,
SavedQuerySaveSlice,
@@ -115,6 +118,77 @@ describe("sqlEditor uiState slice", () => {
expect(s.highlightAccessGrantName).toBeUndefined();
expect(s.isShowingCode).toBe(false);
expect(s.aiPanelSize).toBe(0.3);
+ expect(s.resultPanelSize).toBe(0.4);
+ expect(s.resultPanelMaximized).toBe(false);
+ });
+
+ test("resultPanelSize reads the persisted height", async () => {
+ localStorage.setItem(
+ STORAGE_KEY_SQL_EDITOR_RESULT_PANEL_SIZE,
+ JSON.stringify(0.65)
+ );
+ const useStore = await makeStore();
+ expect(useStore.getState().resultPanelSize).toBe(0.65);
+ });
+
+ test("resultPanelSize clamps a persisted height to the drag range", async () => {
+ localStorage.setItem(
+ STORAGE_KEY_SQL_EDITOR_RESULT_PANEL_SIZE,
+ JSON.stringify(0.95)
+ );
+ const useStore = await makeStore();
+ expect(useStore.getState().resultPanelSize).toBe(0.8);
+ });
+
+ test("handleResultPanelResize persists the height a drag settles on", async () => {
+ const useStore = await makeStore();
+ vi.useFakeTimers();
+ try {
+ // A drag reports every frame; only the last size reaches storage.
+ for (const size of [0.5, 0.52, 0.55]) {
+ useStore.getState().handleResultPanelResize(size);
+ }
+ expect(useStore.getState().resultPanelSize).toBe(0.55);
+ expect(
+ localStorage.getItem(STORAGE_KEY_SQL_EDITOR_RESULT_PANEL_SIZE)
+ ).toBeNull();
+
+ vi.runAllTimers();
+ expect(
+ localStorage.getItem(STORAGE_KEY_SQL_EDITOR_RESULT_PANEL_SIZE)
+ ).toBe(JSON.stringify(0.55));
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test("handleResultPanelResize ignores a maximized or collapsed pane", async () => {
+ const useStore = await makeStore();
+ vi.useFakeTimers();
+ try {
+ useStore.getState().handleResultPanelResize(0.55);
+ for (const size of [1, 0, Number.NaN]) {
+ useStore.getState().handleResultPanelResize(size);
+ expect(useStore.getState().resultPanelSize).toBe(0.55);
+ }
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test("setResultPanelMaximized toggles without touching the remembered height", async () => {
+ const useStore = await makeStore();
+ vi.useFakeTimers();
+ try {
+ useStore.getState().handleResultPanelResize(0.55);
+ useStore.getState().setResultPanelMaximized(true);
+ expect(useStore.getState().resultPanelMaximized).toBe(true);
+ expect(useStore.getState().resultPanelSize).toBe(0.55);
+ useStore.getState().setResultPanelMaximized(false);
+ expect(useStore.getState().resultPanelMaximized).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
});
test("selectEditorPanelSize returns full-width when AI panel is hidden", async () => {
diff --git a/frontend/src/modules/sql-editor/store/uiState.ts b/frontend/src/modules/sql-editor/store/uiState.ts
index e0f4210751..d121e8677a 100644
--- a/frontend/src/modules/sql-editor/store/uiState.ts
+++ b/frontend/src/modules/sql-editor/store/uiState.ts
@@ -1,9 +1,26 @@
-import { STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE } from "@/utils/storage-keys";
+import {
+ STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE,
+ STORAGE_KEY_SQL_EDITOR_RESULT_PANEL_SIZE,
+} from "@/utils/storage-keys";
import type { SQLEditorSliceCreator, UIStateSlice } from "./types";
const MINIMUM_EDITOR_PANEL_SIZE = 0.5;
const DEFAULT_AI_PANEL_SIZE = 0.3;
+const DEFAULT_RESULT_PANEL_SIZE = 0.4;
+/**
+ * The drag range of the result pane. `StandardPanel` derives the panel's
+ * `minSize` / `maxSize` from these, so the clamp and the layout cannot drift.
+ */
+export const MINIMUM_RESULT_PANEL_SIZE = 0.2;
+export const MAXIMUM_RESULT_PANEL_SIZE = 0.8;
+
+const clampResultPanelSize = (size: number): number =>
+ Math.min(
+ Math.max(size, MINIMUM_RESULT_PANEL_SIZE),
+ MAXIMUM_RESULT_PANEL_SIZE
+ );
+
const readAIPanelSize = (): number => {
try {
const raw = localStorage.getItem(STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE);
@@ -28,6 +45,47 @@ const writeAIPanelSize = (size: number) => {
}
};
+const readResultPanelSize = (): number => {
+ try {
+ const raw = localStorage.getItem(STORAGE_KEY_SQL_EDITOR_RESULT_PANEL_SIZE);
+ if (raw !== null) {
+ const parsed = JSON.parse(raw);
+ if (typeof parsed === "number" && Number.isFinite(parsed)) {
+ return clampResultPanelSize(parsed);
+ }
+ }
+ } catch {
+ // ignore — fall back to default
+ }
+ return DEFAULT_RESULT_PANEL_SIZE;
+};
+
+const writeResultPanelSize = (size: number) => {
+ try {
+ localStorage.setItem(
+ STORAGE_KEY_SQL_EDITOR_RESULT_PANEL_SIZE,
+ JSON.stringify(size)
+ );
+ } catch {
+ // ignore
+ }
+};
+
+// A drag reports a new size every frame; only the one it settles on is worth
+// a synchronous storage write.
+const RESULT_PANEL_SIZE_WRITE_DELAY_MS = 200;
+let resultPanelSizeWriteTimer: ReturnType<typeof setTimeout> | undefined;
+
+const scheduleResultPanelSizeWrite = (size: number) => {
+ if (resultPanelSizeWriteTimer !== undefined) {
+ clearTimeout(resultPanelSizeWriteTimer);
+ }
+ resultPanelSizeWriteTimer = setTimeout(() => {
+ resultPanelSizeWriteTimer = undefined;
+ writeResultPanelSize(size);
+ }, RESULT_PANEL_SIZE_WRITE_DELAY_MS);
+};
+
export const createUIStateSlice: SQLEditorSliceCreator<UIStateSlice> = (
set
) => ({
@@ -38,6 +96,8 @@ export const createUIStateSlice: SQLEditorSliceCreator<UIStateSlice> = (
highlightAccessGrantName: undefined,
isShowingCode: false,
aiPanelSize: readAIPanelSize(),
+ resultPanelSize: readResultPanelSize(),
+ resultPanelMaximized: false,
linkedQueryHistory: undefined,
linkedQueryHistoryTabId: undefined,
linkedQueryHistoryBaseline: undefined,
@@ -60,6 +120,16 @@ export const createUIStateSlice: SQLEditorSliceCreator<UIStateSlice> = (
writeAIPanelSize(next);
set({ aiPanelSize: next });
},
+ setResultPanelMaximized: (value) => set({ resultPanelMaximized: value }),
+ // Only a size the reader dragged is worth keeping. A maximized pane reports
+ // the full height and a collapsed one reports nothing, so both are ignored
+ // rather than written over the remembered height.
+ handleResultPanelResize: (size) => {
+ if (!Number.isFinite(size) || size <= 0 || size >= 1) return;
+ const next = clampResultPanelSize(size);
+ scheduleResultPanelSizeWrite(next);
+ set({ resultPanelSize: next });
+ },
});
export const selectEditorPanelSize = (
diff --git a/frontend/src/utils/storage-keys.ts b/frontend/src/utils/storage-keys.ts
index ba20f1268b..d2db446031 100644
--- a/frontend/src/utils/storage-keys.ts
+++ b/frontend/src/utils/storage-keys.ts
@@ -31,6 +31,8 @@ export const STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT = "bb.sql-editor.result-limit";
export const STORAGE_KEY_SQL_EDITOR_REDIS_NODE = "bb.sql-editor.redis-node";
export const STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE =
"bb.sql-editor.ai-panel-size";
+export const STORAGE_KEY_SQL_EDITOR_RESULT_PANEL_SIZE =
+ "bb.sql-editor.result-panel-size";
export const STORAGE_KEY_SQL_EDITOR_SIDEBAR_TAB =
"bb.sql-editor.sidebar.last-visited-tab";
export const storageKeySqlEditorSidebarTab = (project: string) =>