Skip to content

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

fix(schema-diagram): fit the laid-out tables when the diagram opens (#21698)

zchpeter931033593de8
diff --git a/frontend/src/modules/schema-diagram/Canvas/hooks/useFitView.tsx b/frontend/src/modules/schema-diagram/Canvas/hooks/useFitView.tsx
index 9ae79579be..b4bef1eda2 100644
--- a/frontend/src/modules/schema-diagram/Canvas/hooks/useFitView.tsx
+++ b/frontend/src/modules/schema-diagram/Canvas/hooks/useFitView.tsx
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useRef } from "react";
import { DEFAULT_PADDINGS, ZOOM_RANGE } from "../../common/const";
import { useSchemaDiagramContext } from "../../common/context";
+import type { Geometry } from "../../types";
import { fitView } from "../libs/fitView";
/**
@@ -13,22 +14,29 @@ export const useFitView = (canvas: Element | null) => {
const ctx = useSchemaDiagramContext();
const { setZoom, setPosition, geometries, events } = ctx;
+ const fitTo = useCallback(
+ (targets: Geometry[]) => {
+ if (!canvas) return;
+ const layout = fitView(canvas, targets, DEFAULT_PADDINGS, [
+ ZOOM_RANGE.min,
+ 1.0,
+ ]);
+ setZoom(layout.zoom);
+ setPosition({ x: layout.rect.x, y: layout.rect.y });
+ },
+ [canvas, setZoom, setPosition]
+ );
+
const handleFitView = useCallback(() => {
- if (!canvas) return;
- const layout = fitView(canvas, [...geometries], DEFAULT_PADDINGS, [
- ZOOM_RANGE.min,
- 1.0,
- ]);
- setZoom(layout.zoom);
- setPosition({ x: layout.rect.x, y: layout.rect.y });
- }, [canvas, geometries, setZoom, setPosition]);
+ fitTo([...geometries]);
+ }, [fitTo, geometries]);
- const handleFitViewRef = useRef(handleFitView);
- handleFitViewRef.current = handleFitView;
+ const fitToRef = useRef(fitTo);
+ fitToRef.current = fitTo;
useEffect(() => {
- const off = events.on("fit-view", () => {
- handleFitViewRef.current();
+ const off = events.on("fit-view", ({ data }) => {
+ fitToRef.current(data.geometries);
});
return () => {
off();
diff --git a/frontend/src/modules/schema-diagram/SchemaDiagram.test.tsx b/frontend/src/modules/schema-diagram/SchemaDiagram.test.tsx
new file mode 100644
index 0000000000..6e269929ae
--- /dev/null
+++ b/frontend/src/modules/schema-diagram/SchemaDiagram.test.tsx
@@ -0,0 +1,155 @@
+import { create } from "@bufbuild/protobuf";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ ColumnMetadataSchema,
+ DatabaseMetadataSchema,
+ DatabaseSchema$,
+ SchemaMetadataSchema,
+ TableMetadataSchema,
+} from "@/types/proto-es/v1/database_service_pb";
+import type { Layout } from "./ER/libs/autoLayout";
+import { SchemaDiagram } from "./SchemaDiagram";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const autoLayoutMock = vi.fn<(...args: unknown[]) => Promise<Layout>>();
+
+vi.mock("./ER/libs/autoLayout/index", async (importOriginal) => {
+ const orig =
+ await importOriginal<typeof import("./ER/libs/autoLayout/index")>();
+ return {
+ ...orig,
+ autoLayout: (...args: unknown[]) => autoLayoutMock(...args),
+ };
+});
+
+vi.mock("./Navigator/Navigator", () => ({ Navigator: () => null }));
+
+const CANVAS = { width: 1000, height: 600 };
+
+const TABLE_RECTS = new Map([
+ ["t0", { x: 0, y: 0, width: 256, height: 150 }],
+ ["t1", { x: 900, y: 0, width: 256, height: 150 }],
+ ["t2", { x: 1800, y: 400, width: 256, height: 150 }],
+]);
+
+const makeMetadata = () =>
+ create(DatabaseMetadataSchema, {
+ name: "instances/i/databases/db/metadata",
+ schemas: [
+ create(SchemaMetadataSchema, {
+ name: "public",
+ tables: ["users", "orders", "items"].map((name) =>
+ create(TableMetadataSchema, {
+ name,
+ columns: [create(ColumnMetadataSchema, { name: "id" })],
+ })
+ ),
+ }),
+ ],
+ });
+
+const desktopTransform = (container: HTMLElement) => {
+ const desktop = Array.from(container.querySelectorAll("div")).find((el) =>
+ el.style.transform.startsWith("matrix(")
+ );
+ const [zoom, , , , x, y] = (desktop?.style.transform ?? "")
+ .slice("matrix(".length, -1)
+ .split(",")
+ .map(Number);
+ return { zoom, x, y };
+};
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ autoLayoutMock.mockReset();
+ vi.spyOn(Element.prototype, "getBoundingClientRect").mockReturnValue(
+ DOMRect.fromRect(CANVAS)
+ );
+ // A synchronous frame callback reaches fit-view before React commits
+ // the laid-out rects, the timing that loses the race on a slow host.
+ vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {
+ cb(0);
+ return 0;
+ });
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+const mountDiagram = async () => {
+ autoLayoutMock.mockImplementation(async (nodes) => ({
+ rects: new Map(
+ (nodes as { id: string }[]).map(({ id }, i) => [
+ id,
+ TABLE_RECTS.get(`t${i}`)!,
+ ])
+ ),
+ paths: new Map(),
+ }));
+
+ await act(async () => {
+ root.render(
+ <SchemaDiagram
+ database={create(DatabaseSchema$, {
+ name: "instances/i/databases/db",
+ })}
+ databaseMetadata={makeMetadata()}
+ />
+ );
+ });
+ expect(autoLayoutMock).toHaveBeenCalled();
+};
+
+const expectEveryTableInCanvas = () => {
+ const { zoom, x, y } = desktopTransform(container);
+ expect(zoom).toBeLessThan(1);
+ for (const rect of TABLE_RECTS.values()) {
+ expect(x + rect.x * zoom).toBeGreaterThanOrEqual(0);
+ expect(y + rect.y * zoom).toBeGreaterThanOrEqual(0);
+ expect(x + (rect.x + rect.width) * zoom).toBeLessThanOrEqual(CANVAS.width);
+ expect(y + (rect.y + rect.height) * zoom).toBeLessThanOrEqual(
+ CANVAS.height
+ );
+ }
+};
+
+const click = (label: string) => {
+ const button = container.querySelector<HTMLButtonElement>(
+ `button[aria-label="${label}"]`
+ );
+ expect(button).not.toBeNull();
+ act(() => button!.click());
+};
+
+describe("SchemaDiagram", () => {
+ it("fits every laid-out table into the canvas on mount", async () => {
+ await mountDiagram();
+ expectEveryTableInCanvas();
+ });
+
+ it("fits every table again from the fit button after zooming", async () => {
+ await mountDiagram();
+ const fitted = desktopTransform(container);
+
+ click("Zoom out");
+ expect(desktopTransform(container).zoom).toBeLessThan(fitted.zoom);
+
+ click("Fit content within view");
+ expect(desktopTransform(container)).toEqual(fitted);
+ expectEveryTableInCanvas();
+ });
+});
diff --git a/frontend/src/modules/schema-diagram/SchemaDiagram.tsx b/frontend/src/modules/schema-diagram/SchemaDiagram.tsx
index 80eabc0833..d838bed170 100644
--- a/frontend/src/modules/schema-diagram/SchemaDiagram.tsx
+++ b/frontend/src/modules/schema-diagram/SchemaDiagram.tsx
@@ -147,7 +147,7 @@ function Body({ databaseName, onEditTable, onEditColumn }: BodyProps) {
mergeTableRects(rects);
setInitialized(true);
requestAnimationFrame(() => {
- void events.emit("fit-view");
+ void events.emit("fit-view", { geometries: [...rects.values()] });
void events.emit("render");
});
}, [runLayout, mergeTableRects, setFocusedTables, events]);
diff --git a/frontend/src/modules/schema-diagram/types/context.ts b/frontend/src/modules/schema-diagram/types/context.ts
index e6f269217a..c44874c8c5 100644
--- a/frontend/src/modules/schema-diagram/types/context.ts
+++ b/frontend/src/modules/schema-diagram/types/context.ts
@@ -81,7 +81,9 @@ export type SchemaDiagramContext = {
export type SchemaDiagramEvents = {
render: undefined;
layout: undefined;
- "fit-view": undefined;
+ // Carries the laid-out rects: the table nodes register them only after
+ // React commits, which can be later than the fit.
+ "fit-view": { geometries: Geometry[] };
"edit-table": { schema: SchemaMetadata; table: TableMetadata };
"edit-column": {
schema: SchemaMetadata;
diff --git a/frontend/tests/e2e/sql-editor/sql-editor-schema.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-schema.spec.ts
index f2dcb36e49..fdc9988f9c 100644
--- a/frontend/tests/e2e/sql-editor/sql-editor-schema.spec.ts
+++ b/frontend/tests/e2e/sql-editor/sql-editor-schema.spec.ts
@@ -30,22 +30,10 @@ test.afterAll(async () => {
});
test.describe("Schema Diagram fits all table cards into the viewport on mount", () => {
- // BYT-9481: the schema diagram is mounted with no auto-fit applied,
- // so most table cards land off-screen on a wide virtual canvas. The
- // user sees one or two cards on the left and assumes the diagram is
- // empty or broken — they must zoom out manually to discover the rest.
- //
- // Bug evidence: .playwright-cli/qa-session-2026-05-12/r42-byt9481-schema-diagram/
- // - 02-card-positions.txt (DOM-measured card positions, only 1 of N visible)
- // - 01-schema-diagram-full-view.png
+ // BYT-9481, BYT-10363: without a fit on mount, most table cards land
+ // off-screen and the diagram looks empty.
test("every table card lands inside the viewport at default zoom", async () => {
- // BYT-9481 is queued as not-high-priority. The fix is flaky on
- // main — auto-fit sometimes runs early enough to land all cards
- // in view, often it doesn't. Mark expected-fail so the suite
- // stays green; a real fix will surface as "Expected to fail, but
- // passed" → flip the marker off.
- test.fail();
test.setTimeout(120_000);
const projectId = env.project.split("/").pop()!;