Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(schema-diagram): basic canvas and table nodes (#3944)
Liu Jieb429c49083b
diff --git a/frontend/package.json b/frontend/package.jsonindex 25cedd46fd..6b1f95c8b8 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -24,9 +24,11 @@"axios": "1.1.3","bootstrap": "5.2.2","canvas-confetti": "1.6.0",+ "dagre": "^0.8.5","dayjs": "1.11.6","dompurify": "2.4.0","downloadjs": "1.4.7",+ "emittery": "^1.0.1","escape-string-regexp": "5.0.0","highlight.js": "11.6.0","inter-ui": "3.19.3",@@ -36,6 +38,7 @@"monaco-languageclient": "4.0.1","naive-ui": "2.33.5","node-sql-parser": "4.5.1",+ "normalize-wheel": "^1.0.1","papaparse": "5.3.2","pev2": "1.5.0","pinia": "2.0.23",@@ -68,11 +71,13 @@"@tailwindcss/line-clamp": "0.4.2","@tailwindcss/typography": "0.5.8","@types/canvas-confetti": "1.4.3",+ "@types/dagre": "^0.7.48","@types/dompurify": "2.3.4","@types/downloadjs": "1.4.3","@types/js-yaml": "4.0.5","@types/lodash-es": "4.17.6","@types/node": "18.11.9",+ "@types/normalize-wheel": "^1.0.1","@types/papaparse": "5.3.5","@types/prettier": "2.7.1","@types/qs": "6.9.7",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 307c96ff78..7cc87b4173 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -16,11 +16,13 @@ specifiers:'@tanstack/table-core': 8.5.22'@tanstack/vue-table': 8.5.22'@types/canvas-confetti': 1.4.3+ '@types/dagre': ^0.7.48'@types/dompurify': 2.3.4'@types/downloadjs': 1.4.3'@types/js-yaml': 4.0.5'@types/lodash-es': 4.17.6'@types/node': 18.11.9+ '@types/normalize-wheel': ^1.0.1'@types/papaparse': 5.3.5'@types/prettier': 2.7.1'@types/qs': 6.9.7@@ -40,9 +42,11 @@ specifiers:axios: 1.1.3bootstrap: 5.2.2canvas-confetti: 1.6.0+ dagre: ^0.8.5dayjs: 1.11.6dompurify: 2.4.0downloadjs: 1.4.7+ emittery: ^1.0.1escape-string-regexp: 5.0.0eslint: 8.26.0eslint-config-prettier: 8.5.0@@ -58,6 +62,7 @@ specifiers:monaco-languageclient: 4.0.1naive-ui: 2.33.5node-sql-parser: 4.5.1+ normalize-wheel: ^1.0.1papaparse: 5.3.2pev2: 1.5.0pinia: 2.0.23@@ -107,9 +112,11 @@ dependencies:axios: 1.1.3bootstrap: 5.2.2_@[email protected]canvas-confetti: 1.6.0+ dagre: 0.8.5dayjs: 1.11.6dompurify: 2.4.0downloadjs: 1.4.7+ emittery: 1.0.1escape-string-regexp: 5.0.0highlight.js: 11.6.0inter-ui: 3.19.3@@ -119,6 +126,7 @@ dependencies:monaco-languageclient: 4.0.1_g4fp2q2jxj3u35wmxezeq2vo6ynaive-ui: [email protected]node-sql-parser: 4.5.1+ normalize-wheel: 1.0.1papaparse: 5.3.2pev2: 1.5.0_47tpum6wtjtozdoo6t4hr5iro4pinia: 2.0.23_l7r24p6nevbtlimqmqcwa3ouhu@@ -151,11 +159,13 @@ devDependencies:'@tailwindcss/line-clamp': [email protected]'@tailwindcss/typography': [email protected]'@types/canvas-confetti': 1.4.3+ '@types/dagre': 0.7.48'@types/dompurify': 2.3.4'@types/downloadjs': 1.4.3'@types/js-yaml': 4.0.5'@types/lodash-es': 4.17.6'@types/node': 18.11.9+ '@types/normalize-wheel': 1.0.1'@types/papaparse': 5.3.5'@types/prettier': 2.7.1'@types/qs': 6.9.7@@ -875,6 +885,10 @@ packages:'@types/d3-zoom': 3.0.1dev: false+ /@types/dagre/0.7.48:+ resolution: {integrity: sha512-rF3yXSwHIrDxEkN6edCE4TXknb5YSEpiXfLaspw1I08grC49ZFuAVGOQCmZGIuLUGoFgcqGlUFBL/XrpgYpQgw==}+ dev: true+/@types/dompurify/2.3.4:resolution: {integrity: sha512-EXzDatIb5EspL2eb/xPGmaC8pePcTHrkDCONjeisusLFrVfl38Pjea/R0YJGu3k9ZQadSvMqW0WXPI2hEo2Ajg==}dependencies:@@ -940,6 +954,10 @@ packages:resolution: {integrity: sha512-CRpX21/kGdzjOpFsZSkcrXMGIBWMGNIHXXBVFSH+ggkftxg+XYP20TESbh+zFvFj3EQOl5byk0HTRn1IL6hbqg==}dev: true+ /@types/normalize-wheel/1.0.1:+ resolution: {integrity: sha512-3YBVyWfiwIGDcQY+2ZeT3LxyApYnV3PrysjIKeNkQtT9Q9eq2mcPPcqSCYR4v/FhYJ9xtZNhXMKNxCn6ukLsXQ==}+ dev: true+/@types/object-hash/1.3.4:resolution: {integrity: sha512-xFdpkAkikBgqBdG9vIlsqffDV8GpvnPEzs0IUtr1v3BEB97ijsFQ4RXVbUZwjFThhB4MDSTUfvmxUD5PGx0wXA==}dev: true@@ -1927,6 +1945,13 @@ packages:d3-zoom: 3.0.0dev: false+ /dagre/0.8.5:+ resolution: {integrity: sha512-/aTqmnRta7x7MCCpExk7HQL2O4owCT2h8NT//9I1OQ9vt29Pa0BzSAkR5lwFUcQ7491yVi/3CXU9jQ5o0Mn2Sw==}+ dependencies:+ graphlib: 2.1.8+ lodash: 4.17.21+ dev: false+/dataloader/1.4.0:resolution: {integrity: sha512-68s5jYdlvasItOJnCuI2Q9s4q98g0pCyL3HrcKJu8KNugUl8ahgmZYg38ysLTgQjjXX3H8CJLkAvWrclWfcalw==}dev: true@@ -2069,6 +2094,11 @@ packages:resolution: {integrity: sha512-M8WEXFuKXMYMVr45fo8mq0wUrrJHheiKZf6BArTKk9ZBYCKJEOU5H8cdWgDT+qCVZf7Na4lVUaZsA+h6uA9+PA==}dev: true+ /emittery/1.0.1:+ resolution: {integrity: sha512-2ID6FdrMD9KDLldGesP6317G78K7km/kMcwItRtVFva7I/cSEOIaLpewaUb+YLXVwdAp3Ctfxh/V5zIl1sj7dQ==}+ engines: {node: '>=14.16'}+ dev: false+/esbuild-android-64/0.15.13:resolution: {integrity: sha512-yRorukXBlokwTip+Sy4MYskLhJsO0Kn0/Fj43s1krVblfwP+hMD37a4Wmg139GEsMLl+vh8WXp2mq/cTA9J97g==}engines: {node: '>=12'}@@ -2676,6 +2706,12 @@ packages:resolution: {integrity: sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==}dev: true+ /graphlib/2.1.8:+ resolution: {integrity: sha512-jcLLfkpoVGmH7/InMC/1hIvOPSUh38oJtGhvrOFGzioE1DZ+0YW16RgmOJhHiuWTvGiJQ9Z1Ik43JvkRPRvE+A==}+ dependencies:+ lodash: 4.17.21+ dev: false+/has-flag/4.0.0:resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}engines: {node: '>=8'}@@ -3094,6 +3130,10 @@ packages:engines: {node: '>=0.10.0'}dev: true+ /normalize-wheel/1.0.1:+ resolution: {integrity: sha512-1OnlAPZ3zgrk8B91HyRj+eVv+kS5u+Z0SCsak6Xil/kmgEia50ga7zfkumayonZrImffAxPU/5WcyGhzetHNPA==}+ dev: false+/npm-run-path/4.0.1:resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==}engines: {node: '>=8'}diff --git a/frontend/src/components/SchemaDiagram/Canvas/Canvas.vue b/frontend/src/components/SchemaDiagram/Canvas/Canvas.vuenew file mode 100644index 0000000000..f86789825e--- /dev/null+++ b/frontend/src/components/SchemaDiagram/Canvas/Canvas.vue@@ -0,0 +1,96 @@+<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" />++ <ZoomButton+ :min="ZOOM_RANGE.min"+ :max="ZOOM_RANGE.max"+ @zoom-in="handleZoom(0.1)"+ @zoom-out="handleZoom(-0.1)"+ />+ </div>++ <slot />+ </div>+</template>++<script lang="ts" setup>+import { ref } from "vue";+import { useEventListener } from "@vueuse/core";+import normalizeWheel from "normalize-wheel";++import { Position } from "../types";+import { useDraggable, minmax, useSchemaDiagramContext } from "../common";+import ZoomButton from "./ZoomButton.vue";++const canvas = ref<Element>();+const desktop = ref<Element>();++const { zoom, position } = useSchemaDiagramContext();++const zoomCenter = ref<Position>({ x: 0.5, y: 0.5 });+const ZOOM_RANGE = {+ max: 2, // 200%+ min: 0.05, // 5%+};++const handleZoom = (delta: number, center: Position = { 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;+};++useDraggable(canvas, {+ exact: false,+ onPan: handlePan,+});++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+);+</script>diff --git a/frontend/src/components/SchemaDiagram/Canvas/ZoomButton.vue b/frontend/src/components/SchemaDiagram/Canvas/ZoomButton.vuenew file mode 100644index 0000000000..48bae5833c--- /dev/null+++ b/frontend/src/components/SchemaDiagram/Canvas/ZoomButton.vue@@ -0,0 +1,38 @@+<template>+ <NButtonGroup size="tiny" class="bg-white rounded">+ <NButton :disabled="zoom <= min" @click="$emit('zoom-out')">+ <template #icon>+ <heroicons-outline: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>+ <heroicons-outline:plus />+ </template>+ </NButton>+ </NButtonGroup>+</template>++<script lang="ts" setup>+import { computed } from "vue";+import { NButtonGroup, NButton } from "naive-ui";++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/index.ts b/frontend/src/components/SchemaDiagram/Canvas/index.tsnew file mode 100644index 0000000000..30d0ef20e6--- /dev/null+++ b/frontend/src/components/SchemaDiagram/Canvas/index.ts@@ -0,0 +1,5 @@+import Canvas from "./Canvas.vue";++export { Canvas };++export default Canvas;diff --git a/frontend/src/components/SchemaDiagram/ER/TableNode.vue b/frontend/src/components/SchemaDiagram/ER/TableNode.vuenew file mode 100644index 0000000000..24798f0189--- /dev/null+++ b/frontend/src/components/SchemaDiagram/ER/TableNode.vue@@ -0,0 +1,89 @@+<template>+ <div+ class="absolute rounded-md shadow-lg border-b border-gray-200 bg-white w-[14rem] divide-y z-[10]"+ bb-node-type="table"+ :bb-node-id="idOfTable(table)"+ :style="{+ left: `${position.x}px`,+ top: `${position.y}px`,+ }"+ >+ <h3+ class="font-medium leading-6 text-white text-center truncate px-2 py-2 rounded-t-md"+ :style="{+ 'background-color': tableColor,+ }"+ >+ {{ table.name }}+ </h3>+ <table class="w-full text-sm table-fixed">+ <tr+ v-for="(column, i) in table.columns"+ :key="i"+ :bb-column-name="column.name"+ >+ <td class="w-5 py-1.5">+ <!-- TODO: remove this -->+ <heroicons-outline:key+ v-if="column.name === 'emp_no' || column.name === 'dept_no'"+ class="w-3 h-3 mx-auto text-amber-500"+ />+ </td>+ <td class="w-auto text-xs py-1.5">+ <div class="whitespace-pre-wrap break-words">+ {{ column.name }}+ </div>+ </td>+ <td class="w-20 text-xs text-gray-400 py-1.5">+ <div class="flex items-center w-full overflow-hidden pr-2">+ <EllipsisText class="w-full text-right">+ {{ column.type }}+ </EllipsisText>+ </div>+ </td>+ </tr>+ </table>+ </div>+</template>++<script lang="ts" setup>+import { computed } from "vue";++import { hashCode } from "@/bbkit/BBUtil";+import { TableMetadata } from "@/types/proto/database";+import { useSchemaDiagramContext } from "../common";++const props = withDefaults(+ defineProps<{+ table: TableMetadata;+ }>(),+ {}+);+const { idOfTable, rectOfTable } = 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 position = computed(() => rectOfTable(props.table));+</script>diff --git a/frontend/src/components/SchemaDiagram/ER/index.ts b/frontend/src/components/SchemaDiagram/ER/index.tsnew file mode 100644index 0000000000..9aacf6f7eb--- /dev/null+++ b/frontend/src/components/SchemaDiagram/ER/index.ts@@ -0,0 +1,4 @@+import TableNode from "./TableNode.vue";++export { TableNode };+export * from "./libs/autoLayout";diff --git a/frontend/src/components/SchemaDiagram/ER/libs/autoLayout.ts b/frontend/src/components/SchemaDiagram/ER/libs/autoLayout.tsnew file mode 100644index 0000000000..2f48af7090--- /dev/null+++ b/frontend/src/components/SchemaDiagram/ER/libs/autoLayout.ts@@ -0,0 +1,42 @@+import dagre from "dagre";+import { Rect, Size } from "../../types";++export type GraphNodeItem = {+ id: string;+ size: Size;+};++export type GraphEdgeItem = {+ from: string;+ to: string;+};++export const autoLayout = (+ nodeList: GraphNodeItem[],+ edgeList: GraphEdgeItem[]+) => {+ const g = new dagre.graphlib.Graph();+ g.setGraph({+ rankdir: "TD",+ nodesep: 100, // x gap+ ranksep: 100, // y gap+ });+ g.setDefaultEdgeLabel(() => ({}));++ nodeList.forEach(({ id, size }) => {+ g.setNode(id, {+ ...size,+ });+ });+ edgeList.forEach(({ from, to }) => {+ g.setEdge({ v: from, w: to });+ });+ dagre.layout(g);++ const rectsByTableId = new Map<string, Rect>();+ g.nodes().forEach((id) => {+ const node = g.node(id);+ rectsByTableId.set(id, node);+ });+ return rectsByTableId;+};diff --git a/frontend/src/components/SchemaDiagram/SchemaDiagram.vue b/frontend/src/components/SchemaDiagram/SchemaDiagram.vuenew file mode 100644index 0000000000..388d148bee--- /dev/null+++ b/frontend/src/components/SchemaDiagram/SchemaDiagram.vue@@ -0,0 +1,102 @@+<template>+ <Canvas>+ <template #desktop>+ <TableNode v-for="(table, i) in tableList" :key="i" :table="table" />+ </template>+ </Canvas>+</template>++<script lang="ts" setup>+import { computed, nextTick, onMounted, ref } from "vue";+import { uniqueId } from "lodash-es";+import Emittery from "emittery";++import { Database } from "@/types";+import { TableMetadata } from "@/types/proto/database";+import { Position, Rect, Size, SchemaDiagramContext } from "./types";+import Canvas from "./Canvas";+import { TableNode, autoLayout } from "./ER";+import { provideSchemaDiagramContext } from "./common";++const props = withDefaults(+ defineProps<{+ database: Database;+ tableList: TableMetadata[];+ }>(),+ {}+);++const zoom = ref(1);+const position = ref<Position>({ x: 0, y: 0 });++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 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 = () => {+ nextTick(() => {+ const nodeList = props.tableList+ .map((table) => {+ const id = idOfTable(table);+ const elem = document.querySelector(`[bb-node-id="${id}"]`)!;+ return {+ table,+ id,+ elem,+ };+ })+ .filter((item) => !!item.elem)+ .map((item) => {+ const size: Size = {+ width: item.elem.clientWidth,+ height: item.elem.clientHeight,+ };+ return {+ ...item,+ size,+ };+ });+ const layout = autoLayout(nodeList, []);+ for (const [id, rect] of layout) {+ rectsByTableId.value.set(id, rect);+ }+ });++ render();+};++events.on("layout", layout);++provideSchemaDiagramContext({+ tableList: computed(() => props.tableList),+ zoom,+ position,+ idOfTable,+ rectOfTable,+ render,+ layout,+ events,+});++// autoLayout at the first time the diagram is mounted.+onMounted(layout);+</script>diff --git a/frontend/src/components/SchemaDiagram/common/context.ts b/frontend/src/components/SchemaDiagram/common/context.tsnew file mode 100644index 0000000000..35bd0cac98--- /dev/null+++ b/frontend/src/components/SchemaDiagram/common/context.ts@@ -0,0 +1,14 @@+import { inject, InjectionKey, provide } from "vue";+import { 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);+};diff --git a/frontend/src/components/SchemaDiagram/common/index.ts b/frontend/src/components/SchemaDiagram/common/index.tsnew file mode 100644index 0000000000..c45ebc8a7f--- /dev/null+++ b/frontend/src/components/SchemaDiagram/common/index.ts@@ -0,0 +1,3 @@+export * from "./context";+export * from "./useDraggable";+export * from "./utils";diff --git a/frontend/src/components/SchemaDiagram/common/useDraggable.ts b/frontend/src/components/SchemaDiagram/common/useDraggable.tsnew file mode 100644index 0000000000..1cc0de2c31--- /dev/null+++ b/frontend/src/components/SchemaDiagram/common/useDraggable.ts@@ -0,0 +1,54 @@+import { ref, unref } from "vue";+import { MaybeRef, useEventListener } from "@vueuse/core";++import { Position } from "../types";++export type DraggableOptions = {+ exact?: boolean;+ onPan?: (dx: number, dy: number) => void;+ capture?: boolean;+};++export const useDraggable = (+ target: MaybeRef<Element | undefined>,+ options: DraggableOptions+) => {+ const startPointerPosition = ref<Position>();+ const lastPointerPosition = ref<Position>();++ 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();+ };+ 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();+ };++ 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/common/utils.ts b/frontend/src/components/SchemaDiagram/common/utils.tsnew file mode 100644index 0000000000..35b27be1fe--- /dev/null+++ b/frontend/src/components/SchemaDiagram/common/utils.ts@@ -0,0 +1,5 @@+export const minmax = (value: number, min: number, max: number) => {+ if (value < min) return min;+ if (value > max) return max;+ return value;+};diff --git a/frontend/src/components/SchemaDiagram/index.ts b/frontend/src/components/SchemaDiagram/index.tsnew file mode 100644index 0000000000..921a4cebc5--- /dev/null+++ b/frontend/src/components/SchemaDiagram/index.ts@@ -0,0 +1,5 @@+import SchemaDiagram from "./SchemaDiagram.vue";++export { SchemaDiagram };++export default SchemaDiagram;diff --git a/frontend/src/components/SchemaDiagram/types/context.ts b/frontend/src/components/SchemaDiagram/types/context.tsnew file mode 100644index 0000000000..b30ee5868d--- /dev/null+++ b/frontend/src/components/SchemaDiagram/types/context.ts@@ -0,0 +1,31 @@+import { Ref } from "vue";+import type Emittery from "emittery";+import { TableMetadata } from "@/types/proto/database";++import { Position, Rect } from "./geometry";++// 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+ tableList: Ref<TableMetadata[]>;++ // States+ zoom: Ref<number>;+ position: Ref<Position>;++ // 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;++ // Events+ events: Emittery<{+ render: undefined;+ layout: undefined;+ }>;+};diff --git a/frontend/src/components/SchemaDiagram/types/geometry.ts b/frontend/src/components/SchemaDiagram/types/geometry.tsnew file mode 100644index 0000000000..8edf75aa6f--- /dev/null+++ b/frontend/src/components/SchemaDiagram/types/geometry.ts@@ -0,0 +1,13 @@+export type Size = {+ width: number;+ height: number;+};++export type Position = {+ x: number;+ y: number;+};++export type Rect = Position & Size;++export type Path = Position[];diff --git a/frontend/src/components/SchemaDiagram/types/index.ts b/frontend/src/components/SchemaDiagram/types/index.tsnew file mode 100644index 0000000000..63ed988d65--- /dev/null+++ b/frontend/src/components/SchemaDiagram/types/index.ts@@ -0,0 +1,2 @@+export * from "./context";+export * from "./geometry";diff --git a/frontend/src/components/SchemaEditor/Panels/DatabaseEditor.vue b/frontend/src/components/SchemaEditor/Panels/DatabaseEditor.vueindex f49def1952..eba9a1e949 100644--- a/frontend/src/components/SchemaEditor/Panels/DatabaseEditor.vue+++ b/frontend/src/components/SchemaEditor/Panels/DatabaseEditor.vue@@ -1,5 +1,5 @@<template>- <div class="grid auto-rows-auto w-full h-full overflow-y-auto">+ <div class="flex flex-col w-full h-full overflow-y-auto"><divclass="pt-3 pl-1 w-full flex justify-start items-center border-b border-b-gray-300">@@ -13,22 +13,23 @@>{{ $t("schema-editor.table-list") }}</span><span- class="hidden -mb-px px-3 leading-9 rounded-t-md text-sm text-gray-500 border border-b-0 border-transparent cursor-pointer select-none"+ class="-mb-px px-3 leading-9 rounded-t-md text-sm text-gray-500 border border-b-0 border-transparent cursor-pointer select-none":class="- state.selectedTab === 'er-diagram' &&+ state.selectedTab === 'raw-sql' &&'bg-white border-gray-300 text-gray-800'"- @click="handleChangeTab('er-diagram')"- >ER Diagram</span+ @click="handleChangeTab('raw-sql')"+ >{{ $t("schema-editor.raw-sql") }}</span><span+ v-if="isDev"class="-mb-px px-3 leading-9 rounded-t-md text-sm text-gray-500 border border-b-0 border-transparent cursor-pointer select-none":class="- state.selectedTab === 'raw-sql' &&+ state.selectedTab === 'schema-diagram' &&'bg-white border-gray-300 text-gray-800'"- @click="handleChangeTab('raw-sql')"- >{{ $t("schema-editor.raw-sql") }}</span+ @click="handleChangeTab('schema-diagram')"+ >{{ $t("schema-diagram.self") }}</span></div>@@ -117,9 +118,6 @@</div></div></template>- <template v-else-if="state.selectedTab === 'er-diagram'">- <!-- TODO: ER diagram placeholder -->- </template><divv-else-if="state.selectedTab === 'raw-sql'"class="w-full h-full overflow-y-auto"@@ -142,6 +140,13 @@</div></template></div>+ <template v-else-if="state.selectedTab === 'schema-diagram'">+ <SchemaDiagram+ :key="currentTab.databaseId"+ :database="database"+ :table-list="dbSchemaStore.getTableListByDatabaseId(database.id)"+ />+ </template></div><TableNameModal@@ -158,6 +163,7 @@ import { computed, reactive, watch } from "vue";import { useI18n } from "vue-i18n";import {generateUniqueTabId,+ useDBSchemaStore,useNotificationStore,useSchemaEditorStore,} from "@/store";@@ -167,8 +173,9 @@ import { bytesToString } from "@/utils";import HighlightCodeBlock from "@/components/HighlightCodeBlock";import TableNameModal from "../Modals/TableNameModal.vue";import { diffTableList } from "@/utils/schemaEditor/diffTable";+import SchemaDiagram from "@/components/SchemaDiagram";-type TabType = "table-list" | "er-diagram" | "raw-sql";+type TabType = "table-list" | "schema-diagram" | "raw-sql";interface LocalState {selectedTab: TabType;@@ -182,6 +189,7 @@ interface LocalState {const { t } = useI18n();const editorStore = useSchemaEditorStore();+const dbSchemaStore = useDBSchemaStore();const notificationStore = useNotificationStore();const state = reactive<LocalState>({selectedTab: "table-list",diff --git a/frontend/src/components/SchemaEditor/Panels/TableEditor.vue b/frontend/src/components/SchemaEditor/Panels/TableEditor.vueindex 31b0a2f3f8..8ebcb02304 100644--- a/frontend/src/components/SchemaEditor/Panels/TableEditor.vue+++ b/frontend/src/components/SchemaEditor/Panels/TableEditor.vue@@ -1,5 +1,5 @@<template>- <div class="grid auto-rows-auto w-full h-full overflow-y-auto">+ <div class="flex flex-col w-full h-full overflow-y-auto"><divclass="pt-3 pl-1 w-full flex justify-start items-center border-b border-b-gray-300">diff --git a/frontend/src/components/SchemaEditor/SchemaEditor.vue b/frontend/src/components/SchemaEditor/SchemaEditor.vueindex c3cd1b8eed..87a0e9ae8a 100644--- a/frontend/src/components/SchemaEditor/SchemaEditor.vue+++ b/frontend/src/components/SchemaEditor/SchemaEditor.vue@@ -12,7 +12,7 @@<TabsContainer /><div:key="currentTab.id"- class="w-full h-auto relative overflow-y-auto"+ class="w-full h-full relative overflow-y-auto"><DatabaseEditorv-if="currentTab.type === SchemaEditorTabType.TabForDatabase"diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex f94359918c..0eb57e771a 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1736,5 +1736,8 @@"keep-going-with-bytebase": "Keep going with Bytebase!"}}+ },+ "schema-diagram": {+ "self": "Schema Diagram"}}diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 6516c7410a..a9c16af5ac 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1737,5 +1737,8 @@"keep-going-with-bytebase": "继续使用 Bytebase!"}}+ },+ "schema-diagram": {+ "self": "Schema 展示图"}}diff --git a/frontend/src/views/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail.vueindex db137f53cf..1e5da33db1 100644--- a/frontend/src/views/DatabaseDetail.vue+++ b/frontend/src/views/DatabaseDetail.vue@@ -107,6 +107,14 @@<span class="mr-1">{{ $t("sql-editor.self") }}</span><heroicons-solid:terminal class="w-5 h-5" /></dd>+ <dd+ v-if="isDev"+ class="flex items-center text-sm md:mr-4 textlabel cursor-pointer hover:text-accent"+ @click.prevent="state.showSchemaDiagram = true"+ >+ <span class="mr-1">{{ $t("schema-diagram.self") }}</span>+ <heroicons-solid:table-cells class="w-4 h-4" />+ </dd><DatabaseLabelProps:label-list="database.labels":database="database"@@ -293,6 +301,19 @@<GhostDialog ref="ghostDialog" />+ <BBModal+ v-if="state.showSchemaDiagram"+ :title="$t('schema-diagram.self')"+ @close="state.showSchemaDiagram = false"+ >+ <div class="w-[80vw] h-[70vh]">+ <SchemaDiagram+ :database="database"+ :table-list="dbSchemaStore.getTableListByDatabaseId(database.id)"+ />+ </div>+ </BBModal>+<SchemaEditorModalv-if="state.showSchemaEditorModal":database-id-list="[database.id]"@@ -336,10 +357,12 @@ import {import { BBTabFilterItem } from "@/bbkit/types";import { useI18n } from "vue-i18n";import { GhostDialog } from "@/components/AlterSchemaPrepForm";+import SchemaDiagram from "@/components/SchemaDiagram";import {pushNotification,useCurrentUser,useDatabaseStore,+ useDBSchemaStore,usePolicyByDatabaseAndType,useRepositoryStore,useSQLStore,@@ -362,6 +385,7 @@ interface LocalState {editingProjectId: ProjectId;selectedIndex: number;syncingSchema: boolean;+ showSchemaDiagram: boolean;}const props = defineProps({@@ -373,6 +397,7 @@ const props = defineProps({const databaseStore = useDatabaseStore();const repositoryStore = useRepositoryStore();+const dbSchemaStore = useDBSchemaStore();const sqlStore = useSQLStore();const router = useRouter();const { t } = useI18n();@@ -391,6 +416,7 @@ const state = reactive<LocalState>({editingProjectId: UNKNOWN_ID,selectedIndex: OVERVIEW_TAB,syncingSchema: false,+ showSchemaDiagram: false,});const currentUser = useCurrentUser();