Skip to content

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

refactor(react): schema diagram (#20167)

ecmadao8c7332cb28ff
diff --git a/docs/superpowers/specs/2026-04-28-sql-editor-react-migration-stage-19-design.md b/docs/superpowers/specs/2026-04-28-sql-editor-react-migration-stage-19-design.md
new file mode 100644
index 0000000000..7ac5cf7334
--- /dev/null
+++ b/docs/superpowers/specs/2026-04-28-sql-editor-react-migration-stage-19-design.md
@@ -0,0 +1,312 @@
+# SQL Editor React Migration — Stage 19 Design
+
+**Date:** 2026-04-28
+**Author:** [email protected]
+**Status:** Draft
+
+## 1. Goal & non-goals
+
+**Goal:** Migrate the entire SchemaDiagram subsystem from Vue to React: the
+`DiagramPanel.vue` wrapper inside the SQL Editor's right-panel chooser plus
+all 44 files under `frontend/src/components/SchemaDiagram/`. After this
+stage, the only remaining Vue surfaces in `frontend/src/views/sql-editor/`
+will be the ResultView family (Stage 20) and the host shells (Stage 21).
+
+**Non-goals:**
+- `EditorCommon/ResultView/*` — Stage 20 (perf-spike headline).
+- The five host shells (`Panels`, `EditorPanel`, `StandardPanel`,
+ `TerminalPanel`, `ResultPanel`, `SQLEditorHomePage`) — Stage 21.
+- Visual / behavioral changes to the diagram itself — parity only.
+- New SchemaDiagram features (column edit, relationship inference, etc.) —
+ Stage 19 is a port, not a rewrite.
+- Test coverage for SchemaDiagram beyond what the migration directly
+ requires (the Vue subsystem has zero existing tests; we'll add tests
+ only for the new React seams that warrant them — see §5).
+
+> **Heads-up — no cytoscape.** Initial planning assumed SchemaDiagram was
+> built on cytoscape. It isn't. The canvas is custom SVG/DOM with a CSS
+> `transform: matrix(...)` viewport, drag/wheel handlers via `vueuse`,
+> auto-layout via ELK (`elkjs`), and FK lines as inline SVG paths. The
+> "cytoscape spike" originally scoped into this stage is therefore
+> deleted from the plan.
+
+## 2. Inventory
+
+**In scope (~2,288 LOC):**
+
+| File / group | LOC | Notes |
+|---|---|---|
+| `EditorPanel/Panels/DiagramPanel/DiagramPanel.vue` | 23 | Thin wrapper. Reads the current tab's `database` + `useDBSchemaV1Store().getDatabaseMetadata(...)` and forwards to `<SchemaDiagram>`. |
+| `components/SchemaDiagram/SchemaDiagram.vue` | 265 | Root layout: Navigator (left) + Canvas (right). Owns the context provider. |
+| `components/SchemaDiagram/ER/TableNode.vue` | 229 | Per-table card: title, columns list, FK glyphs, hover affordances. |
+| `components/SchemaDiagram/ER/ForeignKeyLine.vue` | 176 | SVG path between two tables; recomputes anchor sides + path on layout / pan / zoom changes. |
+| `components/SchemaDiagram/Canvas/DummyCanvas.vue` | 176 | Off-screen render of the diagram for `html-to-image` screenshot capture. Exposes `capture(filename)`. |
+| `components/SchemaDiagram/Navigator/Tree.vue` | 146 | NTree of schemas → tables with keyword highlight. |
+| `components/SchemaDiagram/common/geometry.ts` | 139 | Pure rect / point / segment math. No Vue deps. |
+| `components/SchemaDiagram/ER/libs/SVGLine.vue` | 121 | Path renderer with arrowhead decorators. |
+| `components/SchemaDiagram/Canvas/Canvas.vue` | 93 | Viewport: applies `transform: matrix(zoom, 0, 0, zoom, x, y)`, mounts `<DummyCanvas>` for screenshot, hosts zoom controls. |
+| `components/SchemaDiagram/types/context.ts` | 72 | `SchemaDiagramContext` shape: Emittery event bus + reactive refs. |
+| `components/SchemaDiagram/Canvas/composables/useDragCanvas.ts` | 70 | Pan + wheel zoom; uses `normalize-wheel`. |
+| `components/SchemaDiagram/ER/libs/autoLayout/engines/elk.ts` | 70 | Dynamic-imports `elkjs`, returns `Map<tableId, Rect>`. |
+| `components/SchemaDiagram/Navigator/Navigator.vue` | 66 | Collapsible sidebar shell + search input. |
+| `components/SchemaDiagram/common/useDraggable.ts` | 57 | Low-level mousedown/mousemove/mouseup pan helper. |
+| `components/SchemaDiagram/common/FocusButton.vue` | 55 | Per-table "focus" button (centers + zooms on a table). |
+| `components/SchemaDiagram/Navigator/TreeNode/Label.vue` | 44 | Tree-node label with highlight. |
+| `components/SchemaDiagram/Canvas/composables/useSetCenter.ts` | 43 | Listens for `set-center` events, animates `(zoom, position)`. |
+| `components/SchemaDiagram/Canvas/libs/fitView.ts` | 39 | Pure math: bbox → `(zoom, position)`. |
+| `components/SchemaDiagram/Canvas/ZoomButton.vue` | 38 | Zoom in / out / reset / fit / screenshot button group. |
+| `components/SchemaDiagram/Navigator/SchemaSelector.vue` | 37 | Multi-select for which schemas to render (Postgres-style multi-schema DBs). |
+| `components/SchemaDiagram/common/context.ts` | 28 | `provide` / `inject` wrapper around the context. |
+| `components/SchemaDiagram/Canvas/composables/useFitView.ts` | 26 | Listens for `fit-view`, calls `fitView()` math. |
+| `components/SchemaDiagram/common/schema.ts` | 24 | Helpers (engine name, schema-key generation, etc.). |
+| `components/SchemaDiagram/ER/libs/autoLayout/types.ts` | 21 | Graph node / edge types passed to ELK. |
+| `components/SchemaDiagram/ER/libs/isFocusedFKTable.ts` | 21 | "Should this FK line be highlighted?" predicate. |
+| `components/SchemaDiagram/types/schema.ts` | 19 | Internal table / column types. |
+| `components/SchemaDiagram/SchemaDiagramIcon.vue` | 17 | Wrapper for the icon shown in tab strips. |
+| `components/SchemaDiagram/Navigator/TreeNode/Prefix.vue` | 17 | Tree-node prefix slot. |
+| `components/SchemaDiagram/types/geometry.ts` | 15 | `Rect`, `Point` etc. |
+| `components/SchemaDiagram/common/FocusIcon.vue` | 15 | Inline SVG icon. |
+| `components/SchemaDiagram/common/utils.ts` | 14 | Misc. helpers. |
+| `components/SchemaDiagram/Navigator/TreeNode/Suffix.vue` | 27 | Tree-node suffix slot. |
+| `components/SchemaDiagram/common/const.ts` | 6 | Constants (default zoom, padding, etc.). |
+| `components/SchemaDiagram/types/edit.ts` | 1 | Edit-state placeholder. |
+| `components/SchemaDiagram/{ER,Canvas,Navigator,types,common}/index.ts` | ~3-8 each | Barrel re-exports. |
+
+**Total**: 2,288 LOC across 44 files. The canvas + ER + navigator triplet
+accounts for ~75% of it; the remaining ~25% is composables, types,
+geometry math, and barrels.
+
+### Out of scope (later stages)
+
+```
+EditorCommon/ResultView/* → Stage 20 (perf spike)
+ResultPanel/DatabaseQueryContext.vue → Stage 20 (mounts ResultViewV1)
+ResultPanel/ResultPanel.vue → Stage 21 (host shell)
+StandardPanel/StandardPanel.vue → Stage 21
+TerminalPanel/TerminalPanel.vue → Stage 21
+Panels/Panels.vue → Stage 21
+EditorPanel/EditorPanel.vue → Stage 21
+SQLEditorHomePage.vue → Stage 21
+SQLEditorPage.vue → Stage 21
+components/DataExportButton.vue → Stage 20 (last Vue caller deleted with ResultView)
+```
+
+## 3. External deps & primitives
+
+| Vue dep | React replacement | Status |
+|---|---|---|
+| `NButton`, `NButtonGroup` (Canvas / ZoomButton) | `Button` (`@/react/components/ui/button`) | ✓ |
+| `NTooltip` | shared `Tooltip` (`@/react/components/ui/tooltip`) | ✓ |
+| `NInput` (Navigator search) | shared `PanelSearchBox` from Stage 16 — a clearable shadcn `Input` with leading icon | ✓ |
+| `NSelect` (`SchemaSelector`) | shadcn `Combobox` with `multiple` (already used elsewhere) | ✓ |
+| `NTree` (Navigator) | `react-arborist` — already used by Stage 17 `SheetTree` for the worksheet sidebar | ✓ |
+| `Emittery` (event bus inside `SchemaDiagramContext`) | Module-level `Emittery` singleton (Stage 16/17 pattern) | ✓ |
+| Vue `provide` / `inject` | React context (one per SchemaDiagram instance) **or** module-level state — see §4. | Needs decision (low-risk; default to React context) |
+| `vueuse` `useEventListener` | Plain `addEventListener` in `useEffect` cleanup | ✓ |
+| `normalize-wheel` (wheel-zoom) | Same package, framework-agnostic | ✓ |
+| `elkjs` (auto-layout) | Same package, dynamic-imported the same way | ✓ |
+| `html-to-image` + `downloadjs` (screenshot) | Same packages, framework-agnostic | ✓ |
+| `lucide-vue-next` icons | `lucide-react` (already in use everywhere else) | ✓ |
+| Vue `defineExpose({ capture })` on `DummyCanvas` | Replace with React imperative handle, **or** lift the capture logic to a hook called from `Canvas.tsx` directly. See §4 / §8. | Needs decision |
+
+**No cytoscape, no react-cytoscapejs.** The original roadmap's
+"react-cytoscapejs vs direct cytoscape" question is dropped.
+
+## 4. Architecture & phases
+
+A single SchemaDiagram instance is per-tab (rendered inside `DiagramPanel`
+which lives inside the right panel chooser). Multiple tabs ⇒ multiple
+SchemaDiagram instances at most one of which is visible. That makes a
+**React context per instance** the right boundary for state (selected
+schemas, zoom, pan, hovered table, …) — module-level singletons would
+collide across tabs.
+
+The Emittery event bus, however, **stays per-instance** — it's a private
+back-channel between Canvas children and composables, not a cross-tab one.
+We carry it inside the same React context.
+
+### Phase 1 — Foundations (types, context, geometry math)
+
+1. Port `types/{context,geometry,schema,edit}.ts` and `common/{const,utils,schema,geometry}.ts` 1:1. These are pure TS, no Vue. Drop one tiny `vue` ref in `types/context.ts` — replace with React `MutableRefObject` / plain values.
+2. Create `frontend/src/react/components/SchemaDiagram/context.tsx` — React context provider holding:
+ - The Emittery event bus
+ - `zoom`, `position`, `rectsByTableId`, `focusedTable`, `keyword`, `selectedSchemas` (as React state)
+ - Imperative refs (canvas / desktop DOM nodes) for composables that need them
+3. Port `common/useDraggable.ts` → `useDraggable.ts` (React hook, captures via `useEffect` + `addEventListener`).
+
+**Deliverables:** types + geometry helpers + `SchemaDiagramProvider` shell + `useDraggable` hook + 1 unit test for `geometry.ts` segment math.
+
+### Phase 2 — Auto-layout + ELK integration
+
+1. Port `ER/libs/autoLayout/engines/elk.ts` and `ER/libs/autoLayout/types.ts` 1:1. They're plain async TS already; only the dynamic import path needs to keep working under the React esbuild transform (verify in dev — Stage 16 already proved Vite handles dynamic chunks identically for `.tsx`).
+2. Wrap with `useAutoLayout(metadata, schemas) → Map<tableId, Rect>` hook for cleanliness.
+
+**Deliverables:** `useAutoLayout` hook + 1 unit test stubbing ELK output.
+
+### Phase 3 — Navigator (left sidebar)
+
+1. Port `Navigator.vue` (66) → `Navigator.tsx`: collapsible sidebar shell + search input (reuse `PanelSearchBox`).
+2. Port `Tree.vue` (146) + `TreeNode/{Label,Prefix,Suffix}.vue` → `Tree.tsx` using `react-arborist` (same library Stage 17 used). Keyword highlight reuses the shared `HighlightLabelText` (per existing memory rule).
+3. Port `SchemaSelector.vue` (37) → `SchemaSelector.tsx` using shadcn `Combobox` with multi-select.
+
+**Deliverables:** 3 React surfaces + 1 test (tree filter + selection wiring).
+
+### Phase 4 — Canvas (viewport + pan + zoom)
+
+1. Port `Canvas.vue` (93) → `Canvas.tsx`. The whole render is `<div ref={canvas} style={{ transform: matrix(...) }}>...</div>` plus zoom/screenshot button group. Reuse Stage 18 `Tooltip` and `Button`.
+2. Port `Canvas/libs/fitView.ts` (39) — pure math, 1:1.
+3. Port `Canvas/composables/useDragCanvas.ts` (70) → `useDragCanvas.ts` hook. Calls `useDraggable` from Phase 1, plus a wheel listener for zoom.
+4. Port `useFitView.ts` (26) and `useSetCenter.ts` (43) → React hooks listening to the context's Emittery channel.
+5. Port `ZoomButton.vue` (38) → `ZoomButton.tsx` (one row of `Button`s). Triggers context emittery events.
+
+**Deliverables:** 5 React surfaces / hooks + 1 test (drag + wheel-zoom math, `fitView()` math).
+
+### Phase 5 — ER nodes + FK lines
+
+1. Port `SVGLine.vue` (121) → `SVGLine.tsx`. Pure presentation; React's SVG support is identical to Vue's.
+2. Port `TableNode.vue` (229) → `TableNode.tsx`. Includes `FocusButton` (55) and the column FK glyphs (lucide icons). Uses `useDraggable` to support per-table drag-to-reposition.
+3. Port `ForeignKeyLine.vue` (176) → `ForeignKeyLine.tsx`. Reads two table rects from context, recomputes anchor sides + SVG path on layout / drag / pan changes.
+4. Port `isFocusedFKTable.ts` 1:1.
+
+**Deliverables:** 4 React surfaces + 1 test (FK anchor-side selection + path generation).
+
+### Phase 6 — Screenshot (DummyCanvas → utility)
+
+1. The Vue `DummyCanvas.vue` (176) `defineExpose({ capture })` — `Canvas.vue` calls `dummy.value?.capture(filename)`. Two options:
+ - **(a)** Mirror the Vue split: `DummyCanvas.tsx` exposes `capture()` via `useImperativeHandle`, `Canvas.tsx` keeps a ref. Familiar pattern.
+ - **(b)** Lift to a hook: `useScreenshot(elementRef) → capture(filename)`. The hook reads the canvas DOM directly, runs `html-to-image` + `downloadjs` against it. No DummyCanvas component at all.
+ - **Recommendation: (b)**. The existing DummyCanvas is "render the diagram a second time off-screen so html-to-image has a clean target without Naive UI chrome". A React hook + a portaled `<div className="hidden">` is enough for the same effect, and it removes the only imperative-ref coupling in the subsystem.
+
+**Deliverables:** 1 hook + 1 manual verification (screenshot ≥1 large schema).
+
+### Phase 7 — `SchemaDiagram` root + `DiagramPanel` wrapper + caller swap
+
+1. Port `SchemaDiagram.vue` (265) → `SchemaDiagram.tsx`: composes Navigator + Canvas inside the context provider.
+2. Port `DiagramPanel.vue` (23) → `DiagramPanel.tsx`: reads the current tab's `database` (via `useVueState`) + `useDBSchemaV1Store().getDatabaseMetadata(database.name)` (Pinia store, framework-agnostic), forwards to `<SchemaDiagram>`.
+3. Update `Panels.vue` to mount `<ReactPageMount page="DiagramPanel" />` instead of `<DiagramPanel>`.
+4. Delete the Vue `DiagramPanel.vue` and the entire `frontend/src/components/SchemaDiagram/` tree.
+
+**Deliverables:** 2 React surfaces + 1 mount shim + Vue file deletions.
+
+## 5. Per-phase checklist
+
+### Phase 1 — Foundations
+- [ ] Port `types/*` and `common/{const,utils,schema,geometry}.ts` to `frontend/src/react/components/SchemaDiagram/` 1:1
+- [ ] `SchemaDiagramContext` React context + provider component
+- [ ] `useDraggable` hook
+- [ ] Unit test for segment-overlap geometry helpers
+
+### Phase 2 — Auto-layout
+- [ ] `ER/libs/autoLayout/{engines/elk,types}.ts` ported, dynamic import preserved
+- [ ] `useAutoLayout(metadata, selectedSchemas)` hook
+- [ ] Unit test stubbing ELK to assert output Map shape
+
+### Phase 3 — Navigator
+- [ ] `Navigator.tsx` (sidebar shell + search via `PanelSearchBox`)
+- [ ] `Tree.tsx` using `react-arborist`, with keyword highlight via `HighlightLabelText`
+- [ ] `TreeNode/{Label,Prefix,Suffix}.tsx`
+- [ ] `SchemaSelector.tsx` (multi-select via shadcn `Combobox`)
+- [ ] Unit test: filter + select fires the right context events
+
+### Phase 4 — Canvas
+- [ ] `Canvas.tsx` (transform viewport + zoom button group + screenshot button)
+- [ ] `useDragCanvas` hook (pan + wheel zoom)
+- [ ] `useFitView`, `useSetCenter` hooks
+- [ ] `ZoomButton.tsx`
+- [ ] Pure-math tests for `fitView` and `useDragCanvas` zoom math
+
+### Phase 5 — ER nodes + FK lines
+- [ ] `SVGLine.tsx`
+- [ ] `TableNode.tsx` (incl. `FocusButton`, drag-to-reposition)
+- [ ] `ForeignKeyLine.tsx` (anchor side selection + SVG path)
+- [ ] Unit test for FK anchor-side selection given two rects
+
+### Phase 6 — Screenshot
+- [ ] `useScreenshot(canvasRef)` hook running `html-to-image` + `downloadjs`
+- [ ] Manual: capture a 50+ table schema, verify the PNG matches the visible diagram (no Naive UI chrome leaked, FK lines preserved)
+
+### Phase 7 — Root + wrapper + caller swap
+- [ ] `SchemaDiagram.tsx` root
+- [ ] `DiagramPanel.tsx` wrapper (mount shim added to `frontend/src/react/mount.ts` glob if needed)
+- [ ] `Panels.vue` swap (`<DiagramPanel>` → `<ReactPageMount page="DiagramPanel" ... />`)
+- [ ] Delete Vue `DiagramPanel.vue` and `frontend/src/components/SchemaDiagram/*`
+- [ ] Gates green
+- [ ] Manual: walk through §6 verification list
+
+## 6. Manual UX verification
+
+- **Open DiagramPanel** on a Postgres database with multiple schemas + 50+
+ tables. Layout should converge to the same structure as Vue (ELK is
+ deterministic given the same input → identical positions are expected).
+- **Pan / zoom**: drag the canvas, scroll-wheel zoom — the gesture
+ responsiveness should match Vue's. Zoom in / out / reset / fit-view
+ buttons all work.
+- **Schema selector**: toggle schemas on/off, layout re-runs, FK lines
+ update.
+- **Navigator tree**: search filters schemas + tables, click a table →
+ centers it via `set-center` (uses Phase 4's `useSetCenter`).
+- **Hover a table**: FocusButton appears, click it → centers + zooms on
+ that table.
+- **Drag a table**: per-table drag re-positions the node, FK lines
+ re-route to the new anchor sides.
+- **Screenshot**: click the screenshot button → PNG download + clipboard
+ copy. Open the PNG and verify all visible tables + FK lines are
+ captured without Naive UI / shadcn chrome.
+- **Engine variety**: open the diagram on MySQL (single-schema), MongoDB
+ (no FKs, no schemas), and a Postgres DB with 100+ tables to make sure
+ edge cases hold.
+
+## 7. Out of scope (deferred)
+
+- All of `EditorCommon/ResultView/*` and `ResultPanel/DatabaseQueryContext.vue` — Stage 20
+- The host shells — Stage 21
+- AI plugin port — separate effort (currently hosted by Vue at `Panels.vue` / `StandardPanel.vue` via the Stage 16/17 hoist)
+
+## 8. Risks & open questions
+
+- **No existing tests.** SchemaDiagram has zero `.test.*` / `.spec.*`
+ files in the Vue tree. We add seed tests where the math or wiring is
+ non-trivial (geometry helpers, FK anchor selection, ELK plumbing,
+ drag/zoom math, navigator filter wiring) but full coverage is out of
+ scope for a parity port.
+
+- **ELK dynamic import under React esbuild.** The existing call
+ `await import("elkjs/lib/elk.bundled.js")` works under Vue's Vite
+ pipeline. The React `.tsx` files go through esbuild (per
+ `react-tsx-transform`) but the resulting modules still hit Vite's chunk
+ splitting. Verify in dev that the ELK chunk loads exactly once and
+ doesn't re-trigger on every layout. (Cheap to confirm with the
+ Network tab.)
+
+- **DummyCanvas → `useScreenshot` hook (recommended).** The Vue subsystem
+ has a quirky split where `DummyCanvas.vue` does a second off-screen
+ render of the diagram so `html-to-image` has a chrome-free target.
+ Replacing this with a hook that runs against the live canvas DOM is
+ cleaner — but the live canvas includes Tailwind / shadcn affordances
+ (zoom buttons, hover focus button) that we'd need to hide during
+ capture. Two sub-options:
+ - (b1) Add a `data-screenshot-hide` attribute to those affordances and
+ a CSS selector that hides them while a `body[data-capturing]` flag is
+ set during the html-to-image call.
+ - (b2) Keep a thin hidden DOM wrapper that re-renders only the canvas
+ children. Closer to the Vue setup, but loses the simplification win.
+ - Recommendation: try (b1) first — it's the cleaner React idiom. Fall
+ back to (b2) if affordance hiding turns out to be lossy.
+
+- **Per-instance vs module-level state.** The Vue context is per-instance
+ via `provide`/`inject`. We mirror that with a React context per
+ `<SchemaDiagram>` mount. **Don't** lift to a module-level singleton —
+ multiple tabs can have multiple SchemaDiagram instances open
+ simultaneously, and a singleton would cross-talk between them.
+
+- **`react-arborist` reuse.** Stage 17 introduced react-arborist for the
+ worksheet `SheetTree`. The Navigator's tree is structurally similar
+ (parent = schema, children = tables). Reuse the same lib + the
+ existing `onSelect` mount-time-`[]` guard memory.
+
+- **Drag interactions stack with pan.** The canvas listens for
+ drag-to-pan; tables also listen for drag-to-reposition; the wheel both
+ pans with shift held and zooms otherwise. Vue's implementation
+ threads this via event delegation in `useDraggable` + per-table
+ `mousedown` handlers with `stopPropagation`. Mirror exactly to avoid
+ regressions on click-vs-drag thresholds and middle-mouse panning.
diff --git a/frontend/src/assets/css/tailwind.css b/frontend/src/assets/css/tailwind.css
index 742ae44e54..2b45544d40 100644
--- a/frontend/src/assets/css/tailwind.css
+++ b/frontend/src/assets/css/tailwind.css
@@ -424,3 +424,12 @@
.n-input__input-el:focus {
box-shadow: 0 0 0 0;
}
+
+/* SchemaDiagram screenshot capture: while `useScreenshot` flips this
+ attribute on <body>, any element marked `data-screenshot-hide` is
+ omitted from the html-to-image pass. Used for chrome affordances
+ (zoom buttons, schema selector, etc.) that shouldn't appear in
+ the exported PNG. */
+body[data-bb-screenshot-active] [data-screenshot-hide] {
+ display: none !important;
+}
diff --git a/frontend/src/components/SchemaDiagram/Canvas/Canvas.vue b/frontend/src/components/SchemaDiagram/Canvas/Canvas.vue
deleted file mode 100644
index 5ffe570b49..0000000000
--- a/frontend/src/components/SchemaDiagram/Canvas/Canvas.vue
+++ /dev/null
@@ -1,93 +0,0 @@
-<template>
- <div ref="canvas" class="w-full h-full relative bg-gray-200 overflow-hidden">
- <div
- ref="desktop"
- class="absolute overflow-visible"
- :style="{
- transformOrigin: '0 0 0',
- transform: `matrix(${zoom}, 0, 0, ${zoom}, ${position.x}, ${position.y})`,
- }"
- >
- <slot name="desktop" />
- </div>
-
- <div class="absolute! right-2 bottom-2 flex items-center gap-x-2">
- <slot name="controls" />
-
- <NButtonGroup size="tiny" class="bg-white rounded-sm">
- <NTooltip>
- <template #trigger>
- <NButton tooltip>
- <Image @click="handleScreenshot" />
- </NButton>
- </template>
- <div class="whitespace-nowrap">Screenshot</div>
- </NTooltip>
- </NButtonGroup>
-
- <NButtonGroup size="tiny" class="bg-white rounded-sm">
- <NTooltip>
- <template #trigger>
- <NButton tooltip>
- <LayoutGrid @click="handleFitView" />
- </NButton>
- </template>
- <div class="whitespace-nowrap">
- {{ $t("schema-diagram.fit-content-with-view") }}
- </div>
- </NTooltip>
- </NButtonGroup>
-
- <ZoomButton
- :min="ZOOM_RANGE.min"
- :max="ZOOM_RANGE.max"
- @zoom-in="handleZoom(0.1)"
- @zoom-out="handleZoom(-0.1)"
- />
- </div>
-
- <DummyCanvas ref="dummy" :render-desktop="renderDummy" />
-
- <slot />
- </div>
-</template>
-
-<script lang="ts" setup>
-import { Image, LayoutGrid } from "lucide-vue-next";
-import { NButton, NButtonGroup, NTooltip } from "naive-ui";
-import { ref, useSlots } from "vue";
-import { extractDatabaseResourceName } from "@/utils";
-import { useSchemaDiagramContext } from "../common";
-import { ZOOM_RANGE } from "../common/const";
-import { useDragCanvas, useFitView, useSetCenter } from "./composables";
-import DummyCanvas from "./DummyCanvas.vue";
-import ZoomButton from "./ZoomButton.vue";
-
-const slots = useSlots();
-
-const canvas = ref<Element>();
-const desktop = ref<Element>();
-const dummy = ref<InstanceType<typeof DummyCanvas>>();
-
-const { database, busy, zoom, position } = useSchemaDiagramContext();
-
-const handleFitView = useFitView(canvas);
-const { handleZoom } = useDragCanvas(canvas);
-useSetCenter(canvas);
-
-const renderDummy = () => {
- return slots["desktop"]?.();
-};
-
-const handleScreenshot = async () => {
- busy.value = true;
- try {
- const { databaseName } = extractDatabaseResourceName(database.value.name);
- await dummy.value?.capture(`${databaseName}.png`);
- } catch (err) {
- console.error("Screenshot request failed", err);
- } finally {
- busy.value = false;
- }
-};
-</script>
diff --git a/frontend/src/components/SchemaDiagram/Canvas/DummyCanvas.vue b/frontend/src/components/SchemaDiagram/Canvas/DummyCanvas.vue
deleted file mode 100644
index c8447f758c..0000000000
--- a/frontend/src/components/SchemaDiagram/Canvas/DummyCanvas.vue
+++ /dev/null
@@ -1,176 +0,0 @@
-<template>
- <teleport to="#capture-container">
- <div
- v-if="isCapturing"
- ref="canvas"
- class="relative overflow-hidden bg-gray-200 pointer-events-none z-10"
- :style="{
- width: `${resizeParams.rect.width}px`,
- height: `${resizeParams.rect.height}px`,
- }"
- >
- <div
- class="absolute overflow-visible origin-top-left"
- :style="{
- width: `${width}px`,
- height: `${height}px`,
- transform: `scale(${resizeParams.zoom})`,
- }"
- >
- <Watermark />
- <DesktopRenderer />
- </div>
-
- <img
- class="absolute z-50 opacity-50 origin-bottom-left"
- :style="{
- width: `${logoWidth}px`,
- height: 'auto',
- left: `${LOGO_PADDING * resizeParams.zoom}px`,
- bottom: `${LOGO_PADDING * resizeParams.zoom}px`,
- transform: `scale(${resizeParams.zoom})`,
- }"
- src="../../../assets/logo-full.svg"
- alt="Bytebase"
- />
-
- <div
- class="absolute z-50 opacity-50 origin-bottom-right"
- :style="{
- lineHeight: '1em',
- fontSize: `${logoWidth / 6}px`,
- right: `${LOGO_PADDING * resizeParams.zoom}px`,
- bottom: `${LOGO_PADDING * resizeParams.zoom}px`,
- transform: `scale(${resizeParams.zoom})`,
- }"
- >
- {{ now }}
- </div>
- </div>
- </teleport>
-</template>
-
-<script lang="ts" setup>
-import type { PropType, VNode } from "vue";
-import { computed, defineComponent, nextTick, ref } from "vue";
-import Watermark from "@/components/misc/Watermark.vue";
-import { pushNotification } from "@/store";
-import { formatAbsoluteDateTime, minmax } from "@/utils";
-import {
- calcBBox,
- fitBBox,
- provideSchemaDiagramContext,
- useSchemaDiagramContext,
-} from "../common";
-
-const props = defineProps({
- renderDesktop: {
- type: Function as PropType<() => VNode | VNode[] | undefined>,
- required: true,
- },
-});
-
-const LOGO_PADDING = 10;
-
-const canvas = ref<HTMLDivElement>();
-
-const isCapturing = ref(false);
-
-const context = useSchemaDiagramContext();
-const { geometries } = context;
-
-const desktopBBox = computed(() => {
- return calcBBox([...geometries.value]);
-});
-
-// Automatically set the logo's width according to the canvas size.
-const logoWidth = computed(() => {
- const MIN_WIDTH = 120;
- const MAX_WIDTH = 480;
-
- return minmax(desktopBBox.value.width / 8, MIN_WIDTH, MAX_WIDTH);
-});
-
-const width = computed(() => {
- return Math.max(
- desktopBBox.value.width + desktopBBox.value.x * 2,
- logoWidth.value + LOGO_PADDING * 2
- );
-});
-
-const height = computed(() => {
- const WIDTH_HEIGHT_RATIO = 4; // an approximate value.
- // Leave a bottom padding to avoid the logo overlapping diagram contents.
- const paddingBottom = logoWidth.value / WIDTH_HEIGHT_RATIO + LOGO_PADDING;
- return desktopBBox.value.height + desktopBBox.value.y * 2 + paddingBottom;
-});
-
-const resizeParams = computed(() => {
- // Fit the output image within a size-limited box
- // and keep W/H ratio.
- return fitBBox(
- { width: width.value, height: height.value },
- {
- width: 4096,
- height: 4096,
- },
- [0, 1]
- );
-});
-
-const now = computed((): string => {
- return formatAbsoluteDateTime(Date.now());
-});
-
-const DesktopRenderer = defineComponent({
- render: () => {
- return props.renderDesktop();
- },
-});
-
-const capture = async (filename: string) => {
- if (isCapturing.value) {
- return;
- }
-
- isCapturing.value = true;
-
- await nextTick();
-
- const node = canvas.value;
- if (!node) {
- return;
- }
-
- try {
- const [{ toBlob }, { default: download }] = await Promise.all([
- import("html-to-image"),
- import("downloadjs"),
- ]);
- const blob = await toBlob(node, {
- pixelRatio: 1,
- quality: 0.9,
- });
- if (blob) {
- download(blob, filename, blob.type);
-
- const data = [new window.ClipboardItem({ [blob.type]: blob })];
- await navigator.clipboard.write(data);
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: "Screenshot generated successfully and copied to the clipboard!",
- });
- }
- } finally {
- isCapturing.value = false;
- }
-};
-
-provideSchemaDiagramContext({
- ...context,
- dummy: ref(true),
-});
-
-defineExpose({ capture });
-</script>
diff --git a/frontend/src/components/SchemaDiagram/Canvas/ZoomButton.vue b/frontend/src/components/SchemaDiagram/Canvas/ZoomButton.vue
deleted file mode 100644
index 1e876f237e..0000000000
--- a/frontend/src/components/SchemaDiagram/Canvas/ZoomButton.vue
+++ /dev/null
@@ -1,38 +0,0 @@
-<template>
- <NButtonGroup size="tiny" class="bg-white rounded-sm">
- <NButton :disabled="zoom <= min" @click="$emit('zoom-out')">
- <template #icon>
- <Minus />
- </template>
- </NButton>
- <NButton ghost class="pointer-events-none">
- <span class="w-8 text-xs"> {{ displayZoom }} </span>
- </NButton>
- <NButton :disabled="zoom >= max" @click="$emit('zoom-in')">
- <template #icon>
- <Plus />
- </template>
- </NButton>
- </NButtonGroup>
-</template>
-
-<script lang="ts" setup>
-import { Minus, Plus } from "lucide-vue-next";
-import { NButton, NButtonGroup } from "naive-ui";
-import { computed } from "vue";
-import { useSchemaDiagramContext } from "../common";
-
-defineProps<{
- min: number;
- max: number;
-}>();
-
-defineEmits<{
- (e: "zoom-in"): void;
- (e: "zoom-out"): void;
-}>();
-
-const { zoom } = useSchemaDiagramContext();
-
-const displayZoom = computed(() => `${Math.round(zoom.value * 100)}%`);
-</script>
diff --git a/frontend/src/components/SchemaDiagram/Canvas/composables/index.ts b/frontend/src/components/SchemaDiagram/Canvas/composables/index.ts
deleted file mode 100644
index 504da6ac93..0000000000
--- a/frontend/src/components/SchemaDiagram/Canvas/composables/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export * from "./useDragCanvas";
-export * from "./useFitView";
-export * from "./useSetCenter";
diff --git a/frontend/src/components/SchemaDiagram/Canvas/composables/useDragCanvas.ts b/frontend/src/components/SchemaDiagram/Canvas/composables/useDragCanvas.ts
deleted file mode 100644
index a461169e30..0000000000
--- a/frontend/src/components/SchemaDiagram/Canvas/composables/useDragCanvas.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { useEventListener } from "@vueuse/core";
-import normalizeWheel from "normalize-wheel";
-import { type Ref, ref } from "vue";
-import { minmax } from "@/utils";
-import { useDraggable, useSchemaDiagramContext } from "../../common";
-import { ZOOM_RANGE } from "../../common/const";
-import type { Point } from "../../types";
-
-export const useDragCanvas = (canvas: Ref<Element | undefined>) => {
- const { zoom, position, panning } = useSchemaDiagramContext();
-
- const zoomCenter = ref<Point>({ x: 0.5, y: 0.5 });
-
- const handleZoom = (delta: number, center: Point = { x: 0.5, y: 0.5 }) => {
- if (!canvas.value) return "";
-
- const z = minmax(zoom.value + delta, ZOOM_RANGE.min, ZOOM_RANGE.max);
- const factor = z / zoom.value;
- zoom.value = z;
-
- zoomCenter.value = center;
-
- // While zooming, we need to adjust the `position` according to the
- // zoom level and zoom center.
- const { width, height } = canvas.value.getBoundingClientRect();
- const cx = center.x * width;
- const cy = center.y * height;
- position.value.x = cx - factor * (cx - position.value.x);
- position.value.y = cy - factor * (cy - position.value.y);
- };
- const handlePan = (x: number, y: number) => {
- position.value.x += x;
- position.value.y += y;
- panning.value = true;
- };
- const handlePanEnd = () => {
- requestAnimationFrame(() => {
- panning.value = false;
- });
- };
-
- useDraggable(canvas, {
- exact: false,
- onPan: handlePan,
- onEnd: handlePanEnd,
- });
-
- useEventListener(
- canvas,
- "mousewheel",
- (e: WheelEvent) => {
- const ne = normalizeWheel(e);
-
- const scrollDelta = -ne.pixelY;
- const delta = scrollDelta / 250; // adjust the scrolling speed
- const rect = canvas.value!.getBoundingClientRect();
- const center = {
- x: (e.pageX - rect.left) / rect.width,
- y: (e.pageY - rect.top) / rect.height,
- };
- handleZoom(delta, center);
-
- e.preventDefault();
- e.stopPropagation();
- },
- true
- );
-
- return { handleZoom, handlePan, handlePanEnd };
-};
diff --git a/frontend/src/components/SchemaDiagram/Canvas/composables/useFitView.ts b/frontend/src/components/SchemaDiagram/Canvas/composables/useFitView.ts
deleted file mode 100644
index 0f61ce2c4d..0000000000
--- a/frontend/src/components/SchemaDiagram/Canvas/composables/useFitView.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { type Ref } from "vue";
-import { useSchemaDiagramContext } from "../../common";
-import { DEFAULT_PADDINGS, ZOOM_RANGE } from "../../common/const";
-import { fitView } from "../libs/fitView";
-
-export const useFitView = (canvas: Ref<Element | undefined>) => {
- const { zoom, position, geometries, events } = useSchemaDiagramContext();
-
- const handleFitView = () => {
- if (!canvas.value) return;
- const layout = fitView(
- canvas.value,
- [...geometries.value],
- DEFAULT_PADDINGS,
- [ZOOM_RANGE.min, 1.0] /* [zoomMin, zoomMax] */
- );
- zoom.value = layout.zoom;
- position.value = {
- x: layout.rect.x,
- y: layout.rect.y,
- };
- };
- events.on("fit-view", handleFitView);
-
- return handleFitView;
-};
diff --git a/frontend/src/components/SchemaDiagram/Canvas/composables/useSetCenter.ts b/frontend/src/components/SchemaDiagram/Canvas/composables/useSetCenter.ts
deleted file mode 100644
index 82cc307255..0000000000
--- a/frontend/src/components/SchemaDiagram/Canvas/composables/useSetCenter.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { type Ref } from "vue";
-import { DEFAULT_PADDINGS, useSchemaDiagramContext } from "../../common";
-import type { CenterTarget, CenterTargetType, Rect } from "../../types";
-import { fitView } from "../libs/fitView";
-
-export const useSetCenter = (canvas: Ref<Element | undefined>) => {
- const { position, zoom, events, rectOfTable } = useSchemaDiagramContext();
-
- const setCenter = (rect: Rect, padding: number[], zooms: number[]) => {
- if (!canvas.value) {
- return;
- }
- // Fit view according to the center rect with limited zoom range.
- const layout = fitView(canvas.value, [rect], padding, zooms);
- zoom.value = layout.zoom;
- position.value = {
- x: layout.rect.x,
- y: layout.rect.y,
- };
- };
-
- events.on("set-center", (e) => {
- const { padding = DEFAULT_PADDINGS, zooms = [zoom.value, zoom.value] } = e;
- if (isTypedCenterTarget(e, "point")) {
- const center = e.target;
- setCenter({ ...center, width: 0, height: 0 }, padding, zooms);
- } else if (isTypedCenterTarget(e, "rect")) {
- setCenter(e.target, padding, zooms);
- } else if (isTypedCenterTarget(e, "table")) {
- const rect = rectOfTable(e.target);
- setCenter(rect, padding, zooms);
- } else {
- console.assert(false, `unknown set-center target "${e}"`);
- }
- });
-};
-
-const isTypedCenterTarget = <T extends CenterTargetType>(
- e: CenterTarget,
- type: T
-): e is CenterTarget<T> => {
- return e.type === type;
-};
diff --git a/frontend/src/components/SchemaDiagram/Canvas/index.ts b/frontend/src/components/SchemaDiagram/Canvas/index.ts
deleted file mode 100644
index 30d0ef20e6..0000000000
--- a/frontend/src/components/SchemaDiagram/Canvas/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import Canvas from "./Canvas.vue";
-
-export { Canvas };
-
-export default Canvas;
diff --git a/frontend/src/components/SchemaDiagram/ER/ForeignKeyLine.vue b/frontend/src/components/SchemaDiagram/ER/ForeignKeyLine.vue
deleted file mode 100644
index 882b3deee3..0000000000
--- a/frontend/src/components/SchemaDiagram/ER/ForeignKeyLine.vue
+++ /dev/null
@@ -1,176 +0,0 @@
-<template>
- <SVGLine
- class="transition-opacity"
- :class="lineClasses"
- :path="path"
- :decorators="[startManyArrow]"
- :bb-edge-from="`${fk.from.table.name}.${fk.from.column}`"
- :bb-edge-to="`${fk.to.table.name}.${fk.to.column}`"
- :bb-fk-name="fk.metadata.name"
- :bb-fk-on-update="fk.metadata.onUpdate"
- :bb-fk-on-delete="fk.metadata.onDelete"
- :bb-fk-match-type="fk.metadata.matchType"
- />
-</template>
-
-<script lang="ts" setup>
-import { computed, onMounted, ref } from "vue";
-import type { TableMetadata } from "@/types/proto-es/v1/database_service_pb";
-import type { VueClass } from "@/utils";
-import type { SegmentOverlap1D } from "../common";
-import {
- segmentOverlap1D,
- useGeometry,
- useSchemaDiagramContext,
-} from "../common";
-import type { ForeignKey, Path, Point, Rect } from "../types";
-import SVGLine from "./libs/SVGLine.vue";
-
-type Direction = "LEFT" | "RIGHT";
-type Segment1D = [number, number];
-
-const props = withDefaults(
- defineProps<{
- fk: ForeignKey;
- }>(),
- {}
-);
-
-const { zoom, focusedTables, idOfTable, rectOfTable, events } =
- useSchemaDiagramContext();
-const fromRect = ref<Rect>({ x: 0, y: 0, width: 0, height: 0 });
-const toRect = ref<Rect>({ x: 0, y: 0, width: 0, height: 0 });
-const path = computed((): Path => {
- const from = fromRect.value;
- const to = toRect.value;
-
- if (from.width === 0 || to.width === 0) {
- return [];
- }
-
- const fromPorts: Segment1D = [from.x, from.x + from.width];
- const toPorts: Segment1D = [to.x, to.x + to.width];
-
- const rel = segmentOverlap1D(
- fromPorts[0],
- fromPorts[1],
- toPorts[0],
- toPorts[1]
- );
- const [fromPort, toPort] = pickPorts(rel, fromPorts, toPorts);
-
- return generateLine(from, fromPort, to, toPort);
-});
-
-const lineClasses = computed((): VueClass => {
- const classes: string[] = [];
- if (focusedTables.value.size > 0) {
- const { from, to } = props.fk;
- if (
- focusedTables.value.has(from.table) ||
- focusedTables.value.has(to.table)
- ) {
- classes.push("opacity-100");
- } else {
- classes.push("opacity-20");
- }
- }
- return classes;
-});
-
-const findRect = (table: TableMetadata, columnName: string): Rect => {
- const id = idOfTable(table);
- const tableRect = rectOfTable(table);
- const tableElement = document.querySelector(`[bb-node-id="${id}"]`);
- if (!tableElement) {
- return { x: 0, y: 0, width: 0, height: 0 };
- }
- const columnElement = tableElement.querySelector(
- `[bb-column-name="${columnName}"]`
- );
- if (columnElement) {
- const tableView = tableElement.getBoundingClientRect();
- const columnView = columnElement.getBoundingClientRect();
- const columnRect = {
- x: tableRect.x + (columnView.left - tableView.left) / zoom.value,
- y: tableRect.y + (columnView.top - tableView.top) / zoom.value,
- width: columnView.width / zoom.value,
- height: columnView.height / zoom.value,
- };
- return columnRect;
- }
- return tableRect;
-};
-
-// A field has two "ports" - left and right.
-// For a field-field relationship a-b, we need to find which ports
-// of a and b we should use to make the connection line looks natural.
-const pickPorts = (
- rel: SegmentOverlap1D,
- a: Segment1D,
- b: Segment1D
-): [Direction, Direction] => {
- switch (rel) {
- case "BEFORE":
- return ["RIGHT", "LEFT"];
- case "AFTER":
- return ["LEFT", "RIGHT"];
- case "CONTAINS":
- case "OVERLAPS":
- return b[0] <= (a[0] + a[1]) / 2 ? ["LEFT", "LEFT"] : ["RIGHT", "RIGHT"];
- case "OVERLAPPED":
- case "CONTAINED":
- return a[0] <= (b[0] + b[1]) / 2 ? ["LEFT", "LEFT"] : ["RIGHT", "RIGHT"];
- }
-};
-
-const grow = (pos: Point, dir: Direction, length: number): Point => {
- const x = dir === "LEFT" ? pos.x - length : pos.x + length;
- return { x, y: pos.y };
-};
-const anchor = (rect: Rect, edge: Direction): Point => {
- const x = edge === "LEFT" ? rect.x : rect.x + rect.width;
- const y = rect.y + rect.height / 2;
- return { x, y };
-};
-const generateLine = (src: Rect, se: Direction, dest: Rect, de: Direction) => {
- const GROWTH_LEN = 16;
- const sp = anchor(src, se); // source point
- const dp = anchor(dest, de); // destination point
- const sc = grow(sp, se, GROWTH_LEN); // source corner
- const dc = grow(dp, de, GROWTH_LEN); // destination corner
- return [sp, sc, dc, dp];
-};
-const startManyArrow = computed((): Path => {
- if (path.value.length < 2) return [];
- /**
- * Create a "fork"-like line to indicate "to-many" relationship
- * m
- * /
- * q--c--p
- * \
- * n
- */
- const p = path.value[0];
- const q = path.value[1];
- const dir = Math.sign(q.x - p.x);
- const h = 12;
- const v = 6;
- const m = { x: p.x, y: p.y + v };
- const c = { x: p.x + h * dir, y: p.y };
- const n = { x: p.x, y: p.y - v };
- return [m, c, n];
-});
-
-const updatePath = () => {
- const { from, to } = props.fk;
- fromRect.value = findRect(from.table, from.column);
- toRect.value = findRect(to.table, to.column);
-};
-
-events.on("render", () => void updatePath());
-
-onMounted(updatePath);
-
-useGeometry(path);
-</script>
diff --git a/frontend/src/components/SchemaDiagram/ER/TableNode.vue b/frontend/src/components/SchemaDiagram/ER/TableNode.vue
deleted file mode 100644
index 5bf9d01ec8..0000000000
--- a/frontend/src/components/SchemaDiagram/ER/TableNode.vue
+++ /dev/null
@@ -1,229 +0,0 @@
-<template>
- <div
- class="absolute overflow-hidden rounded-md shadow-lg border-b border-gray-200 bg-white w-[16rem] divide-y z-10 transition-opacity"
- :class="tableClasses"
- bb-node-type="table"
- :bb-node-id="dummy ? `dummy-${idOfTable(table)}` : idOfTable(table)"
- :bb-status="tableStatus(table)"
- :style="{
- left: `${rect.x}px`,
- top: `${rect.y}px`,
- }"
- >
- <h3
- class="group font-medium leading-6 text-white px-2 py-2 rounded-t-md gap-x-1 relative text-center whitespace-pre-wrap wrap-break-word"
- :style="{
- 'background-color': tableColor,
- }"
- >
- <FocusButton
- :table="table"
- :set-center="false"
- class="invisible group-hover:visible absolute! top-[50%] -mt-[9px] left-1 text-main group-hover:bg-white/70 group-hover:text-main!"
- focused-class="text-white!"
- />
-
- <template v-if="schema.name !== ''">
- <span :class="[isTableDropped && 'line-through']">
- {{ schema.name }}
- </span>
- <span>.</span>
- </template>
- <span :class="[isTableDropped && 'line-through']">{{ table.name }}</span>
- <span v-if="tableStatusText" class="ml-1 text-sm">
- ({{ tableStatusText }})
- </span>
-
- <button
- v-if="editable"
- class="invisible group-hover:visible absolute top-[50%] -mt-[9px] right-1 text-main bg-white/70 hover:bg-gray-200 p-0.5 rounded-sm"
- @click="events.emit('edit-table', { schema, table })"
- >
- <Pencil class="w-4 h-4" />
- </button>
- </h3>
-
- <table class="w-full text-sm table-fixed">
- <tr
- v-for="(column, i) in table.columns"
- :key="i"
- :bb-column-name="dummy ? `dummy-${column.name}` : column.name"
- :bb-status="columnStatus(column)"
- :class="columnClasses(column)"
- >
- <td class="w-5 py-1.5 relative">
- <Key
- v-if="isPrimaryKey(table, column)"
- class="w-3 h-3 mx-auto text-amber-500"
- />
- <Diamond
- v-else-if="isIndex(table, column)"
- class="w-3 h-3 mx-auto text-gray-500"
- />
- </td>
- <td class="w-auto text-xs py-1.5">
- <div
- class="whitespace-pre-wrap wrap-break-word pr-1.5"
- :class="editable && 'hover:text-accent!'"
- @click="handleClickColumn(column, 'name')"
- >
- {{ column.name }}
- <span
- v-if="columnStatus(column) !== 'normal'"
- class="inline-block rounded-full ml-0.5 h-1.5 w-1.5 bg-accent opacity-75 -translate-y-px"
- ></span>
- </div>
- </td>
- <td class="w-24 text-xs text-gray-400 py-1.5 text-right">
- <div
- class="truncate pr-1.5"
- :class="editable && 'hover:text-accent!'"
- @click="handleClickColumn(column, 'type')"
- >
- {{ column.type }}
- </div>
- </td>
- </tr>
- </table>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { Diamond, Key, Pencil } from "lucide-vue-next";
-import { computed } from "vue";
-import { hashCode } from "@/bbkit/BBUtil";
-import type {
- ColumnMetadata,
- SchemaMetadata,
- TableMetadata,
-} from "@/types/proto-es/v1/database_service_pb";
-import type { VueClass } from "@/utils";
-import {
- FocusButton,
- isIndex,
- isPrimaryKey,
- useGeometry,
- useSchemaDiagramContext,
-} from "../common";
-import { isFocusedForeignTable } from "./libs/isFocusedFKTable";
-
-const props = withDefaults(
- defineProps<{
- schema: SchemaMetadata;
- table: TableMetadata;
- }>(),
- {}
-);
-
-const {
- dummy,
- editable,
- focusedTables,
- foreignKeys,
- idOfTable,
- rectOfTable,
- schemaStatus,
- tableStatus,
- columnStatus,
- panning,
- events,
-} = useSchemaDiagramContext();
-
-const COLOR_LIST = [
- "#64748B",
- "#EF4444",
- "#F97316",
- "#EAB308",
- "#84CC16",
- "#22C55E",
- "#10B981",
- "#06B6D4",
- "#0EA5E9",
- "#3B82F6",
- "#6366F1",
- "#8B5CF6",
- "#A855F7",
- "#D946EF",
- "#EC4899",
- "#F43F5E",
-];
-
-const tableColor = computed(() => {
- const index = (hashCode(props.table.name) & 0xfffffff) % COLOR_LIST.length;
- return COLOR_LIST[index];
-});
-
-const isTableDropped = computed(() => {
- return (
- schemaStatus(props.schema) === "dropped" ||
- tableStatus(props.table) === "dropped"
- );
-});
-
-const isTableCreated = computed(() => {
- return (
- schemaStatus(props.schema) === "created" ||
- tableStatus(props.table) === "created"
- );
-});
-
-const isTableChanged = computed(() => {
- return tableStatus(props.table) === "changed";
-});
-
-const tableClasses = computed((): VueClass => {
- const classes: string[] = [];
- if (focusedTables.value.size > 0) {
- if (focusedTables.value.has(props.table)) {
- classes.push("opacity-100");
- } else if (
- isFocusedForeignTable(props.table, focusedTables.value, foreignKeys.value)
- ) {
- classes.push("opacity-100");
- } else {
- classes.push("opacity-20 hover:opacity-100");
- }
- }
- return classes;
-});
-
-const columnClasses = (column: ColumnMetadata): VueClass => {
- const classes: string[] = [];
- if (editable.value) {
- classes.push("cursor-pointer");
- }
-
- const status = columnStatus(column);
- if (status === "changed") {
- classes.push("text-yellow-700", "bg-yellow-50");
- } else if (status === "created") {
- classes.push("text-green-700", "bg-green-50");
- } else if (status === "dropped") {
- classes.push("text-red-700", "bg-red-50", "line-through");
- }
-
- return classes;
-};
-
-const handleClickColumn = (column: ColumnMetadata, target: "name" | "type") => {
- if (!editable.value) return;
- if (panning.value) return;
- events.emit("edit-column", {
- schema: props.schema,
- table: props.table,
- column,
- target,
- });
-};
-
-const tableStatusText = computed(() => {
- if (isTableCreated.value) return "Created";
- if (isTableDropped.value) return "Dropped";
- if (isTableChanged.value) return "Changed";
- return "";
-});
-
-const rect = computed(() => rectOfTable(props.table));
-
-useGeometry(rect);
-</script>
diff --git a/frontend/src/components/SchemaDiagram/ER/index.ts b/frontend/src/components/SchemaDiagram/ER/index.ts
deleted file mode 100644
index c362692b35..0000000000
--- a/frontend/src/components/SchemaDiagram/ER/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import ForeignKeyLine from "./ForeignKeyLine.vue";
-import TableNode from "./TableNode.vue";
-
-export { TableNode, ForeignKeyLine };
-export * from "./libs/autoLayout";
diff --git a/frontend/src/components/SchemaDiagram/ER/libs/SVGLine.vue b/frontend/src/components/SchemaDiagram/ER/libs/SVGLine.vue
deleted file mode 100644
index e0fd6bebb3..0000000000
--- a/frontend/src/components/SchemaDiagram/ER/libs/SVGLine.vue
+++ /dev/null
@@ -1,121 +0,0 @@
-<template>
- <svg
- version="1.1"
- xmlns="http://www.w3.org/2000/svg"
- class="absolute cursor-pointer"
- pointer-events="none"
- :viewBox="[viewBox.x, viewBox.y, viewBox.width, viewBox.height].join(' ')"
- :style="{
- left: `${bbox.x + viewBox.x}px`,
- top: `${bbox.y + viewBox.y}px`,
- width: `${viewBox.width}px`,
- height: `${viewBox.height}px`,
- 'z-index': hover ? 1 : 0,
- }"
- >
- <path
- ref="track"
- version="1.1"
- xmlns="http://www.w3.org/2000/svg"
- :d="svgLine"
- pointer-events="visibleStroke"
- fill="none"
- :stroke="hover ? COLORS.GLOW.HOVER : COLORS.GLOW.NORMAL"
- :stroke-width="GLOW_WIDTH"
- />
- <path
- v-for="(decorator, i) in svgDecorators"
- :key="i"
- version="1.1"
- xmlns="http://www.w3.org/2000/svg"
- :d="decorator"
- fill="none"
- :stroke="hover ? COLORS.LINE.HOVER : COLORS.LINE.NORMAL"
- stroke-width="1"
- pointer-events="none"
- />
- <path
- ref="line"
- version="1.1"
- xmlns="http://www.w3.org/2000/svg"
- :d="svgLine"
- pointer-events="visibleStroke"
- fill="none"
- :stroke="hover ? COLORS.LINE.HOVER : COLORS.LINE.NORMAL"
- :stroke-width="hover ? 2 : 1.5"
- />
- </svg>
-</template>
-
-<script lang="ts" setup>
-import { useElementHover } from "@vueuse/core";
-import { curveMonotoneX, line as d3Line } from "d3-shape";
-import { computed, ref } from "vue";
-import { calcBBox } from "../../common";
-import type { Path, Rect } from "../../types";
-
-const GLOW_WIDTH = 12;
-const PADDING = GLOW_WIDTH / 2;
-const COLORS = {
- GLOW: {
- NORMAL: "transparent",
- HOVER: "rgba(55,48,163,0.1)",
- },
- LINE: {
- NORMAL: "#1f2937",
- HOVER: "#4f46e5",
- },
-};
-
-const props = withDefaults(
- defineProps<{
- path: Path;
- decorators?: Path[];
- }>(),
- {
- decorators: () => [],
- }
-);
-
-const track = ref<SVGPathElement>();
-const line = ref<SVGPathElement>();
-
-const trackHover = useElementHover(track);
-const lineHover = useElementHover(line);
-const hover = computed(() => trackHover.value || lineHover.value);
-
-const bbox = computed(() => {
- const points = [...props.path];
- props.decorators.forEach((decorator) => points.push(...decorator));
- return calcBBox(points);
-});
-
-const viewBox = computed((): Rect => {
- return {
- x: -PADDING,
- y: -PADDING,
- width: Math.max(bbox.value.width, 0) + PADDING * 2,
- height: Math.max(bbox.value.height, 0) + PADDING * 2,
- };
-});
-
-const normalize = (x: number, y: number): [number, number] => {
- const dx = bbox.value.x;
- const dy = bbox.value.y;
- return [x - dx, y - dy];
-};
-
-const svgLine = computed(() => {
- return (
- d3Line().curve(curveMonotoneX)(
- props.path.map((p) => normalize(p.x, p.y))
- ) ?? ""
- );
-});
-
-const svgDecorators = computed(() => {
- return props.decorators.map((path) => {
- return d3Line()(path.map((p) => normalize(p.x, p.y))) ?? "";
- });
-});
-</script>
diff --git a/frontend/src/components/SchemaDiagram/Navigator/Navigator.vue b/frontend/src/components/SchemaDiagram/Navigator/Navigator.vue
deleted file mode 100644
index 20df95f8db..0000000000
--- a/frontend/src/components/SchemaDiagram/Navigator/Navigator.vue
+++ /dev/null
@@ -1,66 +0,0 @@
-<template>
- <div class="relative h-full">
- <div
- class="bb-schema-diagram--navigator--main h-full bg-white overflow-hidden border-y border-gray-200 flex flex-col transition-all"
- :class="[state.expand ? 'w-72 shadow-sm border-l' : 'w-0']"
- >
- <div class="p-1 flex flex-col gap-y-2">
- <SchemaSelector
- v-if="hasSchemaProperty(instanceEngine)"
- :schemas="databaseMetadata.schemas"
- v-model:value="selectedSchemaNames"
- />
- <NInput
- :size="'small'"
- v-model:value="state.keyword"
- :placeholder="$t('common.search')"
- >
- <template #prefix>
- <Search class="h-5 w-5 text-gray-300" />
- </template>
- </NInput>
- </div>
- <div class="w-full flex-1 overflow-x-hidden overflow-y-auto p-1 pr-2">
- <Tree :keyword="state.keyword" />
- </div>
- </div>
-
- <div
- class="absolute rounded-full shadow-lg w-6 h-6 top-16 flex items-center justify-center bg-white hover:bg-control-bg cursor-pointer z-1 transition-all"
- :class="[state.expand ? 'left-full -translate-x-3' : '-left-3']"
- @click="state.expand = !state.expand"
- >
- <ChevronLeft
- class="w-4 h-4 transition-transform"
- :class="[state.expand ? '' : '-scale-100 translate-x-[3px]']"
- />
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { ChevronLeft, Search } from "lucide-vue-next";
-import { NInput } from "naive-ui";
-import { computed, reactive } from "vue";
-import { getInstanceResource, hasSchemaProperty } from "@/utils";
-import { useSchemaDiagramContext } from "../common";
-import SchemaSelector from "./SchemaSelector.vue";
-import Tree from "./Tree.vue";
-
-type LocalState = {
- expand: boolean;
- keyword: string;
-};
-
-const state = reactive<LocalState>({
- expand: true,
- keyword: "",
-});
-
-const { databaseMetadata, selectedSchemaNames, database } =
- useSchemaDiagramContext();
-
-const instanceEngine = computed(
- () => getInstanceResource(database.value).engine
-);
-</script>
diff --git a/frontend/src/components/SchemaDiagram/Navigator/SchemaSelector.vue b/frontend/src/components/SchemaDiagram/Navigator/SchemaSelector.vue
deleted file mode 100644
index 0c60b8e410..0000000000
--- a/frontend/src/components/SchemaDiagram/Navigator/SchemaSelector.vue
+++ /dev/null
@@ -1,37 +0,0 @@
-<template>
- <NSelect
- v-bind="$attrs"
- :value="value"
- :multiple="true"
- :clearable="true"
- :options="options"
- :max-tag-count="'responsive'"
- :filterable="true"
- :placeholder="$t('schema-editor.schema.select')"
- @update:value="$emit('update:value', $event)"
- />
-</template>
-
-<script lang="tsx" setup>
-import { NSelect } from "naive-ui";
-import { computed } from "vue";
-import type { SchemaMetadata } from "@/types/proto-es/v1/database_service_pb";
-
-const props = defineProps<{
- value: string[];
- schemas: SchemaMetadata[];
-}>();
-
-defineEmits<{
- (event: "update:value", val: string[]): void;
-}>();
-
-const options = computed(() => {
- return props.schemas.map((schema) => {
- return {
- value: schema.name,
- label: schema.name,
- };
- });
-});
-</script>
diff --git a/frontend/src/components/SchemaDiagram/Navigator/Tree.vue b/frontend/src/components/SchemaDiagram/Navigator/Tree.vue
deleted file mode 100644
index 6b5ea4f439..0000000000
--- a/frontend/src/components/SchemaDiagram/Navigator/Tree.vue
+++ /dev/null
@@ -1,146 +0,0 @@
-<template>
- <NTree
- class="bb-schema-diagram-nav-tree select-none"
- :class="[isFlatTree && 'flat']"
- :data="treeData"
- :block-line="true"
- :pattern="keyword"
- :show-irrelevant-nodes="false"
- :default-expand-all="true"
- :selected-keys="[]"
- :expand-on-click="true"
- :render-label="renderLabel"
- :render-prefix="renderPrefix"
- :render-suffix="renderSuffix"
- :node-props="nodeProps"
- />
-</template>
-
-<script lang="ts" setup>
-import { NTree, type TreeOption } from "naive-ui";
-import { computed, h } from "vue";
-import {
- getInstanceResource,
- hasSchemaProperty,
- isDescendantOf,
-} from "@/utils";
-import { useSchemaDiagramContext } from "../common";
-import { DEFAULT_PADDINGS } from "../common/const";
-import { Label, Prefix, Suffix } from "./TreeNode";
-import type { TreeNode } from "./types";
-import { isTypedNode } from "./utils";
-
-const props = withDefaults(
- defineProps<{
- keyword?: string;
- }>(),
- {
- keyword: "",
- }
-);
-
-const context = useSchemaDiagramContext();
-const { selectedSchemas, events, database } = context;
-
-const isFlatTree = computed(() => {
- return hasSchemaProperty(getInstanceResource(database.value).engine);
-});
-
-const treeData = computed(() => {
- const schemaNodeList = selectedSchemas.value.map<TreeNode<"schema">>(
- (schema) => {
- const children = schema.tables.map<TreeNode<"table">>((table) => {
- return {
- key: table.name,
- label: table.name,
- type: "table",
- data: table,
- isLeaf: true,
- children: [],
- };
- });
- return {
- key: schema.name,
- label: schema.name,
- type: "schema",
- data: schema,
- isLeaf: children.length === 0,
- children,
- };
- }
- );
- if (schemaNodeList.length === 1 && schemaNodeList[0].data.name === "") {
- return schemaNodeList[0].children;
- }
- return schemaNodeList;
-});
-
-// dynamic render the highlight keywords
-const renderLabel = ({ option }: { option: TreeOption }) => {
- const node = option as TreeNode;
- return h(Label, { node, keyword: props.keyword });
-};
-
-// Render icons before nodes.
-const renderPrefix = ({ option }: { option: TreeOption }) => {
- const node = option as TreeNode;
- return h(Prefix, { node });
-};
-
-// Render icons after nodes.
-const renderSuffix = ({ option }: { option: TreeOption }) => {
- const node = option as TreeNode;
- return h(Suffix, { node });
-};
-
-const nodeProps = ({ option }: { option: TreeOption }) => {
- const node = option as TreeNode;
- return {
- onClick(e: MouseEvent) {
- if (node.disabled) return;
-
- if (isDescendantOf(e.target as Element, ".n-tree-node-content")) {
- // Check if clicked on the content part.
- // And ignore the fold/unfold arrow.
- if (isTypedNode(node, "table")) {
- events.emit("set-center", {
- type: "table",
- target: node.data,
- padding: DEFAULT_PADDINGS,
- });
- }
- }
- },
- "data-node-type": node.type,
- };
-};
-</script>
-
-<style lang="postcss">
-.bb-schema-diagram-nav-tree.flat .n-tree-node-switcher {
- display: none !important;
-}
-.bb-schema-diagram-nav-tree .n-tree-node-content {
- padding-left: 0 !important;
-}
-.bb-schema-diagram-nav-tree .n-tree-node-content__prefix {
- flex-shrink: 0;
- margin-right: 0.25rem !important;
-}
-.bb-schema-diagram-nav-tree .n-tree-node-content__text {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- margin-right: 0.25rem;
-}
-.bb-schema-diagram-nav-tree .n-tree-node--pending {
- background-color: transparent !important;
-}
-.bb-schema-diagram-nav-tree .n-tree-node--pending:hover {
- background-color: var(--n-node-color-hover) !important;
-}
-.bb-schema-diagram-nav-tree .n-tree-node--selected,
-.bb-schema-diagram-nav-tree .n-tree-node--selected:hover {
- background-color: var(--n-node-color-active) !important;
-}
-</style>
diff --git a/frontend/src/components/SchemaDiagram/Navigator/TreeNode/Label.vue b/frontend/src/components/SchemaDiagram/Navigator/TreeNode/Label.vue
deleted file mode 100644
index b2cfc51ddc..0000000000
--- a/frontend/src/components/SchemaDiagram/Navigator/TreeNode/Label.vue
+++ /dev/null
@@ -1,44 +0,0 @@
-<template>
- <!-- eslint-disable vue/no-v-html -->
- <div class="flex items-center gap-x-1 max-w-full">
- <span
- class="truncate"
- :data-schema-editor-nav-tree-node-id="id"
- v-html="html"
- />
- <span v-if="isTypedNode(node, 'schema')" class="shrink-0 text-gray-500">
- ({{ node.data.tables.length }})
- </span>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import { useI18n } from "vue-i18n";
-import { getHighlightHTMLByKeyWords } from "@/utils";
-import type { TreeNode } from "../types";
-import { isTypedNode } from "../utils";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const { t } = useI18n();
-
-// render an unique id for every node
-// for auto scroll to the node when tab switches
-const id = computed(() => {
- const { node } = props;
- return `tree-node-label-${node.type}-${node.id}`;
-});
-
-const text = computed(() => {
- const { node } = props;
- return node.data.name || t("db.schema.default");
-});
-
-const html = computed(() => {
- return getHighlightHTMLByKeyWords(text.value, props.keyword);
-});
-</script>
diff --git a/frontend/src/components/SchemaDiagram/Navigator/TreeNode/Prefix.vue b/frontend/src/components/SchemaDiagram/Navigator/TreeNode/Prefix.vue
deleted file mode 100644
index 4d88ba9330..0000000000
--- a/frontend/src/components/SchemaDiagram/Navigator/TreeNode/Prefix.vue
+++ /dev/null
@@ -1,17 +0,0 @@
-<template>
- <template v-if="node.type === 'schema'">
- <Layers class="w-4 h-4" />
- </template>
- <template v-if="node.type === 'table'">
- <Table2 class="w-4 h-4" />
- </template>
-</template>
-
-<script lang="ts" setup>
-import { Layers, Table2 } from "lucide-vue-next";
-import type { TreeNode } from "../types";
-
-defineProps<{
- node: TreeNode;
-}>();
-</script>
diff --git a/frontend/src/components/SchemaDiagram/Navigator/TreeNode/Suffix.vue b/frontend/src/components/SchemaDiagram/Navigator/TreeNode/Suffix.vue
deleted file mode 100644
index bfdbacb08a..0000000000
--- a/frontend/src/components/SchemaDiagram/Navigator/TreeNode/Suffix.vue
+++ /dev/null
@@ -1,27 +0,0 @@
-<template>
- <template v-if="node.type === 'schema'">
- <!-- nothing -->
- </template>
- <template v-if="node.type === 'table'">
- <FocusButton
- :table="(node as TreeNode<'table'>).data"
- :set-center="true"
- class="focus-btn"
- />
- </template>
-</template>
-
-<script lang="ts" setup>
-import { FocusButton } from "../../common";
-import type { TreeNode } from "../types";
-
-defineProps<{
- node: TreeNode;
-}>();
-</script>
-
-<style lang="postcss">
-.bb-schema-diagram-nav-tree .n-tree-node:hover .focus-btn {
- visibility: visible !important;
-}
-</style>
diff --git a/frontend/src/components/SchemaDiagram/Navigator/TreeNode/index.ts b/frontend/src/components/SchemaDiagram/Navigator/TreeNode/index.ts
deleted file mode 100644
index b27f779ae4..0000000000
--- a/frontend/src/components/SchemaDiagram/Navigator/TreeNode/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import Label from "./Label.vue";
-import Prefix from "./Prefix.vue";
-import Suffix from "./Suffix.vue";
-
-export { Label, Prefix, Suffix };
diff --git a/frontend/src/components/SchemaDiagram/Navigator/index.ts b/frontend/src/components/SchemaDiagram/Navigator/index.ts
deleted file mode 100644
index 28c17659a6..0000000000
--- a/frontend/src/components/SchemaDiagram/Navigator/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import Navigator from "./Navigator.vue";
-
-export default Navigator;
diff --git a/frontend/src/components/SchemaDiagram/Navigator/utils.ts b/frontend/src/components/SchemaDiagram/Navigator/utils.ts
deleted file mode 100644
index d89761b645..0000000000
--- a/frontend/src/components/SchemaDiagram/Navigator/utils.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import type { NodeType, TreeNode } from "./types";
-
-export const isTypedNode = <T extends NodeType>(
- node: TreeNode,
- type: T
-): node is TreeNode<T> => {
- return node.type === type;
-};
diff --git a/frontend/src/components/SchemaDiagram/SchemaDiagram.vue b/frontend/src/components/SchemaDiagram/SchemaDiagram.vue
deleted file mode 100644
index ba4373b475..0000000000
--- a/frontend/src/components/SchemaDiagram/SchemaDiagram.vue
+++ /dev/null
@@ -1,265 +0,0 @@
-<template>
- <div class="w-full h-full relative overflow-hidden flex">
- <Navigator />
-
- <Canvas class="flex-1">
- <template #desktop>
- <template v-for="(schema, i) in selectedSchemas" :key="`schema-${i}`">
- <TableNode
- v-for="table in schema.tables"
- :key="idOfTable(table)"
- :schema="schema"
- :table="table"
- :class="initialized ? '' : 'invisible'"
- />
- </template>
-
- <template v-if="initialized">
- <ForeignKeyLine v-for="(fk, i) in foreignKeys" :key="i" :fk="fk" />
- </template>
- </template>
-
- <div
- v-if="busy || !initialized"
- class="absolute inset-0 bg-white/40 flex items-center justify-center"
- >
- <BBSpin />
- </div>
- </Canvas>
- </div>
-</template>
-
-<script lang="ts" setup>
-import Emittery from "emittery";
-import { uniqueId } from "lodash-es";
-import { computed, nextTick, ref, toRef, watch } from "vue";
-import { BBSpin } from "@/bbkit";
-import type {
- ColumnMetadata,
- Database,
- DatabaseMetadata,
- SchemaMetadata,
- TableMetadata,
-} from "@/types/proto-es/v1/database_service_pb";
-import Canvas from "./Canvas";
-import { provideSchemaDiagramContext } from "./common";
-import type { GraphEdgeItem, GraphNodeItem } from "./ER";
-import { autoLayout, ForeignKeyLine, TableNode } from "./ER";
-import Navigator from "./Navigator";
-import type {
- EditStatus,
- ForeignKey,
- Geometry,
- Point,
- Rect,
- SchemaDiagramContext,
- Size,
-} from "./types";
-
-const props = withDefaults(
- defineProps<{
- database: Database;
- databaseMetadata: DatabaseMetadata;
- editable?: boolean;
- schemaStatus?: (schema: SchemaMetadata) => EditStatus;
- tableStatus?: (table: TableMetadata) => EditStatus;
- columnStatus?: (column: ColumnMetadata) => EditStatus;
- }>(),
- {
- editable: false,
- schemaStatus: () => "normal" as EditStatus,
- tableStatus: () => "normal" as EditStatus,
- columnStatus: () => "normal" as EditStatus,
- }
-);
-
-const emit = defineEmits<{
- (event: "edit-table", schema: SchemaMetadata, table: TableMetadata): void;
- (
- event: "edit-column",
- schema: SchemaMetadata,
- table: TableMetadata,
- column: ColumnMetadata,
- target: "name" | "type"
- ): void;
-}>();
-
-const initialized = ref(false);
-const dummy = ref(false);
-const busy = ref(false);
-const zoom = ref(1);
-const position = ref<Point>({ x: 0, y: 0 });
-const panning = ref(false);
-const geometries = ref(new Set<Geometry>());
-const focusedTables = ref(new Set<TableMetadata>());
-const selectedSchemaNames = ref<string[]>([]);
-
-const selectedSchemas = computed(() => {
- return props.databaseMetadata.schemas.filter((schema) =>
- selectedSchemaNames.value.includes(schema.name)
- );
-});
-
-const render = () => {
- nextTick(() => {
- events.emit("render");
- });
-};
-
-const events: SchemaDiagramContext["events"] = new Emittery();
-
-const tableIds = ref(new WeakMap<TableMetadata, string>());
-const rectsByTableId = ref(new Map<string, Rect>());
-const foreignKeys = computed((): ForeignKey[] => {
- const find = (s: string, t: string, c: string) => {
- const schema = selectedSchemas.value.find((schema) => schema.name === s);
- const table = schema?.tables.find((table) => table.name === t);
- const column = c;
- return { schema, table, column };
- };
- const fks: ForeignKey[] = [];
- selectedSchemas.value.forEach((schema) => {
- schema.tables.forEach((table) => {
- table.foreignKeys.forEach((fkMetadata) => {
- const {
- columns,
- referencedSchema,
- referencedTable,
- referencedColumns,
- } = fkMetadata;
- for (let i = 0; i < columns.length; i++) {
- const to = find(
- referencedSchema,
- referencedTable,
- referencedColumns[i]
- );
- if (to.schema && to.table) {
- fks.push({
- from: { schema, table, column: columns[i] },
- to,
- metadata: fkMetadata,
- } as ForeignKey);
- }
- }
- });
- });
- });
-
- return fks;
-});
-
-const idOfTable = (table: TableMetadata): string => {
- const ids = tableIds.value;
- if (ids.has(table)) return ids.get(table)!;
- const id = `table-${table.name}-${uniqueId()}`;
- ids.set(table, id);
- return id;
-};
-
-const rectOfTable = (table: TableMetadata): Rect => {
- const id = idOfTable(table);
- return rectsByTableId.value.get(id) ?? { x: 0, y: 0, width: 0, height: 0 };
-};
-
-const layout = () => {
- return nextTick(async () => {
- const nodeList = selectedSchemas.value
- .flatMap((schema) => {
- return schema.tables.map((table) => {
- const id = idOfTable(table);
- const elem = document.querySelector(`[bb-node-id="${id}"]`)!;
- return {
- group: `schema-${schema.name}`,
- table,
- id,
- elem,
- };
- });
- })
- .filter((item) => !!item.elem)
- .map<GraphNodeItem>((item) => {
- const size: Size = {
- width: item.elem.clientWidth,
- height: item.elem.clientHeight,
- };
- return {
- group: item.group,
- id: item.id,
- size,
- children: [],
- };
- });
-
- const edgeList = foreignKeys.value.map<GraphEdgeItem>((fk) => {
- const { from, to } = fk;
- const fromTableId = idOfTable(from.table);
- const toTableId = idOfTable(to.table);
- return {
- id: `${from.schema.name}.${fromTableId}.${from.column}->${to.schema.name}.${toTableId}.${to.column}`,
- from: fromTableId,
- to: toTableId,
- };
- });
- const { rects } = await autoLayout(nodeList, edgeList);
- for (const [id, rect] of rects) {
- rectsByTableId.value.set(id, rect);
- }
-
- render();
- });
-};
-
-events.on("layout", layout);
-events.on("edit-table", ({ schema, table }) =>
- emit("edit-table", schema, table)
-);
-events.on("edit-column", ({ schema, table, column, target }) =>
- emit("edit-column", schema, table, column, target)
-);
-
-provideSchemaDiagramContext({
- database: toRef(props, "database"),
- databaseMetadata: toRef(props, "databaseMetadata"),
- editable: computed(() => props.editable),
- foreignKeys,
- dummy,
- busy,
- zoom,
- position,
- panning,
- geometries,
- focusedTables,
- idOfTable,
- rectOfTable,
- render,
- layout,
- schemaStatus: props.schemaStatus,
- tableStatus: props.tableStatus,
- columnStatus: props.columnStatus,
- events,
- selectedSchemaNames,
- selectedSchemas,
-});
-
-// autoLayout and fit view at the first time the diagram is mounted.
-watch(
- () => props.databaseMetadata,
- () => {
- selectedSchemaNames.value = [props.databaseMetadata.schemas[0]?.name ?? ""];
- },
- { immediate: true }
-);
-
-watch(
- () => selectedSchemaNames.value,
- async () => {
- focusedTables.value = new Set();
- await layout();
- initialized.value = true;
- nextTick(() => {
- events.emit("fit-view");
- });
- },
- { immediate: true }
-);
-</script>
diff --git a/frontend/src/components/SchemaDiagram/common/FocusButton.vue b/frontend/src/components/SchemaDiagram/common/FocusButton.vue
deleted file mode 100644
index af69d03c0c..0000000000
--- a/frontend/src/components/SchemaDiagram/common/FocusButton.vue
+++ /dev/null
@@ -1,55 +0,0 @@
-<template>
- <button
- class="p-0.5 rounded-sm hover:bg-gray-200"
- :class="[isFocused && focusedClass, isFocused ? 'visible!' : 'invisible']"
- @click="toggleFocus"
- >
- <!-- TODO(Jim): replace this raw SVG with heroicons-outline:viewfinder-circle when supported -->
- <FocusIcon class="w-4 h-4" />
- </button>
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import type { TableMetadata } from "@/types/proto-es/v1/database_service_pb";
-import type { VueClass } from "@/utils";
-import { expectedZoomRange, useSchemaDiagramContext } from ".";
-import { DEFAULT_PADDINGS } from "./const";
-import FocusIcon from "./FocusIcon.vue";
-
-const props = withDefaults(
- defineProps<{
- table: TableMetadata;
- focusedClass?: VueClass;
- setCenter?: boolean;
- }>(),
- {
- focusedClass: "",
- setCenter: true,
- }
-);
-
-const { zoom, focusedTables, events } = useSchemaDiagramContext();
-
-const isFocused = computed(() => {
- return focusedTables.value.has(props.table);
-});
-
-const toggleFocus = (e: Event) => {
- e.stopPropagation();
- const on = !isFocused.value;
- if (on) {
- focusedTables.value.add(props.table);
- } else {
- focusedTables.value.delete(props.table);
- }
- if (props.setCenter) {
- events.emit("set-center", {
- type: "table",
- target: props.table,
- padding: DEFAULT_PADDINGS,
- zooms: on ? expectedZoomRange(zoom.value, 0.5, 1) : undefined,
- });
- }
-};
-</script>
diff --git a/frontend/src/components/SchemaDiagram/common/FocusIcon.vue b/frontend/src/components/SchemaDiagram/common/FocusIcon.vue
deleted file mode 100644
index 325911668a..0000000000
--- a/frontend/src/components/SchemaDiagram/common/FocusIcon.vue
+++ /dev/null
@@ -1,15 +0,0 @@
-<template>
- <svg
- xmlns="http://www.w3.org/2000/svg"
- fill="none"
- viewBox="0 0 24 24"
- stroke-width="2"
- stroke="currentColor"
- >
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- d="M7.5 3.75H6A2.25 2.25 0 003.75 6v1.5M16.5 3.75H18A2.25 2.25 0 0120.25 6v1.5m0 9V18A2.25 2.25 0 0118 20.25h-1.5m-9 0H6A2.25 2.25 0 013.75 18v-1.5M15 12a3 3 0 11-6 0 3 3 0 016 0z"
- />
- </svg>
-</template>
diff --git a/frontend/src/components/SchemaDiagram/common/context.ts b/frontend/src/components/SchemaDiagram/common/context.ts
deleted file mode 100644
index 181a2aec24..0000000000
--- a/frontend/src/components/SchemaDiagram/common/context.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import type { InjectionKey } from "vue";
-import { inject, provide, unref, watchEffect } from "vue";
-import type { MaybeRef } from "@/types";
-import type { Geometry, SchemaDiagramContext } from "../types";
-
-export const KEY = Symbol(
- "bb.schema-diagram"
-) as InjectionKey<SchemaDiagramContext>;
-
-export const useSchemaDiagramContext = () => {
- return inject(KEY)!;
-};
-
-export const provideSchemaDiagramContext = (context: SchemaDiagramContext) => {
- provide(KEY, context);
-};
-
-export const useGeometry = (geometry: MaybeRef<Geometry>) => {
- const context = useSchemaDiagramContext();
- if (context.dummy.value) return;
- watchEffect((onCleanup) => {
- const g = unref(geometry);
- context.geometries.value.add(g);
- onCleanup(() => {
- context.geometries.value.delete(g);
- });
- });
-};
diff --git a/frontend/src/components/SchemaDiagram/common/useDraggable.ts b/frontend/src/components/SchemaDiagram/common/useDraggable.ts
deleted file mode 100644
index cc966c22a6..0000000000
--- a/frontend/src/components/SchemaDiagram/common/useDraggable.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { useEventListener } from "@vueuse/core";
-import { type MaybeRef, ref, unref } from "vue";
-import type { Point } from "../types";
-
-export type DraggableOptions = {
- exact?: boolean;
- onStart?: () => void;
- onPan?: (dx: number, dy: number) => void;
- onEnd?: () => void;
- capture?: boolean;
-};
-
-export const useDraggable = (
- target: MaybeRef<Element | undefined>,
- options: DraggableOptions
-) => {
- const startPointerPosition = ref<Point>();
- const lastPointerPosition = ref<Point>();
-
- const start = (e: PointerEvent) => {
- if (unref(options.exact) && e.target !== unref(target)) return;
- startPointerPosition.value = {
- x: e.screenX,
- y: e.screenY,
- };
- lastPointerPosition.value = {
- x: e.screenX,
- y: e.screenY,
- };
- e.stopPropagation();
- e.preventDefault();
- options.onStart?.();
- };
- const move = (e: PointerEvent) => {
- if (!startPointerPosition.value) return;
- if (!lastPointerPosition.value) return;
- const pointer = { x: e.screenX, y: e.screenY };
- e.stopPropagation();
- e.preventDefault();
- options.onPan?.(
- pointer.x - lastPointerPosition.value.x,
- pointer.y - lastPointerPosition.value.y
- );
- lastPointerPosition.value = pointer;
- };
- const end = (e: PointerEvent) => {
- startPointerPosition.value = undefined;
- e.stopPropagation();
- e.preventDefault();
- options.onEnd?.();
- };
-
- const capture = options.capture ?? false;
- useEventListener(target, "pointerdown", start, capture);
- useEventListener(window, "pointermove", move, capture);
- useEventListener(window, "pointerup", end, capture);
-};
diff --git a/frontend/src/components/SchemaDiagram/index.ts b/frontend/src/components/SchemaDiagram/index.ts
index 6ab3b81e11..918a1ec541 100644
--- a/frontend/src/components/SchemaDiagram/index.ts
+++ b/frontend/src/components/SchemaDiagram/index.ts
@@ -1,8 +1,8 @@
-import SchemaDiagram from "./SchemaDiagram.vue";
+// The heavy SchemaDiagram surface (Canvas, Navigator, ER, FK lines,
+// auto-layout, ...) was migrated to React on 2026-04-29. The remaining
+// Vue surfaces here only consume the small `SchemaDiagramIcon` SVG;
+// every other consumer mounts the React diagram via `ReactPageMount`
+// (page="SchemaDiagramPage").
import SchemaDiagramIcon from "./SchemaDiagramIcon.vue";
-export * from "./types";
-
-export { SchemaDiagram, SchemaDiagramIcon };
-
-export default SchemaDiagram;
+export { SchemaDiagramIcon };
diff --git a/frontend/src/components/SchemaDiagram/types/context.ts b/frontend/src/components/SchemaDiagram/types/context.ts
deleted file mode 100644
index 69c116be6f..0000000000
--- a/frontend/src/components/SchemaDiagram/types/context.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import type Emittery from "emittery";
-import type { Ref } from "vue";
-import type {
- ColumnMetadata,
- Database,
- DatabaseMetadata,
- SchemaMetadata,
- TableMetadata,
-} from "@/types/proto-es/v1/database_service_pb";
-import type { EditStatus } from "./edit";
-import type { Geometry, Point, Rect } from "./geometry";
-import type { ForeignKey } from "./schema";
-
-// This is an abstract Schema Diagram context including states, methods and
-// events. This should be implemented in the root component of SchemaDiagram
-// and used in its descendants.
-export type SchemaDiagramContext = {
- // Props
- database: Ref<Database>;
- databaseMetadata: Ref<DatabaseMetadata>;
- editable: Ref<boolean>;
-
- // States
- foreignKeys: Ref<ForeignKey[]>;
- dummy: Ref<boolean>;
- busy: Ref<boolean>;
- zoom: Ref<number>;
- position: Ref<Point>;
- panning: Ref<boolean>;
- geometries: Ref<Set<Geometry>>;
- focusedTables: Ref<Set<TableMetadata>>;
- selectedSchemaNames: Ref<string[]>;
- selectedSchemas: Ref<SchemaMetadata[]>;
-
- // Methods
- idOfTable: (table: TableMetadata) => string;
- rectOfTable: (table: TableMetadata) => Rect;
- // tell the components to re-calculate positions if needed
- render: () => void;
- // auto-layout all components
- layout: () => void;
- schemaStatus: (schema: SchemaMetadata) => EditStatus;
- tableStatus: (table: TableMetadata) => EditStatus;
- columnStatus: (column: ColumnMetadata) => EditStatus;
-
- // Events
- events: Emittery<{
- render: undefined;
- layout: undefined;
- "fit-view": undefined;
- "edit-table": { schema: SchemaMetadata; table: TableMetadata };
- "edit-column": {
- schema: SchemaMetadata;
- table: TableMetadata;
- column: ColumnMetadata;
- target: "name" | "type";
- };
- "set-center": CenterTarget;
- }>;
-};
-
-export type CenterTargetType = "table" | "rect" | "point";
-export type CenterTarget<T extends CenterTargetType = CenterTargetType> = {
- type: T;
- target: {
- table: TableMetadata;
- rect: Rect;
- point: Point;
- }[T];
- padding?: number[]; // [T,R,B,L]
- zooms?: number[]; // [min, max]
-};
diff --git a/frontend/src/react/components/SchemaDiagram/Canvas/Canvas.tsx b/frontend/src/react/components/SchemaDiagram/Canvas/Canvas.tsx
new file mode 100644
index 0000000000..89fdfa2855
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Canvas/Canvas.tsx
@@ -0,0 +1,109 @@
+import { Image, LayoutGrid } from "lucide-react";
+import { type ReactNode, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { ZOOM_RANGE } from "../common/const";
+import { useSchemaDiagramContext } from "../common/context";
+import { useDragCanvas, useFitView, useSetCenter } from "./composables";
+import { useScreenshot } from "./composables/useScreenshot";
+import { ZoomButton } from "./ZoomButton";
+
+interface CanvasProps {
+ /** Diagram content (TableNodes, FK lines) — placed inside the
+ * transformed `desktop` layer. */
+ children?: ReactNode;
+ /** Extra control buttons rendered to the left of the screenshot /
+ * fit / zoom group. */
+ controls?: ReactNode;
+ /**
+ * When provided, the screenshot button is shown and clicking it runs
+ * `html-to-image` on the canvas DOM, downloading + copying the result.
+ * Omit to hide the button entirely.
+ */
+ screenshotFilename?: () => string;
+}
+
+/**
+ * React port of `Canvas/Canvas.vue`. The viewport: applies a CSS
+ * `transform: matrix(zoom, 0, 0, zoom, x, y)` to a desktop layer and
+ * mounts the zoom + fit + screenshot button group at the bottom-right.
+ */
+export function Canvas({
+ children,
+ controls,
+ screenshotFilename,
+}: CanvasProps) {
+ const { t } = useTranslation();
+ const ctx = useSchemaDiagramContext();
+ const { zoom, position } = ctx;
+
+ const [canvas, setCanvas] = useState<HTMLDivElement | null>(null);
+ const [desktop, setDesktop] = useState<HTMLDivElement | null>(null);
+ const handleFitView = useFitView(canvas);
+ const { handleZoom } = useDragCanvas(canvas);
+ useSetCenter(canvas);
+ const { capture, capturing } = useScreenshot(
+ { canvas, desktop },
+ { filename: screenshotFilename ?? (() => "schema-diagram.png") }
+ );
+
+ return (
+ <div
+ ref={setCanvas}
+ className="w-full h-full relative bg-control-bg overflow-hidden"
+ >
+ <div
+ ref={setDesktop}
+ className="absolute overflow-visible"
+ style={{
+ transformOrigin: "0 0 0",
+ transform: `matrix(${zoom}, 0, 0, ${zoom}, ${position.x}, ${position.y})`,
+ }}
+ >
+ {children}
+ </div>
+
+ <div
+ className="absolute right-2 bottom-2 flex items-center gap-x-2"
+ data-screenshot-hide
+ >
+ {controls}
+
+ {screenshotFilename && (
+ <Tooltip content="Screenshot" side="top">
+ <Button
+ variant="outline"
+ size="xs"
+ onClick={() => void capture()}
+ disabled={capturing}
+ aria-label="Screenshot"
+ className="bg-background"
+ >
+ <Image className="size-3" />
+ </Button>
+ </Tooltip>
+ )}
+
+ <Tooltip content={t("schema-diagram.fit-content-with-view")} side="top">
+ <Button
+ variant="outline"
+ size="xs"
+ onClick={handleFitView}
+ aria-label={t("schema-diagram.fit-content-with-view")}
+ className="bg-background"
+ >
+ <LayoutGrid className="size-3" />
+ </Button>
+ </Tooltip>
+
+ <ZoomButton
+ min={ZOOM_RANGE.min}
+ max={ZOOM_RANGE.max}
+ onZoomIn={() => handleZoom(0.1)}
+ onZoomOut={() => handleZoom(-0.1)}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/SchemaDiagram/Canvas/ZoomButton.tsx b/frontend/src/react/components/SchemaDiagram/Canvas/ZoomButton.tsx
new file mode 100644
index 0000000000..11ab0969f1
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Canvas/ZoomButton.tsx
@@ -0,0 +1,49 @@
+import { Minus, Plus } from "lucide-react";
+import { useMemo } from "react";
+import { Button } from "@/react/components/ui/button";
+import { cn } from "@/react/lib/utils";
+import { useSchemaDiagramContext } from "../common/context";
+
+interface ZoomButtonProps {
+ min: number;
+ max: number;
+ onZoomIn: () => void;
+ onZoomOut: () => void;
+}
+
+/**
+ * React port of `Canvas/ZoomButton.vue`. A three-button group: minus,
+ * current zoom (read-only label), plus.
+ */
+export function ZoomButton({ min, max, onZoomIn, onZoomOut }: ZoomButtonProps) {
+ const { zoom } = useSchemaDiagramContext();
+ const display = useMemo(() => `${Math.round(zoom * 100)}%`, [zoom]);
+
+ return (
+ <div className="bg-background rounded-sm flex items-center gap-x-px">
+ <Button
+ variant="outline"
+ size="xs"
+ onClick={onZoomOut}
+ disabled={zoom <= min}
+ className={cn("rounded-r-none px-2")}
+ aria-label="Zoom out"
+ >
+ <Minus className="size-3" />
+ </Button>
+ <div className="px-2 h-6 inline-flex items-center justify-center text-xs border-y border-control-border bg-background">
+ <span className="w-8 text-center">{display}</span>
+ </div>
+ <Button
+ variant="outline"
+ size="xs"
+ onClick={onZoomIn}
+ disabled={zoom >= max}
+ className={cn("rounded-l-none px-2")}
+ aria-label="Zoom in"
+ >
+ <Plus className="size-3" />
+ </Button>
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/SchemaDiagram/Canvas/composables/index.ts b/frontend/src/react/components/SchemaDiagram/Canvas/composables/index.ts
new file mode 100644
index 0000000000..3528ffc1fa
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Canvas/composables/index.ts
@@ -0,0 +1,4 @@
+export { useDragCanvas } from "./useDragCanvas";
+export { useFitView } from "./useFitView";
+export { useScreenshot } from "./useScreenshot";
+export { useSetCenter } from "./useSetCenter";
diff --git a/frontend/src/react/components/SchemaDiagram/Canvas/composables/useDragCanvas.tsx b/frontend/src/react/components/SchemaDiagram/Canvas/composables/useDragCanvas.tsx
new file mode 100644
index 0000000000..3005e83ee5
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Canvas/composables/useDragCanvas.tsx
@@ -0,0 +1,84 @@
+import normalizeWheel from "normalize-wheel";
+import { useCallback, useEffect, useRef } from "react";
+import { minmax } from "@/utils/math";
+import { ZOOM_RANGE } from "../../common/const";
+import { useSchemaDiagramContext } from "../../common/context";
+import { useDraggable } from "../../common/useDraggable";
+import type { Point } from "../../types";
+
+/**
+ * React port of `Canvas/composables/useDragCanvas.ts`.
+ *
+ * Wires the canvas element for drag-to-pan and wheel-to-zoom. Returns
+ * `handleZoom(delta, center?)` which the zoom button group calls
+ * imperatively.
+ */
+export const useDragCanvas = (canvas: Element | null) => {
+ const ctx = useSchemaDiagramContext();
+ const { zoom, position, setZoom, setPosition, setPanning } = ctx;
+
+ // Capture latest values without re-running the wheel listener every render.
+ const stateRef = useRef({ zoom, position });
+ stateRef.current = { zoom, position };
+
+ const handleZoom = useCallback(
+ (delta: number, center: Point = { x: 0.5, y: 0.5 }) => {
+ if (!canvas) return;
+ const { zoom: prevZoom, position: prevPos } = stateRef.current;
+ const z = minmax(prevZoom + delta, ZOOM_RANGE.min, ZOOM_RANGE.max);
+ const factor = z / prevZoom;
+ setZoom(z);
+
+ const { width, height } = canvas.getBoundingClientRect();
+ const cx = center.x * width;
+ const cy = center.y * height;
+ setPosition({
+ x: cx - factor * (cx - prevPos.x),
+ y: cy - factor * (cy - prevPos.y),
+ });
+ },
+ [canvas, setZoom, setPosition]
+ );
+
+ const handleZoomRef = useRef(handleZoom);
+ handleZoomRef.current = handleZoom;
+
+ // Drag-to-pan via the shared useDraggable hook.
+ useDraggable(canvas, {
+ exact: false,
+ onPan: (dx, dy) => {
+ const { position: prev } = stateRef.current;
+ setPosition({ x: prev.x + dx, y: prev.y + dy });
+ setPanning(true);
+ },
+ onEnd: () => {
+ requestAnimationFrame(() => setPanning(false));
+ },
+ });
+
+ // Wheel-to-zoom. Capture phase mirrors Vue's `useEventListener(..., true)`.
+ useEffect(() => {
+ if (!canvas) return;
+ const handler = (e: WheelEvent) => {
+ const ne = normalizeWheel(e);
+ const scrollDelta = -ne.pixelY;
+ const delta = scrollDelta / 250; // tuned for trackpad / mouse parity
+ const rect = canvas.getBoundingClientRect();
+ const center = {
+ x: (e.pageX - rect.left) / rect.width,
+ y: (e.pageY - rect.top) / rect.height,
+ };
+ handleZoomRef.current(delta, center);
+ e.preventDefault();
+ e.stopPropagation();
+ };
+ canvas.addEventListener("mousewheel", handler as EventListener, true);
+ canvas.addEventListener("wheel", handler as EventListener, true);
+ return () => {
+ canvas.removeEventListener("mousewheel", handler as EventListener, true);
+ canvas.removeEventListener("wheel", handler as EventListener, true);
+ };
+ }, [canvas]);
+
+ return { handleZoom };
+};
diff --git a/frontend/src/react/components/SchemaDiagram/Canvas/composables/useFitView.tsx b/frontend/src/react/components/SchemaDiagram/Canvas/composables/useFitView.tsx
new file mode 100644
index 0000000000..cdd81136a4
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Canvas/composables/useFitView.tsx
@@ -0,0 +1,41 @@
+import { useCallback, useEffect, useRef } from "react";
+import { DEFAULT_PADDINGS, ZOOM_RANGE } from "../../common/const";
+import { useSchemaDiagramContext } from "../../common/context";
+import { fitView } from "../libs/fitView";
+
+/**
+ * React port of `Canvas/composables/useFitView.ts`.
+ *
+ * Returns a `handleFitView()` callback the zoom buttons / external code
+ * can invoke imperatively, AND subscribes to the context's `fit-view`
+ * Emittery channel so other parts of the diagram can request a fit
+ * without holding a ref.
+ */
+export const useFitView = (canvas: Element | null) => {
+ const ctx = useSchemaDiagramContext();
+ const { setZoom, setPosition, geometries, events } = ctx;
+
+ 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]);
+
+ const handleFitViewRef = useRef(handleFitView);
+ handleFitViewRef.current = handleFitView;
+
+ useEffect(() => {
+ const off = events.on("fit-view", () => {
+ handleFitViewRef.current();
+ });
+ return () => {
+ off();
+ };
+ }, [events]);
+
+ return handleFitView;
+};
diff --git a/frontend/src/react/components/SchemaDiagram/Canvas/composables/useScreenshot.tsx b/frontend/src/react/components/SchemaDiagram/Canvas/composables/useScreenshot.tsx
new file mode 100644
index 0000000000..8782393fb3
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Canvas/composables/useScreenshot.tsx
@@ -0,0 +1,126 @@
+import { useCallback, useState } from "react";
+import { pushNotification } from "@/store";
+import { useSchemaDiagramContext } from "../../common/context";
+import { calcBBox } from "../../common/geometry";
+
+const HIDE_FLAG_ATTR = "data-bb-screenshot-active";
+const CAPTURE_PADDING = 40;
+
+interface UseScreenshotOptions {
+ /** Callback that resolves the desired filename (e.g. `${db}.png`). */
+ filename: () => string;
+}
+
+interface UseScreenshotTargets {
+ /** The outer canvas (clipped viewport). Used only as a fallback. */
+ canvas: Element | null;
+ /**
+ * The inner `desktop` layer. `overflow-visible`, holds the diagram at
+ * natural coordinates with its own transform. We capture this so
+ * tables/FK lines outside the visible viewport are still included.
+ */
+ desktop: Element | null;
+}
+
+/**
+ * Capture the SchemaDiagram canvas as a PNG. Targets the inner `desktop`
+ * layer (not the outer viewport — that's `overflow-hidden` and would
+ * clip large schemas to whatever fits on screen). Computes the natural
+ * bbox from the geometries the diagram has registered with the context,
+ * then overrides the cloned node's transform + dimensions so
+ * `html-to-image` captures the full extent at zoom 1.
+ *
+ * Returns:
+ * - `capture()` — async, opens the download + copies to clipboard
+ * - `capturing` — boolean, true while the capture is in flight
+ */
+export function useScreenshot(
+ targets: UseScreenshotTargets,
+ { filename }: UseScreenshotOptions
+) {
+ const ctx = useSchemaDiagramContext();
+ const { setBusy, geometries } = ctx;
+ const [capturing, setCapturing] = useState(false);
+
+ const capture = useCallback(async () => {
+ const { canvas, desktop } = targets;
+ const target = desktop ?? canvas;
+ if (!target || capturing) return;
+ setCapturing(true);
+ setBusy(true);
+ // Mark the document so the CSS rule that hides `data-screenshot-hide`
+ // affordances (zoom buttons, schema selector, etc.) takes effect on
+ // the cloned subtree.
+ document.body.setAttribute(HIDE_FLAG_ATTR, "true");
+
+ try {
+ const [{ toBlob }, { default: download }] = await Promise.all([
+ import("html-to-image"),
+ import("downloadjs"),
+ ]);
+
+ // Compute the natural bbox from registered geometries (TableNodes
+ // call `useGeometry(rect)` and ForeignKeyLines call
+ // `useGeometry(path)`). Add padding so edges aren't flush against
+ // the PNG border.
+ const bbox = calcBBox([...geometries]);
+ const captureWidth = Math.max(
+ Math.ceil(bbox.width + bbox.x + CAPTURE_PADDING * 2),
+ 100
+ );
+ const captureHeight = Math.max(
+ Math.ceil(bbox.height + bbox.y + CAPTURE_PADDING * 2),
+ 100
+ );
+
+ const blob = await toBlob(target as HTMLElement, {
+ pixelRatio: 1,
+ quality: 0.9,
+ width: captureWidth,
+ height: captureHeight,
+ // The cloned root style — overrides the live transform/size so
+ // the capture renders at zoom 1 with origin shifted to (padding,
+ // padding). Children (TableNodes, FK lines) keep their absolute
+ // positions in natural coordinates and are visible because the
+ // desktop layer is `overflow-visible`.
+ style: {
+ transform: `translate(${CAPTURE_PADDING}px, ${CAPTURE_PADDING}px) scale(1)`,
+ transformOrigin: "0 0",
+ width: `${captureWidth}px`,
+ height: `${captureHeight}px`,
+ backgroundColor: "white",
+ },
+ });
+ if (blob) {
+ download(blob, filename(), blob.type);
+ try {
+ const data = [new window.ClipboardItem({ [blob.type]: blob })];
+ await navigator.clipboard.write(data);
+ } catch {
+ // ClipboardItem may be unavailable (Firefox < 127 etc.) — the
+ // download itself still succeeded, so swallow this branch.
+ }
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title:
+ "Screenshot generated successfully and copied to the clipboard!",
+ });
+ }
+ } catch (err) {
+ console.error("Screenshot failed", err);
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: "Screenshot failed",
+ description: String(err),
+ });
+ } finally {
+ document.body.removeAttribute(HIDE_FLAG_ATTR);
+ setCapturing(false);
+ setBusy(false);
+ }
+ }, [targets, capturing, filename, setBusy, geometries]);
+
+ return { capture, capturing };
+}
diff --git a/frontend/src/react/components/SchemaDiagram/Canvas/composables/useSetCenter.tsx b/frontend/src/react/components/SchemaDiagram/Canvas/composables/useSetCenter.tsx
new file mode 100644
index 0000000000..8f9e1e2c61
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Canvas/composables/useSetCenter.tsx
@@ -0,0 +1,61 @@
+import { useEffect, useRef } from "react";
+import { DEFAULT_PADDINGS } from "../../common/const";
+import { useSchemaDiagramContext } from "../../common/context";
+import type { CenterTarget, CenterTargetType, Rect } from "../../types";
+import { fitView } from "../libs/fitView";
+
+const isTypedCenterTarget = <T extends CenterTargetType>(
+ e: CenterTarget,
+ type: T
+): e is CenterTarget<T> => e.type === type;
+
+/**
+ * React port of `Canvas/composables/useSetCenter.ts`. Subscribes to
+ * `set-center` events and animates `(zoom, position)` onto the
+ * target — a table, rect, or point.
+ */
+export const useSetCenter = (canvas: Element | null) => {
+ const ctx = useSchemaDiagramContext();
+ const { zoom, setZoom, setPosition, events, rectOfTable } = ctx;
+
+ // Capture latest dependency values for the event handler so we don't
+ // have to re-subscribe on every state update.
+ const stateRef = useRef({ canvas, zoom, setZoom, setPosition, rectOfTable });
+ stateRef.current = { canvas, zoom, setZoom, setPosition, rectOfTable };
+
+ useEffect(() => {
+ const off = events.on("set-center", (e) => {
+ const {
+ canvas: el,
+ zoom: currentZoom,
+ setZoom: applyZoom,
+ setPosition: applyPosition,
+ rectOfTable: lookupRect,
+ } = stateRef.current;
+ if (!el) return;
+
+ const padding = e.padding ?? DEFAULT_PADDINGS;
+ const zooms = e.zooms ?? [currentZoom, currentZoom];
+
+ let rect: Rect | null = null;
+ if (isTypedCenterTarget(e, "point")) {
+ const center = e.target;
+ rect = { ...center, width: 0, height: 0 };
+ } else if (isTypedCenterTarget(e, "rect")) {
+ rect = e.target;
+ } else if (isTypedCenterTarget(e, "table")) {
+ rect = lookupRect(e.target);
+ } else {
+ console.assert(false, `unknown set-center target "${String(e)}"`);
+ return;
+ }
+ if (!rect) return;
+ const layout = fitView(el, [rect], padding, zooms);
+ applyZoom(layout.zoom);
+ applyPosition({ x: layout.rect.x, y: layout.rect.y });
+ });
+ return () => {
+ off();
+ };
+ }, [events]);
+};
diff --git a/frontend/src/react/components/SchemaDiagram/Canvas/index.ts b/frontend/src/react/components/SchemaDiagram/Canvas/index.ts
new file mode 100644
index 0000000000..8d4b9b0edf
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Canvas/index.ts
@@ -0,0 +1,4 @@
+export { Canvas } from "./Canvas";
+export { ZoomButton } from "./ZoomButton";
+export * from "./composables";
+export * from "./libs/fitView";
diff --git a/frontend/src/react/components/SchemaDiagram/Canvas/libs/fitView.test.ts b/frontend/src/react/components/SchemaDiagram/Canvas/libs/fitView.test.ts
new file mode 100644
index 0000000000..9a3c0769b4
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Canvas/libs/fitView.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from "vitest";
+import { fitView } from "./fitView";
+
+const fakeCanvas = (width: number, height: number): Element => {
+ return {
+ getBoundingClientRect: () => ({
+ width,
+ height,
+ top: 0,
+ left: 0,
+ right: width,
+ bottom: height,
+ x: 0,
+ y: 0,
+ toJSON() {
+ return { width, height };
+ },
+ }),
+ } as Element;
+};
+
+describe("fitView", () => {
+ it("fits content into canvas with no padding at zoom 1 when content equals view", () => {
+ const canvas = fakeCanvas(1000, 600);
+ const layout = fitView(
+ canvas,
+ [{ x: 0, y: 0, width: 1000, height: 600 }],
+ [0, 0, 0, 0],
+ [0, 2]
+ );
+ expect(layout.zoom).toBeCloseTo(1, 5);
+ expect(layout.rect.x).toBeCloseTo(0, 5);
+ expect(layout.rect.y).toBeCloseTo(0, 5);
+ });
+
+ it("scales down content larger than the viewport", () => {
+ const canvas = fakeCanvas(1000, 600);
+ const layout = fitView(
+ canvas,
+ [{ x: 0, y: 0, width: 2000, height: 1200 }],
+ [0, 0, 0, 0],
+ [0, 2]
+ );
+ // 1000/2000 = 0.5 (width is the limiting dimension since both are 2x).
+ expect(layout.zoom).toBeCloseTo(0.5, 5);
+ });
+
+ it("respects symmetrical padding by shrinking the view box", () => {
+ const canvas = fakeCanvas(1000, 600);
+ const padded = fitView(
+ canvas,
+ [{ x: 0, y: 0, width: 1000, height: 600 }],
+ [50, 50, 50, 50],
+ [0, 2]
+ );
+ // The view shrinks from 1000x600 to 900x500. Limiting dimension is height
+ // (500/600 ≈ 0.833 < 900/1000 = 0.9), so zoom is 500/600.
+ expect(padded.zoom).toBeCloseTo(500 / 600, 5);
+ });
+
+ it("zero-content collapses without crashing (epsilon clamp)", () => {
+ const canvas = fakeCanvas(1000, 600);
+ const layout = fitView(canvas, [], [0, 0, 0, 0], [0.1, 2]);
+ // With no geometries, calcBBox returns a zero rect. fitView clamps to
+ // EPSILON to avoid divide-by-zero, so the result is well-defined.
+ expect(Number.isFinite(layout.zoom)).toBe(true);
+ expect(Number.isFinite(layout.rect.x)).toBe(true);
+ expect(Number.isFinite(layout.rect.y)).toBe(true);
+ });
+});
diff --git a/frontend/src/components/SchemaDiagram/Canvas/libs/fitView.ts b/frontend/src/react/components/SchemaDiagram/Canvas/libs/fitView.ts
similarity index 95%
rename from frontend/src/components/SchemaDiagram/Canvas/libs/fitView.ts
rename to frontend/src/react/components/SchemaDiagram/Canvas/libs/fitView.ts
index f15af321a3..9dff6a842a 100644
--- a/frontend/src/components/SchemaDiagram/Canvas/libs/fitView.ts
+++ b/frontend/src/react/components/SchemaDiagram/Canvas/libs/fitView.ts
@@ -1,5 +1,5 @@
-import { calcBBox, fitBBox } from "../../common";
import { ZOOM_RANGE } from "../../common/const";
+import { calcBBox, fitBBox } from "../../common/geometry";
import type { Geometry, Rect } from "../../types";
export const fitView = (
diff --git a/frontend/src/react/components/SchemaDiagram/ER/ForeignKeyLine.test.tsx b/frontend/src/react/components/SchemaDiagram/ER/ForeignKeyLine.test.tsx
new file mode 100644
index 0000000000..22d02d76a2
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/ER/ForeignKeyLine.test.tsx
@@ -0,0 +1,68 @@
+import { describe, expect, it } from "vitest";
+import { anchor, generateLine, grow, pickPorts } from "./ForeignKeyLine";
+
+describe("ForeignKeyLine math", () => {
+ describe("pickPorts", () => {
+ it("BEFORE → src right, dest left", () => {
+ expect(pickPorts("BEFORE", [0, 1], [2, 3])).toEqual(["RIGHT", "LEFT"]);
+ });
+ it("AFTER → src left, dest right", () => {
+ expect(pickPorts("AFTER", [5, 6], [0, 1])).toEqual(["LEFT", "RIGHT"]);
+ });
+ it("CONTAINS → both LEFT when dest is to the left of src center", () => {
+ expect(pickPorts("CONTAINS", [0, 100], [10, 30])).toEqual([
+ "LEFT",
+ "LEFT",
+ ]);
+ });
+ it("CONTAINS → both RIGHT when dest is to the right of src center", () => {
+ expect(pickPorts("CONTAINS", [0, 100], [60, 80])).toEqual([
+ "RIGHT",
+ "RIGHT",
+ ]);
+ });
+ it("CONTAINED → both LEFT when src is to the left of dest center", () => {
+ expect(pickPorts("CONTAINED", [10, 30], [0, 100])).toEqual([
+ "LEFT",
+ "LEFT",
+ ]);
+ });
+ });
+
+ describe("anchor / grow", () => {
+ it("anchors on the right edge mid-height for RIGHT", () => {
+ expect(anchor({ x: 10, y: 20, width: 30, height: 40 }, "RIGHT")).toEqual({
+ x: 40,
+ y: 40,
+ });
+ });
+ it("anchors on the left edge mid-height for LEFT", () => {
+ expect(anchor({ x: 10, y: 20, width: 30, height: 40 }, "LEFT")).toEqual({
+ x: 10,
+ y: 40,
+ });
+ });
+ it("grows away from the anchor in the named direction", () => {
+ expect(grow({ x: 10, y: 5 }, "RIGHT", 16)).toEqual({ x: 26, y: 5 });
+ expect(grow({ x: 10, y: 5 }, "LEFT", 16)).toEqual({ x: -6, y: 5 });
+ });
+ });
+
+ describe("generateLine", () => {
+ it("creates a 4-point S-curve between two rects", () => {
+ const a = { x: 0, y: 0, width: 100, height: 50 };
+ const b = { x: 200, y: 100, width: 100, height: 50 };
+ // a is BEFORE b → src RIGHT, dest LEFT
+ const line = generateLine(a, "RIGHT", b, "LEFT");
+ expect(line).toHaveLength(4);
+ // anchor right of a = (100, 25)
+ expect(line[0]).toEqual({ x: 100, y: 25 });
+ // grow right by 16 = (116, 25)
+ expect(line[1]).toEqual({ x: 116, y: 25 });
+ // grow left from b's anchor (200, 125) by 16 = (184, 125)
+ expect(line[2]).toEqual({ x: 184, y: 125 });
+ // anchor left of b = (200, 125)
+ expect(line[3]).toEqual({ x: 200, y: 125 });
+ });
+ });
+});
diff --git a/frontend/src/react/components/SchemaDiagram/ER/ForeignKeyLine.tsx b/frontend/src/react/components/SchemaDiagram/ER/ForeignKeyLine.tsx
new file mode 100644
index 0000000000..57babce027
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/ER/ForeignKeyLine.tsx
@@ -0,0 +1,174 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { cn } from "@/react/lib/utils";
+import type { TableMetadata } from "@/types/proto-es/v1/database_service_pb";
+import { useGeometry, useSchemaDiagramContext } from "../common/context";
+import { type SegmentOverlap1D, segmentOverlap1D } from "../common/geometry";
+import type { ForeignKey, Path, Point, Rect } from "../types";
+import { SVGLine } from "./libs/SVGLine";
+
+type Direction = "LEFT" | "RIGHT";
+type Segment1D = [number, number];
+
+interface ForeignKeyLineProps {
+ fk: ForeignKey;
+}
+
+const ZERO_RECT: Rect = { x: 0, y: 0, width: 0, height: 0 };
+
+/**
+ * React port of `ER/ForeignKeyLine.vue`. Reads each endpoint's column
+ * rect by querying the live DOM (via `data-bb-node-id` /
+ * `data-bb-column-name`), picks anchor sides, builds the SVG path, and
+ * registers it as a geometry so fit-view's bbox includes the FK line.
+ *
+ * Recomputes when the context emits `render` (typically after layout
+ * resolves or when a table is dragged).
+ */
+export function ForeignKeyLine({ fk }: ForeignKeyLineProps) {
+ const ctx = useSchemaDiagramContext();
+ const { zoom, focusedTables, idOfTable, rectOfTable, events } = ctx;
+
+ // Recompute trigger — bumped when the diagram emits "render".
+ const [, setTick] = useState(0);
+
+ useEffect(() => {
+ const off = events.on("render", () => setTick((n) => n + 1));
+ return () => {
+ off();
+ };
+ }, [events]);
+
+ const findRect = useCallback(
+ (table: TableMetadata, columnName: string): Rect => {
+ const id = idOfTable(table);
+ const tableRect = rectOfTable(table);
+ const tableEl = document.querySelector(`[data-bb-node-id="${id}"]`);
+ if (!tableEl) return ZERO_RECT;
+ const colEl = tableEl.querySelector(
+ `[data-bb-column-name="${columnName}"]`
+ );
+ if (colEl) {
+ const tableView = tableEl.getBoundingClientRect();
+ const columnView = colEl.getBoundingClientRect();
+ return {
+ x: tableRect.x + (columnView.left - tableView.left) / zoom,
+ y: tableRect.y + (columnView.top - tableView.top) / zoom,
+ width: columnView.width / zoom,
+ height: columnView.height / zoom,
+ };
+ }
+ return tableRect;
+ },
+ [idOfTable, rectOfTable, zoom]
+ );
+
+ // Read tableRects so a layout / drag triggers a re-render.
+ // (rectOfTable is regenerated whenever the underlying tableRects state
+ // changes, so listing it as a dep covers the layout-resolved case.)
+ const fromRect = useMemo(
+ () => findRect(fk.from.table, fk.from.column),
+ [fk.from.table, fk.from.column, findRect]
+ );
+ const toRect = useMemo(
+ () => findRect(fk.to.table, fk.to.column),
+ [fk.to.table, fk.to.column, findRect]
+ );
+
+ const path = useMemo<Path>(() => {
+ if (fromRect.width === 0 || toRect.width === 0) return [];
+ const fromPorts: Segment1D = [fromRect.x, fromRect.x + fromRect.width];
+ const toPorts: Segment1D = [toRect.x, toRect.x + toRect.width];
+ const rel = segmentOverlap1D(
+ fromPorts[0],
+ fromPorts[1],
+ toPorts[0],
+ toPorts[1]
+ );
+ const [fromPort, toPort] = pickPorts(rel, fromPorts, toPorts);
+ return generateLine(fromRect, fromPort, toRect, toPort);
+ }, [fromRect, toRect]);
+
+ const startManyArrow = useMemo<Path>(() => {
+ if (path.length < 2) return [];
+ const p = path[0];
+ const q = path[1];
+ const dir = Math.sign(q.x - p.x);
+ const h = 12;
+ const v = 6;
+ return [
+ { x: p.x, y: p.y + v },
+ { x: p.x + h * dir, y: p.y },
+ { x: p.x, y: p.y - v },
+ ];
+ }, [path]);
+
+ const lineClasses = useMemo(() => {
+ if (focusedTables.size === 0) return "";
+ if (focusedTables.has(fk.from.table) || focusedTables.has(fk.to.table)) {
+ return "opacity-100";
+ }
+ return "opacity-20";
+ }, [focusedTables, fk]);
+
+ useGeometry(path);
+
+ return (
+ <SVGLine
+ className={cn("transition-opacity", lineClasses)}
+ path={path}
+ decorators={[startManyArrow]}
+ data-bb-edge-from={`${fk.from.table.name}.${fk.from.column}`}
+ data-bb-edge-to={`${fk.to.table.name}.${fk.to.column}`}
+ data-bb-fk-name={fk.metadata.name}
+ data-bb-fk-on-update={fk.metadata.onUpdate}
+ data-bb-fk-on-delete={fk.metadata.onDelete}
+ data-bb-fk-match-type={fk.metadata.matchType}
+ />
+ );
+}
+
+// ===== Pure helpers (extracted for testability — see ForeignKeyLine.test) =====
+
+export const pickPorts = (
+ rel: SegmentOverlap1D,
+ a: Segment1D,
+ b: Segment1D
+): [Direction, Direction] => {
+ switch (rel) {
+ case "BEFORE":
+ return ["RIGHT", "LEFT"];
+ case "AFTER":
+ return ["LEFT", "RIGHT"];
+ case "CONTAINS":
+ case "OVERLAPS":
+ return b[0] <= (a[0] + a[1]) / 2 ? ["LEFT", "LEFT"] : ["RIGHT", "RIGHT"];
+ case "OVERLAPPED":
+ case "CONTAINED":
+ return a[0] <= (b[0] + b[1]) / 2 ? ["LEFT", "LEFT"] : ["RIGHT", "RIGHT"];
+ }
+};
+
+export const grow = (pos: Point, dir: Direction, length: number): Point => {
+ const x = dir === "LEFT" ? pos.x - length : pos.x + length;
+ return { x, y: pos.y };
+};
+
+export const anchor = (rect: Rect, edge: Direction): Point => {
+ const x = edge === "LEFT" ? rect.x : rect.x + rect.width;
+ const y = rect.y + rect.height / 2;
+ return { x, y };
+};
+
+export const generateLine = (
+ src: Rect,
+ se: Direction,
+ dest: Rect,
+ de: Direction
+): Path => {
+ const GROWTH_LEN = 16;
+ const sp = anchor(src, se);
+ const dp = anchor(dest, de);
+ const sc = grow(sp, se, GROWTH_LEN);
+ const dc = grow(dp, de, GROWTH_LEN);
+ return [sp, sc, dc, dp];
+};
diff --git a/frontend/src/react/components/SchemaDiagram/ER/TableNode.tsx b/frontend/src/react/components/SchemaDiagram/ER/TableNode.tsx
new file mode 100644
index 0000000000..60a70de679
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/ER/TableNode.tsx
@@ -0,0 +1,225 @@
+import { Diamond, Key, Pencil } from "lucide-react";
+import { useCallback, useMemo } from "react";
+import { hashCode } from "@/bbkit/BBUtil";
+import { cn } from "@/react/lib/utils";
+import type {
+ ColumnMetadata,
+ SchemaMetadata,
+ TableMetadata,
+} from "@/types/proto-es/v1/database_service_pb";
+import { useGeometry, useSchemaDiagramContext } from "../common/context";
+import { FocusButton } from "../common/FocusButton";
+import { isIndex, isPrimaryKey } from "../common/schema";
+import { isFocusedForeignTable } from "./libs/isFocusedFKTable";
+
+interface TableNodeProps {
+ schema: SchemaMetadata;
+ table: TableMetadata;
+}
+
+const COLOR_LIST = [
+ "#64748B",
+ "#EF4444",
+ "#F97316",
+ "#EAB308",
+ "#84CC16",
+ "#22C55E",
+ "#10B981",
+ "#06B6D4",
+ "#0EA5E9",
+ "#3B82F6",
+ "#6366F1",
+ "#8B5CF6",
+ "#A855F7",
+ "#D946EF",
+ "#EC4899",
+ "#F43F5E",
+];
+
+/**
+ * React port of `ER/TableNode.vue`. One table card with title bar, FK
+ * focus button, optional edit pencil, and a column list with PK / index
+ * glyphs and edit-on-click affordances when `editable` is on.
+ */
+export function TableNode({ schema, table }: TableNodeProps) {
+ const ctx = useSchemaDiagramContext();
+ const {
+ dummy,
+ editable,
+ focusedTables,
+ foreignKeys,
+ idOfTable,
+ rectOfTable,
+ schemaStatus,
+ tableStatus,
+ columnStatus,
+ panning,
+ events,
+ } = ctx;
+
+ const tableColor = useMemo(() => {
+ const index = (hashCode(table.name) & 0xfffffff) % COLOR_LIST.length;
+ return COLOR_LIST[index];
+ }, [table.name]);
+
+ const isTableDropped = useMemo(
+ () =>
+ schemaStatus(schema) === "dropped" || tableStatus(table) === "dropped",
+ [schema, table, schemaStatus, tableStatus]
+ );
+
+ const isTableCreated = useMemo(
+ () =>
+ schemaStatus(schema) === "created" || tableStatus(table) === "created",
+ [schema, table, schemaStatus, tableStatus]
+ );
+
+ const isTableChanged = useMemo(
+ () => tableStatus(table) === "changed",
+ [table, tableStatus]
+ );
+
+ const tableStatusText = isTableCreated
+ ? "Created"
+ : isTableDropped
+ ? "Dropped"
+ : isTableChanged
+ ? "Changed"
+ : "";
+
+ const tableClasses = useMemo(() => {
+ if (focusedTables.size === 0) return "";
+ if (focusedTables.has(table)) return "opacity-100";
+ if (isFocusedForeignTable(table, focusedTables, foreignKeys)) {
+ return "opacity-100";
+ }
+ return "opacity-20 hover:opacity-100";
+ }, [table, focusedTables, foreignKeys]);
+
+ const columnClasses = useCallback(
+ (column: ColumnMetadata) => {
+ const classes: string[] = [];
+ if (editable) classes.push("cursor-pointer");
+ const status = columnStatus(column);
+ if (status === "changed") classes.push("text-yellow-700 bg-yellow-50");
+ else if (status === "created") classes.push("text-green-700 bg-green-50");
+ else if (status === "dropped")
+ classes.push("text-red-700 bg-red-50 line-through");
+ return classes.join(" ");
+ },
+ [editable, columnStatus]
+ );
+
+ const handleClickColumn = useCallback(
+ (column: ColumnMetadata, target: "name" | "type") => {
+ if (!editable) return;
+ if (panning) return;
+ void events.emit("edit-column", { schema, table, column, target });
+ },
+ [editable, panning, events, schema, table]
+ );
+
+ const id = idOfTable(table);
+ const rect = rectOfTable(table);
+
+ // Register the rect so the canvas's fit-view bbox includes this table.
+ useGeometry(rect);
+
+ return (
+ <div
+ className={cn(
+ "absolute overflow-hidden rounded-md shadow-lg border-b border-control-border bg-background w-[16rem] divide-y divide-control-border z-10 transition-opacity",
+ tableClasses
+ )}
+ data-bb-node-type="table"
+ data-bb-node-id={dummy ? `dummy-${id}` : id}
+ data-bb-status={tableStatus(table)}
+ style={{ left: `${rect.x}px`, top: `${rect.y}px` }}
+ >
+ <h3
+ className={cn(
+ "group font-medium leading-6 text-white px-2 py-2 rounded-t-md gap-x-1 relative text-center whitespace-pre-wrap break-words"
+ )}
+ style={{ backgroundColor: tableColor }}
+ >
+ <FocusButton
+ table={table}
+ setCenter={false}
+ className="invisible group-hover:visible !absolute top-[50%] -mt-[9px] left-1 text-control group-hover:!bg-white/70 group-hover:!text-control"
+ focusedClass="!text-white"
+ />
+
+ {schema.name !== "" && (
+ <>
+ <span className={cn(isTableDropped && "line-through")}>
+ {schema.name}
+ </span>
+ <span>.</span>
+ </>
+ )}
+ <span className={cn(isTableDropped && "line-through")}>
+ {table.name}
+ </span>
+ {tableStatusText && (
+ <span className="ml-1 text-sm">({tableStatusText})</span>
+ )}
+
+ {editable && (
+ <button
+ type="button"
+ className="invisible group-hover:visible absolute top-[50%] -mt-[9px] right-1 text-control bg-white/70 hover:bg-control-bg p-0.5 rounded-sm"
+ onClick={() => events.emit("edit-table", { schema, table })}
+ >
+ <Pencil className="size-4" />
+ </button>
+ )}
+ </h3>
+
+ <table className="w-full text-sm table-fixed">
+ <tbody>
+ {table.columns.map((column, i) => (
+ <tr
+ key={i}
+ data-bb-column-name={dummy ? `dummy-${column.name}` : column.name}
+ data-bb-status={columnStatus(column)}
+ className={columnClasses(column)}
+ >
+ <td className="w-5 py-1.5 relative">
+ {isPrimaryKey(table, column) ? (
+ <Key className="size-3 mx-auto text-warning" />
+ ) : isIndex(table, column) ? (
+ <Diamond className="size-3 mx-auto text-control-light" />
+ ) : null}
+ </td>
+ <td className="w-auto text-xs py-1.5">
+ <div
+ className={cn(
+ "whitespace-pre-wrap break-words pr-1.5",
+ editable && "hover:!text-accent"
+ )}
+ onClick={() => handleClickColumn(column, "name")}
+ >
+ {column.name}
+ {columnStatus(column) !== "normal" && (
+ <span className="inline-block rounded-full ml-0.5 h-1.5 w-1.5 bg-accent opacity-75 -translate-y-px" />
+ )}
+ </div>
+ </td>
+ <td className="w-24 text-xs text-control-light py-1.5 text-right">
+ <div
+ className={cn(
+ "truncate pr-1.5",
+ editable && "hover:!text-accent"
+ )}
+ onClick={() => handleClickColumn(column, "type")}
+ >
+ {column.type}
+ </div>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/SchemaDiagram/ER/index.ts b/frontend/src/react/components/SchemaDiagram/ER/index.ts
new file mode 100644
index 0000000000..4df8f79096
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/ER/index.ts
@@ -0,0 +1,4 @@
+export { ForeignKeyLine } from "./ForeignKeyLine";
+export { TableNode } from "./TableNode";
+export { isFocusedForeignTable } from "./libs/isFocusedFKTable";
+export { SVGLine } from "./libs/SVGLine";
diff --git a/frontend/src/react/components/SchemaDiagram/ER/libs/SVGLine.tsx b/frontend/src/react/components/SchemaDiagram/ER/libs/SVGLine.tsx
new file mode 100644
index 0000000000..e11a101878
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/ER/libs/SVGLine.tsx
@@ -0,0 +1,133 @@
+import { curveMonotoneX, line as d3Line } from "d3-shape";
+import { type ComponentProps, useMemo, useState } from "react";
+import { cn } from "@/react/lib/utils";
+import { calcBBox } from "../../common/geometry";
+import type { Path, Point, Rect } from "../../types";
+
+const GLOW_WIDTH = 12;
+const PADDING = GLOW_WIDTH / 2;
+const COLORS = {
+ GLOW: {
+ NORMAL: "transparent",
+ HOVER: "rgba(55,48,163,0.1)",
+ },
+ LINE: {
+ NORMAL: "#1f2937",
+ HOVER: "#4f46e5",
+ },
+};
+
+interface SVGLineProps {
+ path: Path;
+ decorators?: Path[];
+ className?: string;
+}
+
+/**
+ * React port of `frontend/src/components/SchemaDiagram/ER/libs/SVGLine.vue`.
+ *
+ * Renders a polyline + optional decorator paths inside an absolutely
+ * positioned SVG. Hover (across both the visible line and a wider
+ * invisible "glow" track) flips the stroke color and width.
+ */
+export function SVGLine({
+ path,
+ decorators = [],
+ className,
+ ...rest
+}: SVGLineProps & Omit<ComponentProps<"svg">, "viewBox" | "style" | "path">) {
+ const [trackHover, setTrackHover] = useState(false);
+ const [lineHover, setLineHover] = useState(false);
+ const hover = trackHover || lineHover;
+
+ const bbox = useMemo(() => {
+ const points: Point[] = [...path];
+ for (const d of decorators) {
+ for (const p of d) {
+ points.push(p);
+ }
+ }
+ return calcBBox(points);
+ }, [path, decorators]);
+
+ const viewBox: Rect = useMemo(
+ () => ({
+ x: -PADDING,
+ y: -PADDING,
+ width: Math.max(bbox.width, 0) + PADDING * 2,
+ height: Math.max(bbox.height, 0) + PADDING * 2,
+ }),
+ [bbox]
+ );
+
+ const normalize = (x: number, y: number): [number, number] => [
+ x - bbox.x,
+ y - bbox.y,
+ ];
+
+ const svgLine = useMemo(() => {
+ const points: [number, number][] = path.map((p) => normalize(p.x, p.y));
+ return d3Line<[number, number]>().curve(curveMonotoneX)(points) ?? "";
+ }, [path, bbox]);
+
+ const svgDecorators = useMemo(() => {
+ return decorators.map((d) => {
+ const points: [number, number][] = d.map((p) => normalize(p.x, p.y));
+ return d3Line<[number, number]>()(points) ?? "";
+ });
+ }, [decorators, bbox]);
+
+ return (
+ <svg
+ version="1.1"
+ xmlns="http://www.w3.org/2000/svg"
+ // The hover state lifts the line above its peers so the highlight
+ // isn't occluded by an adjacent FK line. Component-internal stacking
+ // within the same canvas — `z-10` is well below the layering
+ // scanner's high-z threshold (40) and avoids the inline-zIndex ban.
+ className={cn(
+ "absolute cursor-pointer",
+ hover ? "z-10" : "z-0",
+ className
+ )}
+ pointerEvents="none"
+ viewBox={`${viewBox.x} ${viewBox.y} ${viewBox.width} ${viewBox.height}`}
+ style={{
+ left: `${bbox.x + viewBox.x}px`,
+ top: `${bbox.y + viewBox.y}px`,
+ width: `${viewBox.width}px`,
+ height: `${viewBox.height}px`,
+ }}
+ {...rest}
+ >
+ <path
+ d={svgLine}
+ pointerEvents="visibleStroke"
+ fill="none"
+ stroke={hover ? COLORS.GLOW.HOVER : COLORS.GLOW.NORMAL}
+ strokeWidth={GLOW_WIDTH}
+ onMouseEnter={() => setTrackHover(true)}
+ onMouseLeave={() => setTrackHover(false)}
+ />
+ {svgDecorators.map((d, i) => (
+ <path
+ key={i}
+ d={d}
+ fill="none"
+ stroke={hover ? COLORS.LINE.HOVER : COLORS.LINE.NORMAL}
+ strokeWidth={1}
+ pointerEvents="none"
+ />
+ ))}
+ <path
+ d={svgLine}
+ pointerEvents="visibleStroke"
+ fill="none"
+ stroke={hover ? COLORS.LINE.HOVER : COLORS.LINE.NORMAL}
+ strokeWidth={hover ? 2 : 1.5}
+ onMouseEnter={() => setLineHover(true)}
+ onMouseLeave={() => setLineHover(false)}
+ />
+ </svg>
+ );
+}
diff --git a/frontend/src/components/SchemaDiagram/ER/libs/autoLayout/engines/elk.ts b/frontend/src/react/components/SchemaDiagram/ER/libs/autoLayout/engines/elk.ts
similarity index 92%
rename from frontend/src/components/SchemaDiagram/ER/libs/autoLayout/engines/elk.ts
rename to frontend/src/react/components/SchemaDiagram/ER/libs/autoLayout/engines/elk.ts
index 7d9f4c9c2c..46c69dc4d0 100644
--- a/frontend/src/components/SchemaDiagram/ER/libs/autoLayout/engines/elk.ts
+++ b/frontend/src/react/components/SchemaDiagram/ER/libs/autoLayout/engines/elk.ts
@@ -1,7 +1,7 @@
import type { LayoutOptions } from "elkjs/lib/elk.bundled";
import ELK, { type ElkNode } from "elkjs/lib/elk.bundled";
import { groupBy } from "lodash-es";
-import type { Path, Rect } from "@/components/SchemaDiagram/types";
+import type { Path, Rect } from "../../../../types";
import type { GraphEdgeItem, GraphNodeItem, Layout } from "../types";
export const layoutELK = async (
@@ -38,9 +38,7 @@ export const layoutELK = async (
})),
};
- const result = await elk.layout(graph, {
- // logging: true,
- });
+ const result = await elk.layout(graph, {});
const rects = new Map<string, Rect>();
result.children?.forEach((cluster) => {
const { x = 0, y = 0 } = cluster;
diff --git a/frontend/src/components/SchemaDiagram/ER/libs/autoLayout/index.ts b/frontend/src/react/components/SchemaDiagram/ER/libs/autoLayout/index.ts
similarity index 100%
rename from frontend/src/components/SchemaDiagram/ER/libs/autoLayout/index.ts
rename to frontend/src/react/components/SchemaDiagram/ER/libs/autoLayout/index.ts
diff --git a/frontend/src/components/SchemaDiagram/ER/libs/autoLayout/types.ts b/frontend/src/react/components/SchemaDiagram/ER/libs/autoLayout/types.ts
similarity index 81%
rename from frontend/src/components/SchemaDiagram/ER/libs/autoLayout/types.ts
rename to frontend/src/react/components/SchemaDiagram/ER/libs/autoLayout/types.ts
index 8a378acfdc..2313be9a20 100644
--- a/frontend/src/components/SchemaDiagram/ER/libs/autoLayout/types.ts
+++ b/frontend/src/react/components/SchemaDiagram/ER/libs/autoLayout/types.ts
@@ -1,4 +1,4 @@
-import type { Path, Point, Rect, Size } from "@/components/SchemaDiagram/types";
+import type { Path, Point, Rect, Size } from "../../../types";
export type GraphChildNodeItem = { id: string; size: Size; pos: Point };
diff --git a/frontend/src/react/components/SchemaDiagram/ER/libs/autoLayout/useAutoLayout.test.tsx b/frontend/src/react/components/SchemaDiagram/ER/libs/autoLayout/useAutoLayout.test.tsx
new file mode 100644
index 0000000000..3ec378ed18
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/ER/libs/autoLayout/useAutoLayout.test.tsx
@@ -0,0 +1,222 @@
+import { create } from "@bufbuild/protobuf";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ ColumnMetadataSchema,
+ SchemaMetadataSchema,
+ TableMetadataSchema,
+} from "@/types/proto-es/v1/database_service_pb";
+import type { Layout } from "./index";
+import { useAutoLayout } from "./useAutoLayout";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const autoLayoutMock = vi.fn<(...args: unknown[]) => Promise<Layout>>();
+
+vi.mock("./index", async (importOriginal) => {
+ const orig = await importOriginal<typeof import("./index")>();
+ return {
+ ...orig,
+ autoLayout: (...args: unknown[]) => autoLayoutMock(...args),
+ };
+});
+
+const renderHook = <T,>(hookFn: () => T) => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ let value!: T;
+ function Host() {
+ value = hookFn();
+ return null;
+ }
+ act(() => {
+ root.render(<Host />);
+ });
+ return {
+ get current() {
+ return value;
+ },
+ unmount: () =>
+ act(() => {
+ root.unmount();
+ }),
+ };
+};
+
+const makeTable = (name: string) =>
+ create(TableMetadataSchema, {
+ name,
+ columns: [create(ColumnMetadataSchema, { name: "id" })],
+ });
+
+const makeSchema = (name: string, tables: ReturnType<typeof makeTable>[]) =>
+ create(SchemaMetadataSchema, { name, tables });
+
+beforeEach(() => {
+ autoLayoutMock.mockReset();
+});
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("useAutoLayout", () => {
+ it("threads sizes through ELK and returns the rect map", async () => {
+ const t1 = makeTable("users");
+ const t2 = makeTable("orders");
+ const schema = makeSchema("public", [t1, t2]);
+
+ const idOfTable = (t: typeof t1) => `id-${t.name}`;
+ const sizeOfTable = (id: string) =>
+ id === "id-users"
+ ? { width: 200, height: 80 }
+ : { width: 240, height: 100 };
+
+ autoLayoutMock.mockResolvedValueOnce({
+ rects: new Map([
+ ["id-users", { x: 0, y: 0, width: 200, height: 80 }],
+ ["id-orders", { x: 300, y: 0, width: 240, height: 100 }],
+ ]),
+ paths: new Map(),
+ });
+
+ const hook = renderHook(() =>
+ useAutoLayout({
+ selectedSchemas: [schema],
+ edges: [
+ {
+ fromSchema: "public",
+ fromTable: t2,
+ fromColumn: "user_id",
+ toSchema: "public",
+ toTable: t1,
+ toColumn: "id",
+ },
+ ],
+ idOfTable,
+ sizeOfTable,
+ })
+ );
+
+ let rects: Map<string, { x: number; y: number }> | null = null;
+ await act(async () => {
+ const out = await hook.current();
+ rects = out as Map<string, { x: number; y: number }>;
+ });
+
+ expect(rects).not.toBeNull();
+ expect(rects!.get("id-users")).toEqual({
+ x: 0,
+ y: 0,
+ width: 200,
+ height: 80,
+ });
+
+ const callArgs = autoLayoutMock.mock.calls[0];
+ const nodeList = callArgs[0] as Array<{
+ id: string;
+ size: { width: number; height: number };
+ group: string;
+ }>;
+ const edgeList = callArgs[1] as Array<{
+ id: string;
+ from: string;
+ to: string;
+ }>;
+ expect(nodeList).toHaveLength(2);
+ expect(nodeList.map((n) => n.id).sort()).toEqual(["id-orders", "id-users"]);
+ expect(nodeList[0].group).toBe("schema-public");
+ expect(edgeList).toHaveLength(1);
+ expect(edgeList[0].from).toBe("id-orders");
+ expect(edgeList[0].to).toBe("id-users");
+
+ hook.unmount();
+ });
+
+ it("skips tables whose DOM size is unknown", async () => {
+ const t1 = makeTable("users");
+ const t2 = makeTable("orders");
+ const schema = makeSchema("public", [t1, t2]);
+
+ autoLayoutMock.mockResolvedValueOnce({
+ rects: new Map(),
+ paths: new Map(),
+ });
+
+ const hook = renderHook(() =>
+ useAutoLayout({
+ selectedSchemas: [schema],
+ edges: [],
+ idOfTable: (t) => `id-${t.name}`,
+ sizeOfTable: (id) =>
+ id === "id-users" ? { width: 200, height: 80 } : null,
+ })
+ );
+
+ await act(async () => {
+ await hook.current();
+ });
+
+ const nodeList = autoLayoutMock.mock.calls[0][0] as Array<{
+ id: string;
+ }>;
+ expect(nodeList).toHaveLength(1);
+ expect(nodeList[0].id).toBe("id-users");
+
+ hook.unmount();
+ });
+
+ it("discards stale results when a newer call supersedes", async () => {
+ const t1 = makeTable("users");
+ const schema = makeSchema("public", [t1]);
+
+ let resolveA: (layout: Layout) => void = () => {};
+ autoLayoutMock.mockImplementationOnce(
+ () =>
+ new Promise<Layout>((resolve) => {
+ resolveA = resolve;
+ })
+ );
+ autoLayoutMock.mockResolvedValueOnce({
+ rects: new Map([["id-users", { x: 999, y: 0, width: 1, height: 1 }]]),
+ paths: new Map(),
+ });
+
+ const hook = renderHook(() =>
+ useAutoLayout({
+ selectedSchemas: [schema],
+ edges: [],
+ idOfTable: (t) => `id-${t.name}`,
+ sizeOfTable: () => ({ width: 100, height: 50 }),
+ })
+ );
+
+ let firstResult: Map<string, unknown> | null = null;
+ let secondResult: Map<string, unknown> | null = null;
+
+ await act(async () => {
+ const a = hook.current();
+ const b = hook.current();
+ // Resolve A *after* B has been kicked off, so A is now stale.
+ resolveA({
+ rects: new Map([["id-users", { x: 0, y: 0, width: 1, height: 1 }]]),
+ paths: new Map(),
+ });
+ firstResult = (await a) as Map<string, unknown> | null;
+ secondResult = (await b) as Map<string, unknown> | null;
+ });
+
+ expect(firstResult).toBeNull();
+ expect(secondResult).not.toBeNull();
+ expect(secondResult!.get("id-users")).toEqual({
+ x: 999,
+ y: 0,
+ width: 1,
+ height: 1,
+ });
+
+ hook.unmount();
+ });
+});
diff --git a/frontend/src/react/components/SchemaDiagram/ER/libs/autoLayout/useAutoLayout.ts b/frontend/src/react/components/SchemaDiagram/ER/libs/autoLayout/useAutoLayout.ts
new file mode 100644
index 0000000000..5e8f637e30
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/ER/libs/autoLayout/useAutoLayout.ts
@@ -0,0 +1,84 @@
+import { useCallback, useRef } from "react";
+import type {
+ SchemaMetadata,
+ TableMetadata,
+} from "@/types/proto-es/v1/database_service_pb";
+import type { Size } from "../../../types";
+import { autoLayout } from "./index";
+import type { GraphEdgeItem, GraphNodeItem } from "./types";
+
+export type ForeignKeyEdge = {
+ fromSchema: string;
+ fromTable: TableMetadata;
+ fromColumn: string;
+ toSchema: string;
+ toTable: TableMetadata;
+ toColumn: string;
+};
+
+interface UseAutoLayoutInput {
+ selectedSchemas: SchemaMetadata[];
+ edges: ForeignKeyEdge[];
+ /** Resolves a TableMetadata to its assigned id (from the SchemaDiagram context). */
+ idOfTable: (table: TableMetadata) => string;
+ /** Reads the rendered DOM size of a table card by id. */
+ sizeOfTable: (id: string) => Size | null;
+}
+
+/**
+ * Drive ELK auto-layout for the diagram's currently-selected schemas.
+ *
+ * Returns a `runLayout()` callback that the SchemaDiagram root invokes
+ * (typically wired to the `events.on("layout", ...)` channel). The
+ * callback gathers each table's measured DOM size, builds the node + edge
+ * graph, awaits ELK, and resolves with `Map<tableId, Rect>` so the caller
+ * can `mergeTableRects(...)` the result back into the context.
+ *
+ * The most-recent `latest()` token guards against stale ELK results when
+ * the user rapidly toggles schemas: only the in-flight call from the
+ * latest invocation resolves with data; earlier ones resolve `null`.
+ */
+export function useAutoLayout({
+ selectedSchemas,
+ edges,
+ idOfTable,
+ sizeOfTable,
+}: UseAutoLayoutInput) {
+ const tokenRef = useRef(0);
+
+ return useCallback(async () => {
+ const myToken = ++tokenRef.current;
+
+ const nodeList: GraphNodeItem[] = [];
+ for (const schema of selectedSchemas) {
+ for (const table of schema.tables) {
+ const id = idOfTable(table);
+ const size = sizeOfTable(id);
+ if (!size) continue;
+ nodeList.push({
+ group: `schema-${schema.name}`,
+ id,
+ size,
+ children: [],
+ });
+ }
+ }
+
+ const edgeList: GraphEdgeItem[] = edges.map((fk) => {
+ const fromTableId = idOfTable(fk.fromTable);
+ const toTableId = idOfTable(fk.toTable);
+ return {
+ id: `${fk.fromSchema}.${fromTableId}.${fk.fromColumn}->${fk.toSchema}.${toTableId}.${fk.toColumn}`,
+ from: fromTableId,
+ to: toTableId,
+ };
+ });
+
+ const { rects } = await autoLayout(nodeList, edgeList);
+ if (myToken !== tokenRef.current) {
+ // A newer call superseded this one — discard.
+ return null;
+ }
+ return rects;
+ }, [selectedSchemas, edges, idOfTable, sizeOfTable]);
+}
diff --git a/frontend/src/components/SchemaDiagram/ER/libs/isFocusedFKTable.ts b/frontend/src/react/components/SchemaDiagram/ER/libs/isFocusedFKTable.ts
similarity index 100%
rename from frontend/src/components/SchemaDiagram/ER/libs/isFocusedFKTable.ts
rename to frontend/src/react/components/SchemaDiagram/ER/libs/isFocusedFKTable.ts
diff --git a/frontend/src/react/components/SchemaDiagram/Navigator/Navigator.tsx b/frontend/src/react/components/SchemaDiagram/Navigator/Navigator.tsx
new file mode 100644
index 0000000000..d9c1cbc3a2
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Navigator/Navigator.tsx
@@ -0,0 +1,81 @@
+import { ChevronLeft } from "lucide-react";
+import { useMemo, useState } from "react";
+import { PanelSearchBox } from "@/react/components/sql-editor/Panels/common/PanelSearchBox";
+import { cn } from "@/react/lib/utils";
+import { getInstanceResource, hasSchemaProperty } from "@/utils";
+import { useSchemaDiagramContext } from "../common/context";
+import { SchemaSelector } from "./SchemaSelector";
+import { NavigatorTree } from "./Tree";
+
+interface NavigatorProps {
+ /** Override the tree's default height. */
+ treeHeight?: number;
+}
+
+/**
+ * React port of `Navigator/Navigator.vue`. Collapsible left sidebar
+ * holding the schema selector (Postgres-style multi-schema only), a
+ * search input, and the schema → table tree.
+ */
+export function Navigator({ treeHeight = 480 }: NavigatorProps) {
+ const ctx = useSchemaDiagramContext();
+ const {
+ databaseMetadata,
+ selectedSchemaNames,
+ setSelectedSchemaNames,
+ database,
+ } = ctx;
+
+ const [expanded, setExpanded] = useState(true);
+ const [keyword, setKeyword] = useState("");
+
+ const showSchemaSelector = useMemo(
+ () => hasSchemaProperty(getInstanceResource(database).engine),
+ [database]
+ );
+
+ return (
+ <div className="relative h-full">
+ <div
+ className={cn(
+ "bb-schema-diagram--navigator--main h-full overflow-hidden border-y border-control-border flex flex-col transition-all bg-background",
+ expanded ? "w-72 shadow-sm border-l" : "w-0"
+ )}
+ >
+ <div className="p-1 flex flex-col gap-y-2 shrink-0">
+ {showSchemaSelector && (
+ <SchemaSelector
+ schemas={databaseMetadata.schemas}
+ value={selectedSchemaNames}
+ onChange={setSelectedSchemaNames}
+ />
+ )}
+ <PanelSearchBox
+ value={keyword}
+ onChange={setKeyword}
+ className="max-w-none"
+ />
+ </div>
+ <div className="w-full flex-1 overflow-x-hidden overflow-y-auto p-1 pr-2">
+ <NavigatorTree keyword={keyword} height={treeHeight} />
+ </div>
+ </div>
+
+ <button
+ type="button"
+ onClick={() => setExpanded((prev) => !prev)}
+ className={cn(
+ "absolute rounded-full shadow-lg w-6 h-6 top-16 flex items-center justify-center bg-background hover:bg-control-bg cursor-pointer transition-all",
+ expanded ? "left-full -translate-x-3" : "-left-3"
+ )}
+ >
+ <ChevronLeft
+ className={cn(
+ "size-4 transition-transform",
+ !expanded && "-scale-100 translate-x-[3px]"
+ )}
+ />
+ </button>
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/SchemaDiagram/Navigator/SchemaSelector.tsx b/frontend/src/react/components/SchemaDiagram/Navigator/SchemaSelector.tsx
new file mode 100644
index 0000000000..f8903069fe
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Navigator/SchemaSelector.tsx
@@ -0,0 +1,41 @@
+import { useTranslation } from "react-i18next";
+import { Combobox } from "@/react/components/ui/combobox";
+import type { SchemaMetadata } from "@/types/proto-es/v1/database_service_pb";
+
+interface SchemaSelectorProps {
+ schemas: SchemaMetadata[];
+ value: string[];
+ onChange: (value: string[]) => void;
+ /** Render the dropdown via portal — needed inside the Sheet body. */
+ portal?: boolean;
+}
+
+/**
+ * React port of `Navigator/SchemaSelector.vue`. Multi-select for which
+ * schemas to render in the diagram. Used only when the engine has a
+ * `schema` property (e.g. Postgres).
+ */
+export function SchemaSelector({
+ schemas,
+ value,
+ onChange,
+ portal,
+}: SchemaSelectorProps) {
+ const { t } = useTranslation();
+ const options = schemas.map((schema) => ({
+ value: schema.name,
+ label: schema.name,
+ }));
+
+ return (
+ <Combobox
+ multiple
+ value={value}
+ onChange={onChange}
+ options={options}
+ placeholder={t("schema-editor.schema.select")}
+ portal={portal}
+ clearable
+ />
+ );
+}
diff --git a/frontend/src/react/components/SchemaDiagram/Navigator/Tree.tsx b/frontend/src/react/components/SchemaDiagram/Navigator/Tree.tsx
new file mode 100644
index 0000000000..08f4596e2a
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Navigator/Tree.tsx
@@ -0,0 +1,120 @@
+import { useMemo } from "react";
+import {
+ Tree as ArboristTree,
+ type TreeDataNode,
+} from "@/react/components/ui/tree";
+import { cn } from "@/react/lib/utils";
+import { getInstanceResource, hasSchemaProperty } from "@/utils";
+import { DEFAULT_PADDINGS } from "../common/const";
+import { useSchemaDiagramContext } from "../common/context";
+import { Label, Prefix, Suffix } from "./TreeNode";
+import type { NavigatorTreeNode } from "./types";
+import { isTypedNode } from "./utils";
+
+interface NavigatorTreeProps {
+ keyword?: string;
+ /** Outer height of the virtualized tree viewport. */
+ height?: number;
+}
+
+/**
+ * React port of `Navigator/Tree.vue`. Reuses the shared `Tree` primitive
+ * (react-arborist) and renders schema → table levels with prefix /
+ * suffix slots. Clicking a table emits `set-center` so the canvas
+ * recenters on it.
+ */
+export function NavigatorTree({
+ keyword = "",
+ height = 480,
+}: NavigatorTreeProps) {
+ const ctx = useSchemaDiagramContext();
+ const { selectedSchemas, events, database } = ctx;
+
+ const isFlatTree = useMemo(
+ () => hasSchemaProperty(getInstanceResource(database).engine),
+ [database]
+ );
+
+ const data = useMemo<readonly TreeDataNode<NavigatorTreeNode>[]>(() => {
+ const schemaNodes = selectedSchemas.map((schema) => {
+ const tableChildren: TreeDataNode<NavigatorTreeNode>[] =
+ schema.tables.map((table) => ({
+ id: `table-${schema.name}-${table.name}`,
+ data: {
+ id: `table-${schema.name}-${table.name}`,
+ type: "table" as const,
+ data: table,
+ },
+ }));
+ const node: TreeDataNode<NavigatorTreeNode> = {
+ id: `schema-${schema.name}`,
+ children: tableChildren,
+ data: {
+ id: `schema-${schema.name}`,
+ type: "schema" as const,
+ data: schema,
+ children: tableChildren.map((c) => c.data),
+ },
+ };
+ return node;
+ });
+ // Mirror Vue: collapse the tree when there's a single, unnamed schema
+ // (e.g. MySQL's default schema) — show only the table children.
+ if (schemaNodes.length === 1 && selectedSchemas[0].name === "") {
+ return schemaNodes[0].children ?? [];
+ }
+ return schemaNodes;
+ }, [selectedSchemas]);
+
+ // Match Vue's `default-expand-all="true"` — every schema row opens
+ // expanded so the table children are visible without manual clicking.
+ const expandedIds = useMemo(() => data.map((node) => node.id), [data]);
+
+ return (
+ <ArboristTree<NavigatorTreeNode>
+ className={cn(
+ "bb-schema-diagram-nav-tree select-none",
+ isFlatTree && "flat"
+ )}
+ data={data}
+ height={height}
+ expandedIds={expandedIds}
+ searchTerm={keyword}
+ searchMatch={(node, term) =>
+ (node.data.data.name ?? "").toLowerCase().includes(term.toLowerCase())
+ }
+ renderNode={({ node, style, dragHandle }) => {
+ const treeNode = node.data.data;
+ return (
+ <div
+ ref={dragHandle}
+ style={style}
+ className={cn(
+ "group flex items-center gap-x-1 px-1 cursor-pointer hover:bg-control-bg"
+ )}
+ onClick={() => {
+ if (isTypedNode(treeNode, "schema")) {
+ node.toggle();
+ return;
+ }
+ if (isTypedNode(treeNode, "table")) {
+ void events.emit("set-center", {
+ type: "table",
+ target: treeNode.data,
+ padding: DEFAULT_PADDINGS,
+ });
+ }
+ }}
+ data-node-type={treeNode.type}
+ >
+ <Prefix node={treeNode} />
+ <div className="flex-1 min-w-0">
+ <Label node={treeNode} keyword={keyword} />
+ </div>
+ <Suffix node={treeNode} />
+ </div>
+ );
+ }}
+ />
+ );
+}
diff --git a/frontend/src/react/components/SchemaDiagram/Navigator/TreeNode/Label.tsx b/frontend/src/react/components/SchemaDiagram/Navigator/TreeNode/Label.tsx
new file mode 100644
index 0000000000..bb1888290a
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Navigator/TreeNode/Label.tsx
@@ -0,0 +1,38 @@
+import { useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import { HighlightLabelText } from "@/react/components/HighlightLabelText";
+import type { NavigatorTreeNode } from "../types";
+import { isTypedNode } from "../utils";
+
+interface LabelProps {
+ node: NavigatorTreeNode;
+ keyword: string;
+}
+
+/**
+ * React port of `Navigator/TreeNode/Label.vue`. Uses the shared
+ * `HighlightLabelText` for keyword highlighting (per the
+ * use-highlightlabeltext memory rule — never inline highlight HTML).
+ */
+export function Label({ node, keyword }: LabelProps) {
+ const { t } = useTranslation();
+ const text = useMemo(() => {
+ return node.data.name || t("db.schema.default");
+ }, [node, t]);
+
+ const id = `tree-node-label-${node.type}-${node.id}`;
+
+ return (
+ <div
+ className="flex items-center gap-x-1 max-w-full"
+ data-schema-editor-nav-tree-node-id={id}
+ >
+ <HighlightLabelText text={text} keyword={keyword} className="truncate" />
+ {isTypedNode(node, "schema") && (
+ <span className="shrink-0 text-control-light">
+ ({node.data.tables.length})
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/SchemaDiagram/Navigator/TreeNode/Prefix.tsx b/frontend/src/react/components/SchemaDiagram/Navigator/TreeNode/Prefix.tsx
new file mode 100644
index 0000000000..ed02d2adda
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Navigator/TreeNode/Prefix.tsx
@@ -0,0 +1,13 @@
+import { Layers, Table2 } from "lucide-react";
+import type { NavigatorTreeNode } from "../types";
+
+interface PrefixProps {
+ node: NavigatorTreeNode;
+}
+
+/** React port of `Navigator/TreeNode/Prefix.vue`. */
+export function Prefix({ node }: PrefixProps) {
+ if (node.type === "schema") return <Layers className="size-4" />;
+ if (node.type === "table") return <Table2 className="size-4" />;
+ return null;
+}
diff --git a/frontend/src/react/components/SchemaDiagram/Navigator/TreeNode/Suffix.tsx b/frontend/src/react/components/SchemaDiagram/Navigator/TreeNode/Suffix.tsx
new file mode 100644
index 0000000000..bca186ab03
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Navigator/TreeNode/Suffix.tsx
@@ -0,0 +1,27 @@
+import { FocusButton } from "../../common/FocusButton";
+import type { NavigatorTreeNode } from "../types";
+import { isTypedNode } from "../utils";
+
+interface SuffixProps {
+ node: NavigatorTreeNode;
+}
+
+/** React port of `Navigator/TreeNode/Suffix.vue`. */
+export function Suffix({ node }: SuffixProps) {
+ if (isTypedNode(node, "table")) {
+ // `FocusButton` defaults to `invisible` for unfocused tables (the
+ // canvas surface only shows it on per-table hover). The Vue tree
+ // relied on a `.bb-schema-diagram-nav-tree .n-tree-node:hover
+ // .focus-btn { visibility: visible }` rule that didn't survive the
+ // port. Re-create the affordance with `group-hover:visible` — the
+ // surrounding tree row in `Tree.tsx` sets `group`.
+ return (
+ <FocusButton
+ table={node.data}
+ setCenter
+ className="group-hover:visible"
+ />
+ );
+ }
+ return null;
+}
diff --git a/frontend/src/react/components/SchemaDiagram/Navigator/TreeNode/index.ts b/frontend/src/react/components/SchemaDiagram/Navigator/TreeNode/index.ts
new file mode 100644
index 0000000000..66b5b9b83c
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Navigator/TreeNode/index.ts
@@ -0,0 +1,3 @@
+export { Label } from "./Label";
+export { Prefix } from "./Prefix";
+export { Suffix } from "./Suffix";
diff --git a/frontend/src/react/components/SchemaDiagram/Navigator/index.ts b/frontend/src/react/components/SchemaDiagram/Navigator/index.ts
new file mode 100644
index 0000000000..fd47bffff9
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Navigator/index.ts
@@ -0,0 +1,4 @@
+export { Navigator } from "./Navigator";
+export { NavigatorTree } from "./Tree";
+export { SchemaSelector } from "./SchemaSelector";
+export type { NavigatorTreeNode, NodeType } from "./types";
diff --git a/frontend/src/components/SchemaDiagram/Navigator/types.ts b/frontend/src/react/components/SchemaDiagram/Navigator/types.ts
similarity index 59%
rename from frontend/src/components/SchemaDiagram/Navigator/types.ts
rename to frontend/src/react/components/SchemaDiagram/Navigator/types.ts
index 7884252803..5d3e5a9963 100644
--- a/frontend/src/components/SchemaDiagram/Navigator/types.ts
+++ b/frontend/src/react/components/SchemaDiagram/Navigator/types.ts
@@ -1,4 +1,3 @@
-import type { TreeOption } from "naive-ui";
import type {
SchemaMetadata,
TableMetadata,
@@ -11,10 +10,9 @@ type NodeTypeMapping = {
table: TableMetadata;
};
-export type TreeNode<T extends NodeType = NodeType> = TreeOption & {
- key: string;
+export type NavigatorTreeNode<T extends NodeType = NodeType> = {
+ id: string;
type: T;
data: NodeTypeMapping[T];
- isLeaf: boolean;
- children: TreeNode<NodeType>[];
+ children?: NavigatorTreeNode<NodeType>[];
};
diff --git a/frontend/src/react/components/SchemaDiagram/Navigator/utils.ts b/frontend/src/react/components/SchemaDiagram/Navigator/utils.ts
new file mode 100644
index 0000000000..1627010369
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/Navigator/utils.ts
@@ -0,0 +1,8 @@
+import type { NavigatorTreeNode, NodeType } from "./types";
+
+export const isTypedNode = <T extends NodeType>(
+ node: NavigatorTreeNode,
+ type: T
+): node is NavigatorTreeNode<T> => {
+ return node.type === type;
+};
diff --git a/frontend/src/react/components/SchemaDiagram/SchemaDiagram.tsx b/frontend/src/react/components/SchemaDiagram/SchemaDiagram.tsx
new file mode 100644
index 0000000000..a35436a311
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/SchemaDiagram.tsx
@@ -0,0 +1,232 @@
+import { LoaderCircle } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import type {
+ ColumnMetadata,
+ Database,
+ DatabaseMetadata,
+ SchemaMetadata,
+ TableMetadata,
+} from "@/types/proto-es/v1/database_service_pb";
+import { extractDatabaseResourceName } from "@/utils";
+import { Canvas } from "./Canvas/Canvas";
+import {
+ SchemaDiagramProvider,
+ useSchemaDiagramContext,
+} from "./common/context";
+import { ForeignKeyLine } from "./ER/ForeignKeyLine";
+import {
+ type ForeignKeyEdge,
+ useAutoLayout,
+} from "./ER/libs/autoLayout/useAutoLayout";
+import { TableNode } from "./ER/TableNode";
+import { Navigator } from "./Navigator/Navigator";
+import type { EditStatus } from "./types";
+
+interface SchemaDiagramProps {
+ database: Database;
+ databaseMetadata: DatabaseMetadata;
+ editable?: boolean;
+ schemaStatus?: (schema: SchemaMetadata) => EditStatus;
+ tableStatus?: (table: TableMetadata) => EditStatus;
+ columnStatus?: (column: ColumnMetadata) => EditStatus;
+ onEditTable?: (schema: SchemaMetadata, table: TableMetadata) => void;
+ onEditColumn?: (
+ schema: SchemaMetadata,
+ table: TableMetadata,
+ column: ColumnMetadata,
+ target: "name" | "type"
+ ) => void;
+}
+
+/**
+ * React port of `frontend/src/components/SchemaDiagram/SchemaDiagram.vue`.
+ * Composes Navigator + Canvas inside the per-instance React context;
+ * an inner `<Body>` component runs the ELK layout when metadata /
+ * selection changes.
+ */
+export function SchemaDiagram({
+ database,
+ databaseMetadata,
+ editable = false,
+ schemaStatus,
+ tableStatus,
+ columnStatus,
+ onEditTable,
+ onEditColumn,
+}: SchemaDiagramProps) {
+ return (
+ <SchemaDiagramProvider
+ database={database}
+ databaseMetadata={databaseMetadata}
+ editable={editable}
+ schemaStatus={schemaStatus}
+ tableStatus={tableStatus}
+ columnStatus={columnStatus}
+ >
+ <Body
+ databaseName={database.name}
+ onEditTable={onEditTable}
+ onEditColumn={onEditColumn}
+ />
+ </SchemaDiagramProvider>
+ );
+}
+
+interface BodyProps {
+ databaseName: string;
+ onEditTable?: SchemaDiagramProps["onEditTable"];
+ onEditColumn?: SchemaDiagramProps["onEditColumn"];
+}
+
+function Body({ databaseName, onEditTable, onEditColumn }: BodyProps) {
+ const ctx = useSchemaDiagramContext();
+ const {
+ busy,
+ selectedSchemas,
+ selectedSchemaNames,
+ setSelectedSchemaNames,
+ setFocusedTables,
+ foreignKeys,
+ idOfTable,
+ mergeTableRects,
+ events,
+ databaseMetadata,
+ } = ctx;
+
+ // Vue mirrors: pick the first schema as the initial selection, NOT all
+ // of them. (Most diagrams target a single schema; users can opt into
+ // others via the SchemaSelector.)
+ const lastInitializedMetadataRef = useRef<DatabaseMetadata | null>(null);
+ useEffect(() => {
+ if (lastInitializedMetadataRef.current === databaseMetadata) return;
+ lastInitializedMetadataRef.current = databaseMetadata;
+ const first = databaseMetadata.schemas[0]?.name ?? "";
+ setSelectedSchemaNames([first]);
+ }, [databaseMetadata, setSelectedSchemaNames]);
+
+ const [initialized, setInitialized] = useState(false);
+
+ // Edge list for ELK derived from foreignKeys.
+ const edges = useMemo<ForeignKeyEdge[]>(
+ () =>
+ foreignKeys.map((fk) => ({
+ fromSchema: fk.from.schema.name,
+ fromTable: fk.from.table,
+ fromColumn: fk.from.column,
+ toSchema: fk.to.schema.name,
+ toTable: fk.to.table,
+ toColumn: fk.to.column,
+ })),
+ [foreignKeys]
+ );
+
+ const sizeOfTable = useCallback((id: string) => {
+ const elem = document.querySelector(`[data-bb-node-id="${id}"]`);
+ if (!elem) return null;
+ const rect = elem.getBoundingClientRect();
+ return { width: rect.width, height: rect.height };
+ }, []);
+
+ const runLayout = useAutoLayout({
+ selectedSchemas,
+ edges,
+ idOfTable,
+ sizeOfTable,
+ });
+
+ // Drive the layout when (a) selectedSchemas changes, (b) the diagram
+ // emits "layout" via the context (e.g. external trigger).
+ const driveLayout = useCallback(async () => {
+ setFocusedTables(new Set());
+ // Defer one frame so newly-mounted TableNodes have laid out their
+ // DOM before we measure them.
+ await new Promise<void>((resolve) =>
+ requestAnimationFrame(() => resolve())
+ );
+ const rects = await runLayout();
+ if (!rects) return;
+ mergeTableRects(rects);
+ setInitialized(true);
+ requestAnimationFrame(() => {
+ void events.emit("fit-view");
+ void events.emit("render");
+ });
+ }, [runLayout, mergeTableRects, setFocusedTables, events]);
+
+ // Re-run layout on selection change.
+ // (selectedSchemas is a reference-stable derived from selectedSchemaNames
+ // + databaseMetadata, but listing its identity is enough.)
+ useEffect(() => {
+ if (selectedSchemaNames.length === 0) return;
+ void driveLayout();
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
+ selectedSchemas;
+ }, [selectedSchemas, selectedSchemaNames, driveLayout]);
+
+ // External `layout` trigger.
+ useEffect(() => {
+ const off = events.on("layout", () => {
+ void driveLayout();
+ });
+ return () => {
+ off();
+ };
+ }, [events, driveLayout]);
+
+ // External `edit-table` / `edit-column` events bridge to caller props.
+ useEffect(() => {
+ if (!onEditTable) return;
+ const off = events.on("edit-table", ({ schema, table }) => {
+ onEditTable(schema, table);
+ });
+ return () => {
+ off();
+ };
+ }, [events, onEditTable]);
+
+ useEffect(() => {
+ if (!onEditColumn) return;
+ const off = events.on(
+ "edit-column",
+ ({ schema, table, column, target }) => {
+ onEditColumn(schema, table, column, target);
+ }
+ );
+ return () => {
+ off();
+ };
+ }, [events, onEditColumn]);
+
+ const screenshotFilename = useCallback(() => {
+ const { databaseName: shortName } =
+ extractDatabaseResourceName(databaseName);
+ return `${shortName}.png`;
+ }, [databaseName]);
+
+ return (
+ <div className="w-full h-full relative overflow-hidden flex">
+ <Navigator />
+
+ <div className="flex-1 relative">
+ <Canvas screenshotFilename={screenshotFilename}>
+ {selectedSchemas.map((schema) =>
+ schema.tables.map((table) => (
+ <TableNode key={idOfTable(table)} schema={schema} table={table} />
+ ))
+ )}
+ {initialized &&
+ foreignKeys.map((fk, i) => <ForeignKeyLine key={i} fk={fk} />)}
+ </Canvas>
+
+ {(busy || !initialized) && (
+ <div
+ className="absolute inset-0 bg-white/40 flex items-center justify-center pointer-events-none"
+ data-screenshot-hide
+ >
+ <LoaderCircle className="size-6 text-accent animate-spin" />
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/SchemaDiagram/common/FocusButton.tsx b/frontend/src/react/components/SchemaDiagram/common/FocusButton.tsx
new file mode 100644
index 0000000000..56928d6f58
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/common/FocusButton.tsx
@@ -0,0 +1,77 @@
+import { ScanSearch } from "lucide-react";
+import { useCallback, useMemo } from "react";
+import { cn } from "@/react/lib/utils";
+import type { TableMetadata } from "@/types/proto-es/v1/database_service_pb";
+import { DEFAULT_PADDINGS } from "./const";
+import { useSchemaDiagramContext } from "./context";
+import { expectedZoomRange } from "./utils";
+
+interface FocusButtonProps {
+ table: TableMetadata;
+ /** Extra classes when the table is currently focused. */
+ focusedClass?: string;
+ /** When true, clicking re-centers the canvas on the table. Default: true. */
+ setCenter?: boolean;
+ className?: string;
+}
+
+/**
+ * React port of `frontend/src/components/SchemaDiagram/common/FocusButton.vue`.
+ *
+ * Toggles the `focusedTables` membership for the given table and (by
+ * default) emits `set-center` so the canvas re-centers + zooms onto it.
+ * Used inside Navigator tree node suffixes and on hover over each
+ * table card in the canvas.
+ */
+export function FocusButton({
+ table,
+ focusedClass = "",
+ setCenter = true,
+ className,
+}: FocusButtonProps) {
+ const ctx = useSchemaDiagramContext();
+ const { zoom, focusedTables, setFocusedTables, events } = ctx;
+
+ const isFocused = useMemo(
+ () => focusedTables.has(table),
+ [focusedTables, table]
+ );
+
+ const toggleFocus = useCallback(
+ (e: React.MouseEvent) => {
+ e.stopPropagation();
+ const next = new Set(focusedTables);
+ const turningOn = !next.has(table);
+ if (turningOn) {
+ next.add(table);
+ } else {
+ next.delete(table);
+ }
+ setFocusedTables(next);
+ if (setCenter) {
+ void events.emit("set-center", {
+ type: "table",
+ target: table,
+ padding: DEFAULT_PADDINGS,
+ zooms: turningOn ? expectedZoomRange(zoom, 0.5, 1) : undefined,
+ });
+ }
+ },
+ [table, focusedTables, setFocusedTables, setCenter, events, zoom]
+ );
+
+ return (
+ <button
+ type="button"
+ onClick={toggleFocus}
+ className={cn(
+ "p-0.5 rounded-sm hover:bg-control-bg",
+ isFocused ? "visible" : "invisible",
+ isFocused && focusedClass,
+ className
+ )}
+ >
+ <ScanSearch className="size-4" />
+ </button>
+ );
+}
diff --git a/frontend/src/components/SchemaDiagram/common/const.ts b/frontend/src/react/components/SchemaDiagram/common/const.ts
similarity index 100%
rename from frontend/src/components/SchemaDiagram/common/const.ts
rename to frontend/src/react/components/SchemaDiagram/common/const.ts
diff --git a/frontend/src/react/components/SchemaDiagram/common/context.tsx b/frontend/src/react/components/SchemaDiagram/common/context.tsx
new file mode 100644
index 0000000000..f29f439632
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/common/context.tsx
@@ -0,0 +1,295 @@
+import Emittery from "emittery";
+import { uniqueId } from "lodash-es";
+import {
+ createContext,
+ type ReactNode,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import type {
+ ColumnMetadata,
+ Database,
+ DatabaseMetadata,
+ SchemaMetadata,
+ TableMetadata,
+} from "@/types/proto-es/v1/database_service_pb";
+import type {
+ EditStatus,
+ ForeignKey,
+ Geometry,
+ Point,
+ Rect,
+ SchemaDiagramContext,
+ SchemaDiagramEvents,
+} from "../types";
+
+const Context = createContext<SchemaDiagramContext | null>(null);
+
+interface SchemaDiagramProviderProps {
+ database: Database;
+ databaseMetadata: DatabaseMetadata;
+ editable?: boolean;
+ /**
+ * When true, the provider is mounted for the screenshot off-screen
+ * pass — descendants should skip side effects (e.g. registering
+ * geometries) that would otherwise pollute the live diagram's state.
+ */
+ dummy?: boolean;
+ schemaStatus?: (schema: SchemaMetadata) => EditStatus;
+ tableStatus?: (table: TableMetadata) => EditStatus;
+ columnStatus?: (column: ColumnMetadata) => EditStatus;
+ children: ReactNode;
+}
+
+const DEFAULT_RECT: Rect = { x: 0, y: 0, width: 0, height: 0 };
+
+/**
+ * Per-instance React context for SchemaDiagram. Owns the Emittery event
+ * bus + reactive state used by Navigator / Canvas / ER children. Mounted
+ * once per `<SchemaDiagram>` instance — see Stage 19 design doc §4.
+ */
+export function SchemaDiagramProvider({
+ database,
+ databaseMetadata,
+ editable = false,
+ dummy = false,
+ schemaStatus: schemaStatusProp,
+ tableStatus: tableStatusProp,
+ columnStatus: columnStatusProp,
+ children,
+}: SchemaDiagramProviderProps) {
+ // Stable singletons for this instance.
+ const events = useMemo(() => new Emittery<SchemaDiagramEvents>(), []);
+ const geometriesRef = useRef<Set<Geometry>>(new Set());
+ // `WeakMap` (not `Map`) so old `TableMetadata` objects can be garbage
+ // collected when the user switches databases or refreshes metadata.
+ // A regular `Map` would pin every table object ever seen for the
+ // lifetime of the page, leaking memory in long SQL editor sessions.
+ // Matches the Vue implementation.
+ const tableIdsRef = useRef<WeakMap<TableMetadata, string>>(new WeakMap());
+
+ // Reactive state.
+ const [zoom, setZoom] = useState(1);
+ const [position, setPosition] = useState<Point>({ x: 0, y: 0 });
+ const [panning, setPanning] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [selectedSchemaNames, setSelectedSchemaNames] = useState<string[]>([]);
+ const [focusedTables, setFocusedTables] = useState<Set<TableMetadata>>(
+ () => new Set()
+ );
+ const [tableRects, setTableRects] = useState<Map<string, Rect>>(
+ () => new Map()
+ );
+ // Bumped by `addGeometry` / `removeGeometry` so consumers that read
+ // the live Set get a fresh render after each mutation.
+ const [, setGeometryVersion] = useState(0);
+
+ // Initialize selected schemas to the full list whenever metadata changes.
+ useEffect(() => {
+ setSelectedSchemaNames(databaseMetadata.schemas.map((s) => s.name));
+ }, [databaseMetadata]);
+
+ const selectedSchemas = useMemo(() => {
+ const set = new Set(selectedSchemaNames);
+ return databaseMetadata.schemas.filter((s) => set.has(s.name));
+ }, [databaseMetadata, selectedSchemaNames]);
+
+ const foreignKeys = useMemo<ForeignKey[]>(() => {
+ // Iterate ONLY `selectedSchemas` for both endpoints. If a user
+ // deselects a schema, FK edges that reference it are dropped — same
+ // semantics as Vue's `find()` helper. Otherwise ELK gets edges whose
+ // endpoints aren't in the node list, which destabilizes layout.
+ const out: ForeignKey[] = [];
+ for (const schema of selectedSchemas) {
+ for (const table of schema.tables) {
+ for (const fk of table.foreignKeys) {
+ if (fk.columns.length === 0) continue;
+ const referencedSchema = selectedSchemas.find(
+ (s) => s.name === fk.referencedSchema
+ );
+ if (!referencedSchema) continue;
+ const referencedTable = referencedSchema.tables.find(
+ (t) => t.name === fk.referencedTable
+ );
+ if (!referencedTable) continue;
+ for (let i = 0; i < fk.columns.length; i++) {
+ const column = fk.columns[i];
+ const referencedColumn = fk.referencedColumns[i] ?? "";
+ out.push({
+ from: { schema, table, column },
+ to: {
+ schema: referencedSchema,
+ table: referencedTable,
+ column: referencedColumn,
+ },
+ metadata: fk,
+ });
+ }
+ }
+ }
+ }
+ return out;
+ }, [selectedSchemas]);
+
+ const idOfTable = useCallback((table: TableMetadata) => {
+ let id = tableIdsRef.current.get(table);
+ if (!id) {
+ id = uniqueId("bb-table-");
+ tableIdsRef.current.set(table, id);
+ }
+ return id;
+ }, []);
+
+ const rectOfTable = useCallback(
+ (table: TableMetadata) => {
+ const id = idOfTable(table);
+ return tableRects.get(id) ?? DEFAULT_RECT;
+ },
+ [idOfTable, tableRects]
+ );
+
+ const updateTableRect = useCallback((id: string, rect: Rect) => {
+ setTableRects((prev) => {
+ const next = new Map(prev);
+ next.set(id, rect);
+ return next;
+ });
+ }, []);
+
+ const mergeTableRects = useCallback((rects: Map<string, Rect>) => {
+ setTableRects((prev) => {
+ const next = new Map(prev);
+ for (const [id, rect] of rects) {
+ next.set(id, rect);
+ }
+ return next;
+ });
+ }, []);
+
+ const addGeometry = useCallback((g: Geometry) => {
+ geometriesRef.current.add(g);
+ setGeometryVersion((v) => v + 1);
+ }, []);
+ const removeGeometry = useCallback((g: Geometry) => {
+ geometriesRef.current.delete(g);
+ setGeometryVersion((v) => v + 1);
+ }, []);
+
+ const render = useCallback(() => {
+ void events.emit("render");
+ }, [events]);
+ const layout = useCallback(() => {
+ void events.emit("layout");
+ }, [events]);
+
+ const schemaStatus = useCallback<(schema: SchemaMetadata) => EditStatus>(
+ (schema) => schemaStatusProp?.(schema) ?? "normal",
+ [schemaStatusProp]
+ );
+ const tableStatus = useCallback<(table: TableMetadata) => EditStatus>(
+ (table) => tableStatusProp?.(table) ?? "normal",
+ [tableStatusProp]
+ );
+ const columnStatus = useCallback<(column: ColumnMetadata) => EditStatus>(
+ (column) => columnStatusProp?.(column) ?? "normal",
+ [columnStatusProp]
+ );
+
+ const value = useMemo<SchemaDiagramContext>(
+ () => ({
+ database,
+ databaseMetadata,
+ editable,
+ foreignKeys,
+ dummy,
+ busy,
+ zoom,
+ position,
+ panning,
+ geometries: geometriesRef.current,
+ focusedTables,
+ selectedSchemaNames,
+ selectedSchemas,
+ setZoom,
+ setPosition,
+ setPanning,
+ setBusy,
+ setSelectedSchemaNames,
+ setFocusedTables,
+ addGeometry,
+ removeGeometry,
+ updateTableRect,
+ mergeTableRects,
+ idOfTable,
+ rectOfTable,
+ schemaStatus,
+ tableStatus,
+ columnStatus,
+ render,
+ layout,
+ events,
+ }),
+ [
+ database,
+ databaseMetadata,
+ editable,
+ foreignKeys,
+ dummy,
+ busy,
+ zoom,
+ position,
+ panning,
+ focusedTables,
+ selectedSchemaNames,
+ selectedSchemas,
+ addGeometry,
+ removeGeometry,
+ updateTableRect,
+ mergeTableRects,
+ idOfTable,
+ rectOfTable,
+ schemaStatus,
+ tableStatus,
+ columnStatus,
+ render,
+ layout,
+ events,
+ ]
+ );
+
+ return <Context value={value}>{children}</Context>;
+}
+
+export function useSchemaDiagramContext(): SchemaDiagramContext {
+ const ctx = useContext(Context);
+ if (!ctx) {
+ throw new Error(
+ "useSchemaDiagramContext must be called inside <SchemaDiagramProvider>"
+ );
+ }
+ return ctx;
+}
+
+/**
+ * Register a geometry with the parent SchemaDiagram so the canvas can
+ * include it when computing the bbox for `fit-view`. Mirrors Vue's
+ * `useGeometry(geometry)` composable. Skipped when the diagram is in
+ * dummy (off-screen screenshot) mode.
+ */
+export function useGeometry(geometry: Geometry) {
+ const ctx = useSchemaDiagramContext();
+ const dummy = ctx.dummy;
+ const addGeometry = ctx.addGeometry;
+ const removeGeometry = ctx.removeGeometry;
+ useEffect(() => {
+ if (dummy) return;
+ addGeometry(geometry);
+ return () => {
+ removeGeometry(geometry);
+ };
+ }, [geometry, dummy, addGeometry, removeGeometry]);
+}
diff --git a/frontend/src/react/components/SchemaDiagram/common/geometry.test.ts b/frontend/src/react/components/SchemaDiagram/common/geometry.test.ts
new file mode 100644
index 0000000000..9d55d05d35
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/common/geometry.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from "vitest";
+import {
+ calcBBox,
+ isPath,
+ isPoint,
+ isRect,
+ pointsOfRect,
+ segmentOverlap1D,
+} from "./geometry";
+
+describe("SchemaDiagram geometry helpers", () => {
+ it("classifies geometries", () => {
+ expect(isPoint({ x: 1, y: 2 })).toBe(true);
+ expect(isPoint({ x: 1, y: 2, width: 3, height: 4 })).toBe(false);
+ expect(isPath([{ x: 1, y: 2 }])).toBe(true);
+ expect(isRect({ x: 1, y: 2, width: 3, height: 4 })).toBe(true);
+ });
+
+ it("returns the four corners of a rect", () => {
+ const rect = { x: 10, y: 20, width: 30, height: 40 };
+ expect(pointsOfRect(rect)).toEqual([
+ { x: 10, y: 20 },
+ { x: 40, y: 20 },
+ { x: 10, y: 60 },
+ { x: 40, y: 60 },
+ ]);
+ });
+
+ it("computes the bbox covering mixed geometries", () => {
+ const bbox = calcBBox([
+ { x: 0, y: 0 },
+ { x: 100, y: 80, width: 20, height: 20 },
+ [
+ { x: -5, y: 5 },
+ { x: 50, y: 50 },
+ ],
+ ]);
+ expect(bbox).toEqual({ x: -5, y: 0, width: 125, height: 100 });
+ });
+
+ it("returns a zero rect when no geometries are provided", () => {
+ expect(calcBBox([])).toEqual({ x: 0, y: 0, width: 0, height: 0 });
+ });
+
+ describe("segmentOverlap1D", () => {
+ it("classifies all six relations between AB and CD", () => {
+ // 1. AB before CD (A-B C-D)
+ expect(segmentOverlap1D(0, 1, 2, 3)).toBe("BEFORE");
+ // 2. AB overlaps CD (A-C-B-D)
+ expect(segmentOverlap1D(0, 5, 3, 8)).toBe("OVERLAPS");
+ // 3. AB contains CD (A-C-D-B)
+ expect(segmentOverlap1D(0, 10, 3, 7)).toBe("CONTAINS");
+ // 4. AB overlapped by CD (C-A-D-B)
+ expect(segmentOverlap1D(3, 8, 0, 5)).toBe("OVERLAPPED");
+ // 5. AB contained by CD (C-A-B-D)
+ expect(segmentOverlap1D(3, 7, 0, 10)).toBe("CONTAINED");
+ // 6. AB after CD (C-D A-B)
+ expect(segmentOverlap1D(5, 6, 0, 4)).toBe("AFTER");
+ });
+ });
+});
diff --git a/frontend/src/components/SchemaDiagram/common/geometry.ts b/frontend/src/react/components/SchemaDiagram/common/geometry.ts
similarity index 93%
rename from frontend/src/components/SchemaDiagram/common/geometry.ts
rename to frontend/src/react/components/SchemaDiagram/common/geometry.ts
index 75fe2fc1d7..a48e33da52 100644
--- a/frontend/src/components/SchemaDiagram/common/geometry.ts
+++ b/frontend/src/react/components/SchemaDiagram/common/geometry.ts
@@ -1,4 +1,7 @@
-import { minmax } from "@/utils";
+// Deep import: `@/utils` (the barrel) transitively pulls in Monaco, which
+// can't be resolved in the vitest environment. `minmax` itself is a pure
+// math helper; importing it directly keeps the geometry helpers test-safe.
+import { minmax } from "@/utils/math";
import type { Geometry, Path, Point, Rect, Size } from "../types";
export const pointsOfRect = (rect: Rect): Point[] => {
@@ -68,6 +71,7 @@ export const segmentOverlap1D = (
throw new Error(`should never be here a=${a}, b=${b}, c=${c}, d=${d}`);
};
+
export const isPoint = (geometry: Geometry): geometry is Point => {
if (Array.isArray(geometry)) {
return false;
diff --git a/frontend/src/components/SchemaDiagram/common/index.ts b/frontend/src/react/components/SchemaDiagram/common/index.ts
similarity index 69%
rename from frontend/src/components/SchemaDiagram/common/index.ts
rename to frontend/src/react/components/SchemaDiagram/common/index.ts
index 86253564bc..2a55a95258 100644
--- a/frontend/src/components/SchemaDiagram/common/index.ts
+++ b/frontend/src/react/components/SchemaDiagram/common/index.ts
@@ -1,10 +1,6 @@
-import FocusButton from "./FocusButton.vue";
-
export * from "./const";
export * from "./context";
-export * from "./useDraggable";
export * from "./geometry";
export * from "./schema";
+export * from "./useDraggable";
export * from "./utils";
-
-export { FocusButton };
diff --git a/frontend/src/components/SchemaDiagram/common/schema.ts b/frontend/src/react/components/SchemaDiagram/common/schema.ts
similarity index 100%
rename from frontend/src/components/SchemaDiagram/common/schema.ts
rename to frontend/src/react/components/SchemaDiagram/common/schema.ts
diff --git a/frontend/src/react/components/SchemaDiagram/common/useDraggable.tsx b/frontend/src/react/components/SchemaDiagram/common/useDraggable.tsx
new file mode 100644
index 0000000000..bf7e09b032
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/common/useDraggable.tsx
@@ -0,0 +1,79 @@
+import { useEffect, useRef } from "react";
+
+export type DraggableOptions = {
+ exact?: boolean;
+ onStart?: () => void;
+ onPan?: (dx: number, dy: number) => void;
+ onEnd?: () => void;
+ capture?: boolean;
+};
+
+/**
+ * React port of `frontend/src/components/SchemaDiagram/common/useDraggable.ts`.
+ *
+ * Pointer-driven drag listener. Attaches `pointerdown` to the given
+ * element and `pointermove` / `pointerup` to `window`, mirroring the
+ * Vue `vueuse` setup so a drag continues even if the pointer leaves
+ * the element. `screenX`/`screenY` are used (matching Vue) so the
+ * delta is independent of the element's position when it's the one
+ * being dragged.
+ *
+ * Pass `null` while the element is unmounted; the hook re-attaches
+ * when a real element arrives. Callbacks are read through a ref so
+ * inline option objects don't re-run the effect each render.
+ */
+export const useDraggable = (
+ target: Element | null,
+ options: DraggableOptions
+) => {
+ const optionsRef = useRef(options);
+ optionsRef.current = options;
+
+ useEffect(() => {
+ if (!target) return;
+
+ let startPointer: { x: number; y: number } | undefined;
+ let lastPointer: { x: number; y: number } | undefined;
+
+ const start = (e: PointerEvent) => {
+ const opts = optionsRef.current;
+ if (opts.exact && e.target !== target) return;
+ startPointer = { x: e.screenX, y: e.screenY };
+ lastPointer = { x: e.screenX, y: e.screenY };
+ e.stopPropagation();
+ e.preventDefault();
+ opts.onStart?.();
+ };
+ const move = (e: PointerEvent) => {
+ if (!startPointer || !lastPointer) return;
+ const opts = optionsRef.current;
+ const pointer = { x: e.screenX, y: e.screenY };
+ e.stopPropagation();
+ e.preventDefault();
+ opts.onPan?.(pointer.x - lastPointer.x, pointer.y - lastPointer.y);
+ lastPointer = pointer;
+ };
+ const end = (e: PointerEvent) => {
+ const opts = optionsRef.current;
+ startPointer = undefined;
+ lastPointer = undefined;
+ e.stopPropagation();
+ e.preventDefault();
+ opts.onEnd?.();
+ };
+
+ const capture = optionsRef.current.capture ?? false;
+ target.addEventListener("pointerdown", start as EventListener, capture);
+ window.addEventListener("pointermove", move, capture);
+ window.addEventListener("pointerup", end, capture);
+ return () => {
+ target.removeEventListener(
+ "pointerdown",
+ start as EventListener,
+ capture
+ );
+ window.removeEventListener("pointermove", move, capture);
+ window.removeEventListener("pointerup", end, capture);
+ };
+ }, [target]);
+};
diff --git a/frontend/src/components/SchemaDiagram/common/utils.ts b/frontend/src/react/components/SchemaDiagram/common/utils.ts
similarity index 100%
rename from frontend/src/components/SchemaDiagram/common/utils.ts
rename to frontend/src/react/components/SchemaDiagram/common/utils.ts
diff --git a/frontend/src/react/components/SchemaDiagram/index.ts b/frontend/src/react/components/SchemaDiagram/index.ts
new file mode 100644
index 0000000000..28f431fcff
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/index.ts
@@ -0,0 +1,2 @@
+export { SchemaDiagram } from "./SchemaDiagram";
+export type { SchemaDiagramContext, EditStatus, ForeignKey } from "./types";
diff --git a/frontend/src/react/components/SchemaDiagram/types/context.ts b/frontend/src/react/components/SchemaDiagram/types/context.ts
new file mode 100644
index 0000000000..98c510feb1
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagram/types/context.ts
@@ -0,0 +1,107 @@
+import type Emittery from "emittery";
+import type {
+ ColumnMetadata,
+ Database,
+ DatabaseMetadata,
+ SchemaMetadata,
+ TableMetadata,
+} from "@/types/proto-es/v1/database_service_pb";
+import type { EditStatus } from "./edit";
+import type { Geometry, Point, Rect } from "./geometry";
+import type { ForeignKey } from "./schema";
+
+/**
+ * React port of the Vue `SchemaDiagramContext`. Values are stored as plain
+ * fields (held by React state inside the provider) instead of Vue `Ref<T>`,
+ * matching the per-instance React-context pattern decided in the Stage 19
+ * design doc.
+ *
+ * Mutators are exposed as methods rather than direct setters so the
+ * provider can scope updates inside `useState`/`useRef` correctly. Methods
+ * are stable (wrapped in `useCallback`) so descendants can list them in
+ * effect deps without re-running on every render.
+ */
+export type SchemaDiagramContext = {
+ // Props (set once by the SchemaDiagram root from its own props)
+ database: Database;
+ databaseMetadata: DatabaseMetadata;
+ editable: boolean;
+
+ // Reactive state (mutates over time, drives renders)
+ foreignKeys: ForeignKey[];
+ dummy: boolean;
+ busy: boolean;
+ zoom: number;
+ position: Point;
+ panning: boolean;
+ /**
+ * Mutable Set tracked across descendants via the `useGeometry` hook.
+ * It's a live reference (not a copy) so consumers can read it inside
+ * a single render without triggering an extra round-trip; writes go
+ * through `addGeometry` / `removeGeometry`.
+ */
+ geometries: Set<Geometry>;
+ focusedTables: Set<TableMetadata>;
+ selectedSchemaNames: string[];
+ selectedSchemas: SchemaMetadata[];
+
+ // State mutators (stable references)
+ setZoom: (zoom: number) => void;
+ setPosition: (position: Point) => void;
+ setPanning: (panning: boolean) => void;
+ setBusy: (busy: boolean) => void;
+ setSelectedSchemaNames: (names: string[]) => void;
+ setFocusedTables: (tables: Set<TableMetadata>) => void;
+ addGeometry: (g: Geometry) => void;
+ removeGeometry: (g: Geometry) => void;
+ /**
+ * Replace one table's rect (e.g. after a per-table drag). The first
+ * argument is the table id from `idOfTable(table)`.
+ */
+ updateTableRect: (id: string, rect: Rect) => void;
+ /**
+ * Bulk-merge rects after auto-layout resolves. Updates state in a
+ * single pass so descendants re-render once.
+ */
+ mergeTableRects: (rects: Map<string, Rect>) => void;
+
+ // Pure helpers (do not depend on context state)
+ idOfTable: (table: TableMetadata) => string;
+ rectOfTable: (table: TableMetadata) => Rect;
+ schemaStatus: (schema: SchemaMetadata) => EditStatus;
+ tableStatus: (table: TableMetadata) => EditStatus;
+ columnStatus: (column: ColumnMetadata) => EditStatus;
+
+ // Imperative actions (fire-and-forget)
+ render: () => void;
+ layout: () => void;
+
+ // Event bus (per-instance Emittery — see design doc §4 / §8)
+ events: Emittery<SchemaDiagramEvents>;
+};
+
+export type SchemaDiagramEvents = {
+ render: undefined;
+ layout: undefined;
+ "fit-view": undefined;
+ "edit-table": { schema: SchemaMetadata; table: TableMetadata };
+ "edit-column": {
+ schema: SchemaMetadata;
+ table: TableMetadata;
+ column: ColumnMetadata;
+ target: "name" | "type";
+ };
+ "set-center": CenterTarget;
+};
+
+export type CenterTargetType = "table" | "rect" | "point";
+export type CenterTarget<T extends CenterTargetType = CenterTargetType> = {
+ type: T;
+ target: {
+ table: TableMetadata;
+ rect: Rect;
+ point: Point;
+ }[T];
+ padding?: number[]; // [T,R,B,L]
+ zooms?: number[]; // [min, max]
+};
diff --git a/frontend/src/components/SchemaDiagram/types/edit.ts b/frontend/src/react/components/SchemaDiagram/types/edit.ts
similarity index 100%
rename from frontend/src/components/SchemaDiagram/types/edit.ts
rename to frontend/src/react/components/SchemaDiagram/types/edit.ts
diff --git a/frontend/src/components/SchemaDiagram/types/geometry.ts b/frontend/src/react/components/SchemaDiagram/types/geometry.ts
similarity index 100%
rename from frontend/src/components/SchemaDiagram/types/geometry.ts
rename to frontend/src/react/components/SchemaDiagram/types/geometry.ts
diff --git a/frontend/src/components/SchemaDiagram/types/index.ts b/frontend/src/react/components/SchemaDiagram/types/index.ts
similarity index 100%
rename from frontend/src/components/SchemaDiagram/types/index.ts
rename to frontend/src/react/components/SchemaDiagram/types/index.ts
index 3f1e68246c..3c72c0d4f0 100644
--- a/frontend/src/components/SchemaDiagram/types/index.ts
+++ b/frontend/src/react/components/SchemaDiagram/types/index.ts
@@ -1,4 +1,4 @@
export * from "./context";
+export * from "./edit";
export * from "./geometry";
export * from "./schema";
-export * from "./edit";
diff --git a/frontend/src/components/SchemaDiagram/types/schema.ts b/frontend/src/react/components/SchemaDiagram/types/schema.ts
similarity index 100%
rename from frontend/src/components/SchemaDiagram/types/schema.ts
rename to frontend/src/react/components/SchemaDiagram/types/schema.ts
diff --git a/frontend/src/react/components/SchemaDiagramPage.tsx b/frontend/src/react/components/SchemaDiagramPage.tsx
new file mode 100644
index 0000000000..7d17e00f22
--- /dev/null
+++ b/frontend/src/react/components/SchemaDiagramPage.tsx
@@ -0,0 +1,11 @@
+/**
+ * Top-level page shim so `ReactPageMount` can locate the
+ * `<SchemaDiagram>` root via `mount.ts`'s `pageDirs` lookup (it scans
+ * for `<page>.tsx` files, not directories).
+ *
+ * Vue callers mount this with `<ReactPageMount page="SchemaDiagramPage"
+ * :page-props="{ database, databaseMetadata, editable, onEditTable,
+ * onEditColumn }">` to render the React diagram inside a still-Vue
+ * surface (e.g. `SchemaEditorLite/Panels/DatabaseEditor.vue`).
+ */
+export { SchemaDiagram as SchemaDiagramPage } from "./SchemaDiagram";
diff --git a/frontend/src/react/components/database/DatabaseTableView.tsx b/frontend/src/react/components/database/DatabaseTableView.tsx
index b2ab9ebc3b..5e7f9641b5 100644
--- a/frontend/src/react/components/database/DatabaseTableView.tsx
+++ b/frontend/src/react/components/database/DatabaseTableView.tsx
@@ -265,10 +265,20 @@ export function DatabaseTableView({
),
});
return cols;
- // toggleSelection / toggleSelectAll close over selectedNames /
- // onSelectedNamesChange but they're stable callbacks within a single
- // render and the cell handlers re-bind on every render anyway.
- }, [showSelection, showProjectColumn, allSelected, selectedNames, t]);
+ // `databases` and `onSelectedNamesChange` belong here because the
+ // header checkbox's `toggleSelectAll` closes over both. Pagination /
+ // filtering can replace `databases` while `allSelected` stays false —
+ // without listing it the memoized handler keeps the previous page's
+ // names and "select all" selects the wrong rows.
+ }, [
+ showSelection,
+ showProjectColumn,
+ allSelected,
+ selectedNames,
+ onSelectedNamesChange,
+ databases,
+ t,
+ ]);
const { widths, totalWidth, onResizeStart } = useColumnWidths(columns);
diff --git a/frontend/src/react/components/database/TransferProjectSheet.tsx b/frontend/src/react/components/database/TransferProjectSheet.tsx
index 276f4e3e6c..d99c648db7 100644
--- a/frontend/src/react/components/database/TransferProjectSheet.tsx
+++ b/frontend/src/react/components/database/TransferProjectSheet.tsx
@@ -54,12 +54,13 @@ export function TransferProjectSheet({
{t("database.selected-n-databases", { n: databases.length })}
</p>
- {/* Table grows / shrinks to fill remaining SheetBody space and
- becomes the scroll container when the rows exceed it. The
- `min-h-0` is required so flex can shrink it below the
- natural content height; without it the children's intrinsic
- size would push the SheetBody to overflow instead. */}
- <div className="flex-1 min-h-0 overflow-y-auto">
+ {/* Table is naturally sized — short lists stay short. When the
+ row count would push the SheetBody past its bounds, this
+ wrapper is the only flex child without `shrink-0`, so it
+ shrinks to absorb the overflow and `overflow-y-auto` engages.
+ `min-h-0` lifts the implicit `min-height: auto` floor so the
+ shrink can go below the natural content height. */}
+ <div className="min-h-0 overflow-y-auto">
<DatabaseTableView databases={databases} />
</div>
diff --git a/frontend/src/react/components/sql-editor/DiagramPanel.tsx b/frontend/src/react/components/sql-editor/DiagramPanel.tsx
new file mode 100644
index 0000000000..6407cef254
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/DiagramPanel.tsx
@@ -0,0 +1,29 @@
+import { SchemaDiagram } from "@/react/components/SchemaDiagram";
+import { useVueState } from "@/react/hooks/useVueState";
+import {
+ useConnectionOfCurrentSQLEditorTab,
+ useDBSchemaV1Store,
+} from "@/store";
+
+/**
+ * React port of `frontend/src/views/sql-editor/EditorPanel/Panels/DiagramPanel/DiagramPanel.vue`.
+ *
+ * Reads the current tab's database from the SQL Editor connection
+ * store + its metadata from `useDBSchemaV1Store`, and forwards both
+ * to `<SchemaDiagram>`. Mounted by `Panels.vue` via `ReactPageMount`.
+ */
+export function DiagramPanel() {
+ const dbSchemaStore = useDBSchemaV1Store();
+ const { database: databaseRef } = useConnectionOfCurrentSQLEditorTab();
+ const database = useVueState(() => databaseRef.value);
+ const databaseMetadata = useVueState(
+ () => dbSchemaStore.getDatabaseMetadata(database.name),
+ { deep: true }
+ );
+
+ return (
+ <div className="w-full h-full bb-react-schema-diagram">
+ <SchemaDiagram database={database} databaseMetadata={databaseMetadata} />
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx
index 0250fb6e73..80c64ec2c2 100644
--- a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx
+++ b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx
@@ -345,7 +345,7 @@ type TabButtonProps = {
onClose: () => void;
isFailed: boolean;
isEmpty: boolean;
-};
+} & Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "onClick">;
function TabButton({
item,
@@ -354,7 +354,11 @@ function TabButton({
onClose,
isFailed,
isEmpty,
-}: TabButtonProps) {
+ ref,
+ className,
+ style: styleProp,
+ ...rest
+}: TabButtonProps & { ref?: React.Ref<HTMLButtonElement> }) {
const { t } = useTranslation();
const environment = getDatabaseEnvironment(item.database);
const colorRgb = hexToRgb(environment.color || "#4f46e5").join(", ");
@@ -363,18 +367,22 @@ function TabButton({
borderTopColor: `rgb(${colorRgb})`,
color: `rgb(${colorRgb})`,
borderTop: isSelected ? "3px solid" : "",
+ ...styleProp,
};
const instance = getInstanceResource(item.database);
return (
<button
type="button"
+ ref={ref}
style={style}
onClick={onSelect}
className={cn(
"inline-flex items-center gap-x-1 h-7 px-2 rounded-xs text-xs font-medium",
- "border border-control-border cursor-pointer whitespace-nowrap"
+ "border border-control-border cursor-pointer whitespace-nowrap",
+ className
)}
+ {...rest}
>
{EngineIconPath[instance.engine] && (
<img
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index f134dd4cc4..e1d15dfe1f 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -1950,6 +1950,7 @@
"rollout.task.selected-count": "{{count}} task selected",
"rollout.task.statement-truncated-hint": "Statement truncated due to large size.",
"schema-diagram": {
+ "fit-content-with-view": "Fit content within view",
"self": "Schema Diagram"
},
"schema-editor": {
@@ -2018,7 +2019,8 @@
"raw-sql": "Raw SQL",
"schema": {
"duplicate-name": "Schema name already exists",
- "name-placeholder": "Schema name"
+ "name-placeholder": "Schema name",
+ "select": "Select schema"
},
"self": "Schema editor",
"table": {
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index 9dc9df3211..64bd7913a6 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -1937,6 +1937,7 @@
"rollout.task.selected-count": "{{count}} tarea seleccionada",
"rollout.task.statement-truncated-hint": "Declaración truncada debido al gran tamaño.",
"schema-diagram": {
+ "fit-content-with-view": "Ajustar contenido dentro de la vista",
"self": "Diagrama de Esquema"
},
"schema-editor": {
@@ -2005,7 +2006,8 @@
"raw-sql": "Raw SQL",
"schema": {
"duplicate-name": "Schema name already exists",
- "name-placeholder": "Schema name"
+ "name-placeholder": "Schema name",
+ "select": "Seleccionar esquema"
},
"self": "Editor de esquema",
"table": {
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index 22044c7a9f..b660290073 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -1937,6 +1937,7 @@
"rollout.task.selected-count": "{{count}} 件のタスクを選択中",
"rollout.task.statement-truncated-hint": "サイズが大きいため、ステートメントは切り捨てられました。",
"schema-diagram": {
+ "fit-content-with-view": "ビューに自動的に適応します",
"self": "スキーマ図"
},
"schema-editor": {
@@ -2005,7 +2006,8 @@
"raw-sql": "Raw SQL",
"schema": {
"duplicate-name": "Schema name already exists",
- "name-placeholder": "Schema name"
+ "name-placeholder": "Schema name",
+ "select": "スキーマの選択"
},
"self": "スキーマエディタ",
"table": {
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index f3bf7dc1d3..ddb36cc31e 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -1937,6 +1937,7 @@
"rollout.task.selected-count": "Đã chọn {{count}} tác vụ",
"rollout.task.statement-truncated-hint": "Câu lệnh bị cắt bớt do kích thước lớn.",
"schema-diagram": {
+ "fit-content-with-view": "Điều chỉnh nội dung vừa với khung nhìn",
"self": "Sơ đồ Lược đồ"
},
"schema-editor": {
@@ -2005,7 +2006,8 @@
"raw-sql": "Raw SQL",
"schema": {
"duplicate-name": "Schema name already exists",
- "name-placeholder": "Schema name"
+ "name-placeholder": "Schema name",
+ "select": "Chọn lược đồ"
},
"self": "Trình chỉnh sửa lược đồ",
"table": {
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index 1de2cf45d9..22903e5fa8 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -1937,6 +1937,7 @@
"rollout.task.selected-count": "已选择 {{count}} 个任务",
"rollout.task.statement-truncated-hint": "由于语句过长,已被截断。",
"schema-diagram": {
+ "fit-content-with-view": "自动适应视图",
"self": "Schema 关系图"
},
"schema-editor": {
@@ -2005,7 +2006,8 @@
"raw-sql": "Raw SQL",
"schema": {
"duplicate-name": "Schema name already exists",
- "name-placeholder": "Schema name"
+ "name-placeholder": "Schema name",
+ "select": "选择 schema"
},
"self": "Schema 编辑器",
"table": {
diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/DiagramPanel/DiagramPanel.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/DiagramPanel/DiagramPanel.vue
deleted file mode 100644
index 9b27bc0d8c..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/Panels/DiagramPanel/DiagramPanel.vue
+++ /dev/null
@@ -1,23 +0,0 @@
-<template>
- <SchemaDiagram
- :database="database"
- :database-metadata="dbSchemaStore.getDatabaseMetadata(database.name)"
- />
-</template>
-
-<script setup lang="ts">
-import SchemaDiagram from "@/components/SchemaDiagram";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
-} from "@/store";
-
-const dbSchemaStore = useDBSchemaV1Store();
-const { database } = useConnectionOfCurrentSQLEditorTab();
-</script>
-
-<style lang="postcss" scoped>
-:deep(.bb-schema-diagram--navigator--main) {
- border-width: 0;
-}
-</style>
diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/DiagramPanel/index.ts b/frontend/src/views/sql-editor/EditorPanel/Panels/DiagramPanel/index.ts
deleted file mode 100644
index ed510ec4af..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/Panels/DiagramPanel/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import DiagramPanel from "./DiagramPanel.vue";
-
-export default DiagramPanel;
diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue
index d624f517c6..73d2388a6d 100644
--- a/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue
@@ -73,9 +73,10 @@
:key="`external-tables-${tab?.id}`"
page="ExternalTablesPanel"
/>
- <DiagramPanel
+ <ReactPageMount
v-if="viewState.view === 'DIAGRAM'"
- :key="tab?.id"
+ :key="`diagram-${tab?.id}`"
+ page="DiagramPanel"
/>
</template>
<template v-if="showAIPaneAlongsidePanel" #2>
@@ -127,7 +128,6 @@ import {
type VueClass,
} from "@/utils";
import { useCurrentTabViewStateContext } from "../context/viewState.tsx";
-import DiagramPanel from "./DiagramPanel";
defineProps<{
contentClass?: VueClass;
diff --git a/frontend/tsconfig.app.json b/frontend/tsconfig.app.json
index 3c7a08a279..96dd60e136 100644
--- a/frontend/tsconfig.app.json
+++ b/frontend/tsconfig.app.json
@@ -14,6 +14,13 @@
"src/react/components/task-run-log/index.ts",
"src/react/components/monaco/index.ts",
"src/react/components/revision/index.ts",
+ "src/react/components/SchemaDiagram/index.ts",
+ "src/react/components/SchemaDiagram/Canvas/index.ts",
+ "src/react/components/SchemaDiagram/Canvas/composables/index.ts",
+ "src/react/components/SchemaDiagram/ER/index.ts",
+ "src/react/components/SchemaDiagram/Navigator/index.ts",
+ "src/react/components/SchemaDiagram/Navigator/TreeNode/index.ts",
+ "src/react/components/SchemaDiagram/common/index.ts",
"src/react/components/SchemaEditorLite/index.ts",
"src/react/components/SchemaEditorLite/Aside/index.ts",
"src/react/components/SchemaEditorLite/Panels/TableColumnEditor/index.ts",
diff --git a/frontend/tsconfig.vitest.json b/frontend/tsconfig.vitest.json
index aad6356059..cd3a92306e 100644
--- a/frontend/tsconfig.vitest.json
+++ b/frontend/tsconfig.vitest.json
@@ -13,6 +13,13 @@
"src/react/components/task-run-log/index.ts",
"src/react/components/monaco/index.ts",
"src/react/components/revision/index.ts",
+ "src/react/components/SchemaDiagram/index.ts",
+ "src/react/components/SchemaDiagram/Canvas/index.ts",
+ "src/react/components/SchemaDiagram/Canvas/composables/index.ts",
+ "src/react/components/SchemaDiagram/ER/index.ts",
+ "src/react/components/SchemaDiagram/Navigator/index.ts",
+ "src/react/components/SchemaDiagram/Navigator/TreeNode/index.ts",
+ "src/react/components/SchemaDiagram/common/index.ts",
"src/react/components/SchemaEditorLite/index.ts",
"src/react/components/SchemaEditorLite/Aside/index.ts",
"src/react/components/SchemaEditorLite/Panels/TableColumnEditor/index.ts",