feat(diagram): enhance ER diagram editing and exports
This commit is contained in:
1 parent
9fda1d690a
commit
212cf1da7e
92 files changed
+12231
-943
No files matched your search
@@ -0,0 +1,194 @@
|
||||
import type { CustomDiagramRelationship, DiagramPosition, DiagramRelationship, DiagramTable } from "@/lib/diagram/erDiagram";
|
||||
import type { DiagramLayer } from "@/types/diagram";
|
||||
|
||||
export type DiagramExportFormat = "svg" | "png" | "json" | "dbml" | "mermaid";
|
||||
|
||||
export interface DiagramJsonSnapshot {
|
||||
meta: {
|
||||
connectionName: string;
|
||||
database: string;
|
||||
schema: string;
|
||||
mode: "table" | "engineering";
|
||||
exportedAt: string;
|
||||
};
|
||||
tables: Array<{
|
||||
name: string;
|
||||
columns: Array<{
|
||||
name: string;
|
||||
dataType: string;
|
||||
nullable: boolean;
|
||||
primaryKey: boolean;
|
||||
}>;
|
||||
foreignKeys: Array<{
|
||||
name: string;
|
||||
column: string;
|
||||
refTable: string;
|
||||
refColumn: string;
|
||||
}>;
|
||||
}>;
|
||||
relationships: DiagramRelationship[];
|
||||
positions: Record<string, DiagramPosition>;
|
||||
layers: DiagramLayer[];
|
||||
customRelationships: CustomDiagramRelationship[];
|
||||
matchConfirms: string[];
|
||||
matchIgnores: string[];
|
||||
}
|
||||
|
||||
function fileToken(value: string): string {
|
||||
return value
|
||||
.trim()
|
||||
.replace(/[^\p{L}\p{N}._-]+/gu, "-")
|
||||
.replace(/-+/g, "-")
|
||||
.replace(/^-|-$/g, "");
|
||||
}
|
||||
|
||||
function quoteIdent(name: string): string {
|
||||
if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) return name;
|
||||
return `"${name.replace(/"/g, '\\"')}"`;
|
||||
}
|
||||
|
||||
function mermaidIdent(name: string): string {
|
||||
const cleaned = name.replace(/[^A-Za-z0-9_]/g, "_");
|
||||
return cleaned || "entity";
|
||||
}
|
||||
|
||||
function dbmlType(dataType: string): string {
|
||||
const t = dataType.trim() || "varchar";
|
||||
// Keep parentheses content; quote if spaces / special chars
|
||||
if (/^[A-Za-z_][A-Za-z0-9_]*(?:\([^)]*\))?$/.test(t)) return t;
|
||||
return `"${t.replace(/"/g, '\\"')}"`;
|
||||
}
|
||||
|
||||
function dbmlRefOp(sourceCardinality: "1" | "N", targetCardinality: "1" | "N"): string {
|
||||
if (sourceCardinality === "1" && targetCardinality === "1") return "-";
|
||||
if (sourceCardinality === "N" && targetCardinality === "N") return "<>";
|
||||
if (sourceCardinality === "N" && targetCardinality === "1") return ">";
|
||||
return "<";
|
||||
}
|
||||
|
||||
function mermaidCardinality(sourceCardinality: "1" | "N", targetCardinality: "1" | "N"): string {
|
||||
// Mermaid: ENTITY1 ||--o{ ENTITY2 : "label"
|
||||
if (sourceCardinality === "1" && targetCardinality === "1") return "||--||";
|
||||
if (sourceCardinality === "1" && targetCardinality === "N") return "||--o{";
|
||||
if (sourceCardinality === "N" && targetCardinality === "1") return "}o--||";
|
||||
return "}o--o{";
|
||||
}
|
||||
|
||||
export function diagramExportFileName(connectionName: string, databaseName: string, mode: "table" | "engineering", format: DiagramExportFormat): string {
|
||||
const context = [connectionName, databaseName].map(fileToken).filter(Boolean);
|
||||
const modeSuffix = mode === "engineering" ? "engineering-er" : "table-structure";
|
||||
const ext = format === "svg" ? "svg" : format === "png" ? "png" : format === "json" ? "json" : format === "dbml" ? "dbml" : "mmd";
|
||||
const kind = format === "svg" || format === "png" ? modeSuffix : format === "json" ? "diagram" : format === "dbml" ? "schema" : "er";
|
||||
return ["dbx", ...(context.length > 0 ? context : ["diagram"]), kind].join("-") + `.${ext}`;
|
||||
}
|
||||
|
||||
export function buildDiagramJson(snapshot: DiagramJsonSnapshot): string {
|
||||
return `${JSON.stringify(snapshot, null, 2)}\n`;
|
||||
}
|
||||
|
||||
export function buildDiagramDbml(tables: DiagramTable[], relationships: DiagramRelationship[]): string {
|
||||
const lines: string[] = ["// Generated by DBX", ""];
|
||||
|
||||
for (const table of tables) {
|
||||
lines.push(`Table ${quoteIdent(table.name)} {`);
|
||||
for (const column of table.columns) {
|
||||
const attrs: string[] = [];
|
||||
if (column.is_primary_key) attrs.push("pk");
|
||||
if (!column.is_nullable) attrs.push("not null");
|
||||
const attrSuffix = attrs.length > 0 ? ` [${attrs.join(", ")}]` : "";
|
||||
lines.push(` ${quoteIdent(column.name)} ${dbmlType(column.data_type)}${attrSuffix}`);
|
||||
}
|
||||
lines.push("}", "");
|
||||
}
|
||||
|
||||
for (const rel of relationships) {
|
||||
const op = dbmlRefOp(rel.sourceCardinality, rel.targetCardinality);
|
||||
lines.push(`Ref: ${quoteIdent(rel.sourceTable)}.${quoteIdent(rel.sourceColumn)} ${op} ${quoteIdent(rel.targetTable)}.${quoteIdent(rel.targetColumn)}`);
|
||||
}
|
||||
|
||||
if (relationships.length > 0) lines.push("");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export function buildDiagramMermaid(tables: DiagramTable[], relationships: DiagramRelationship[]): string {
|
||||
const lines: string[] = ["erDiagram"];
|
||||
|
||||
for (const table of tables) {
|
||||
const entity = mermaidIdent(table.name);
|
||||
lines.push(` ${entity} {`);
|
||||
for (const column of table.columns) {
|
||||
const typeToken = (column.data_type || "unknown").replace(/\s+/g, "_").replace(/[^A-Za-z0-9_]/g, "") || "unknown";
|
||||
const key = column.is_primary_key ? " PK" : "";
|
||||
lines.push(` ${typeToken} ${mermaidIdent(column.name)}${key}`);
|
||||
}
|
||||
lines.push(" }");
|
||||
}
|
||||
|
||||
for (const rel of relationships) {
|
||||
const left = mermaidIdent(rel.sourceTable);
|
||||
const right = mermaidIdent(rel.targetTable);
|
||||
const card = mermaidCardinality(rel.sourceCardinality, rel.targetCardinality);
|
||||
const label = `${rel.sourceColumn} -> ${rel.targetColumn}`.replace(/"/g, "'");
|
||||
lines.push(` ${left} ${card} ${right} : "${label}"`);
|
||||
}
|
||||
|
||||
lines.push("");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export function svgToPngBlob(svg: string, scale = 2): Promise<Blob> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
try {
|
||||
const width = Math.max(1, Math.ceil(img.naturalWidth * scale));
|
||||
const height = Math.max(1, Math.ceil(img.naturalHeight * scale));
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) {
|
||||
URL.revokeObjectURL(url);
|
||||
reject(new Error("Canvas unsupported"));
|
||||
return;
|
||||
}
|
||||
ctx.fillStyle = "#fafafa";
|
||||
ctx.fillRect(0, 0, width, height);
|
||||
ctx.drawImage(img, 0, 0, width, height);
|
||||
URL.revokeObjectURL(url);
|
||||
canvas.toBlob((png) => {
|
||||
if (!png) {
|
||||
reject(new Error("PNG encode failed"));
|
||||
return;
|
||||
}
|
||||
resolve(png);
|
||||
}, "image/png");
|
||||
} catch (err) {
|
||||
URL.revokeObjectURL(url);
|
||||
reject(err);
|
||||
}
|
||||
};
|
||||
img.onerror = () => {
|
||||
URL.revokeObjectURL(url);
|
||||
reject(new Error("Failed to load SVG for PNG export"));
|
||||
};
|
||||
img.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
export function diagramExportDialogFilter(format: DiagramExportFormat): { name: string; extensions: string[] } {
|
||||
switch (format) {
|
||||
case "svg":
|
||||
return { name: "SVG", extensions: ["svg"] };
|
||||
case "png":
|
||||
return { name: "PNG", extensions: ["png"] };
|
||||
case "json":
|
||||
return { name: "JSON", extensions: ["json"] };
|
||||
case "dbml":
|
||||
return { name: "DBML", extensions: ["dbml"] };
|
||||
case "mermaid":
|
||||
return { name: "Mermaid", extensions: ["mmd", "md"] };
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,51 @@
|
||||
import type { EngineeringDiagram, EngineeringEntityNode } from "@/lib/diagram/engineeringDiagram";
|
||||
import type { DiagramPosition, DiagramRelationship, DiagramTable } from "@/lib/diagram/erDiagram";
|
||||
import { pickHandles } from "@/lib/diagram/vue-flow-adapter";
|
||||
import { pointAlongPolyline, pointsToSvgPath, type Point } from "@/lib/diagram/edge-obstacle-router";
|
||||
import { CARD_BOTTOM_PADDING, CARD_HEADER_HEIGHT, CARD_WIDTH, COLUMN_ROW_HEIGHT, MARGIN } from "@/lib/diagram/diagram-constants";
|
||||
|
||||
type DiagramSvgMode = "table" | "engineering";
|
||||
const SOURCE_CARDINALITY_T = 0.18;
|
||||
const TARGET_CARDINALITY_T = 0.82;
|
||||
|
||||
interface DiagramCanvas {
|
||||
width: number;
|
||||
height: number;
|
||||
/** viewBox origin; defaults to 0 when omitted (engineering mode already normalizes to ~0). */
|
||||
originX?: number;
|
||||
originY?: number;
|
||||
}
|
||||
|
||||
export interface TableDiagramRelationshipLayout {
|
||||
path: string;
|
||||
routePoints: DiagramPosition[];
|
||||
sourceCardinality: DiagramPosition;
|
||||
targetCardinality: DiagramPosition;
|
||||
export interface DiagramSvgLayer {
|
||||
id: string;
|
||||
name: string;
|
||||
color: string;
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface TableDiagramSvgOptions {
|
||||
tables: DiagramTable[];
|
||||
relationships: DiagramRelationship[];
|
||||
positions: Record<string, DiagramPosition>;
|
||||
relationshipLayouts: Record<string, TableDiagramRelationshipLayout>;
|
||||
relationshipPaths: Record<string, string>;
|
||||
/** Polyline points for endpoint cardinality badges (aligned with relationshipPaths). */
|
||||
relationshipPolylines?: Record<string, Point[]>;
|
||||
canvas: DiagramCanvas;
|
||||
cardWidth: number;
|
||||
cardHeaderHeight: number;
|
||||
columnRowHeight: number;
|
||||
maxVisibleColumns: number;
|
||||
cardBottomPadding?: number;
|
||||
moreColumnsLabel?: (count: number) => string;
|
||||
layers?: DiagramSvgLayer[];
|
||||
}
|
||||
|
||||
type CardHeightMetrics = {
|
||||
cardHeaderHeight: number;
|
||||
columnRowHeight: number;
|
||||
cardBottomPadding?: number;
|
||||
};
|
||||
|
||||
function escapeXml(value: string | number): string {
|
||||
return String(value).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
||||
}
|
||||
@@ -37,17 +54,11 @@ function svgNumber(value: number): string {
|
||||
return Number.isInteger(value) ? String(value) : value.toFixed(2).replace(/\.?0+$/, "");
|
||||
}
|
||||
|
||||
interface SvgViewport {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
function svgHeader(canvas: DiagramCanvas, viewport: SvgViewport = { x: 0, y: 0, width: canvas.width, height: canvas.height }): string {
|
||||
function svgHeader(canvas: DiagramCanvas): string {
|
||||
// Always viewBox 0 0 — callers that use non-zero canvas.origin must translate content (see buildTableDiagramSvg).
|
||||
return [
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="${svgNumber(viewport.width)}" height="${svgNumber(viewport.height)}" viewBox="${svgNumber(viewport.x)} ${svgNumber(viewport.y)} ${svgNumber(viewport.width)} ${svgNumber(viewport.height)}">`,
|
||||
`<rect x="${svgNumber(viewport.x)}" y="${svgNumber(viewport.y)}" width="${svgNumber(viewport.width)}" height="${svgNumber(viewport.height)}" fill="#fafafa"/>`,
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="${svgNumber(canvas.width)}" height="${svgNumber(canvas.height)}" viewBox="0 0 ${svgNumber(canvas.width)} ${svgNumber(canvas.height)}">`,
|
||||
`<rect x="0" y="0" width="${svgNumber(canvas.width)}" height="${svgNumber(canvas.height)}" fill="#fafafa"/>`,
|
||||
].join("");
|
||||
}
|
||||
|
||||
@@ -62,101 +73,211 @@ function svgText(
|
||||
anchor?: "start" | "middle" | "end";
|
||||
family?: string;
|
||||
decoration?: string;
|
||||
stroke?: string;
|
||||
strokeWidth?: number;
|
||||
paintOrder?: string;
|
||||
attributes?: Record<string, string>;
|
||||
} = {},
|
||||
): string {
|
||||
const attrs = [`x="${svgNumber(x)}"`, `y="${svgNumber(y)}"`, `fill="${options.fill ?? "#18181b"}"`, `font-size="${options.size ?? 12}"`, `font-family="${options.family ?? "Arial, Helvetica, sans-serif"}"`, 'dominant-baseline="middle"'];
|
||||
if (options.weight) attrs.push(`font-weight="${options.weight}"`);
|
||||
if (options.anchor) attrs.push(`text-anchor="${options.anchor}"`);
|
||||
if (options.decoration) attrs.push(`text-decoration="${options.decoration}"`);
|
||||
if (options.stroke) attrs.push(`stroke="${options.stroke}"`);
|
||||
if (options.strokeWidth) attrs.push(`stroke-width="${svgNumber(options.strokeWidth)}"`);
|
||||
if (options.paintOrder) attrs.push(`paint-order="${options.paintOrder}"`);
|
||||
for (const [name, value] of Object.entries(options.attributes ?? {})) {
|
||||
attrs.push(`${name}="${escapeXml(value)}"`);
|
||||
}
|
||||
return `<text ${attrs.join(" ")}>${escapeXml(label)}</text>`;
|
||||
}
|
||||
|
||||
function tableHeight(table: DiagramTable, options: TableDiagramSvgOptions): number {
|
||||
const visibleCount = Math.min(table.columns.length, options.maxVisibleColumns);
|
||||
const overflowHeight = table.columns.length > options.maxVisibleColumns ? options.columnRowHeight : 0;
|
||||
return options.cardHeaderHeight + visibleCount * options.columnRowHeight + overflowHeight + (options.cardBottomPadding ?? 12);
|
||||
}
|
||||
|
||||
function tableDiagramDefs(): string {
|
||||
return ["<defs>", '<marker id="dbx-diagram-arrow" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto" markerUnits="strokeWidth">', '<path d="M 0 0 L 8 4 L 0 8 z" fill="#2563eb"/>', "</marker>", "</defs>"].join("");
|
||||
/** Shared table card height for SVG canvas / paths / cards. */
|
||||
function svgCardHeight(columnCount: number, metrics: CardHeightMetrics): number {
|
||||
return metrics.cardHeaderHeight + columnCount * metrics.columnRowHeight + (metrics.cardBottomPadding ?? CARD_BOTTOM_PADDING);
|
||||
}
|
||||
|
||||
function isForeignKeyColumn(table: DiagramTable, columnName: string): boolean {
|
||||
return table.foreignKeys.some((fk) => fk.column === columnName);
|
||||
}
|
||||
|
||||
function tableDiagramViewport(options: TableDiagramSvgOptions): SvgViewport {
|
||||
const relationshipPadding = 20;
|
||||
let minX = 0;
|
||||
let minY = 0;
|
||||
let maxX = options.canvas.width;
|
||||
let maxY = options.canvas.height;
|
||||
function handleAnchor(pos: DiagramPosition, handle: string, width: number, height: number): Point {
|
||||
const cx = pos.x + width / 2;
|
||||
const cy = pos.y + height / 2;
|
||||
if (handle.startsWith("right")) return { x: pos.x + width, y: cy };
|
||||
if (handle.startsWith("left")) return { x: pos.x, y: cy };
|
||||
if (handle.startsWith("bottom")) return { x: cx, y: pos.y + height };
|
||||
return { x: cx, y: pos.y };
|
||||
}
|
||||
|
||||
for (const layout of Object.values(options.relationshipLayouts)) {
|
||||
const points = [...layout.routePoints, layout.sourceCardinality, layout.targetCardinality];
|
||||
/** Orthogonal fallback polyline when no ELK/obstacle waypoints are stored. */
|
||||
function orthogonalPointsBetweenTables(sourcePos: DiagramPosition, targetPos: DiagramPosition, sourceHeight: number, targetHeight: number, cardWidth: number): Point[] {
|
||||
const { sourceHandle, targetHandle } = pickHandles(sourcePos, targetPos, sourceHeight, targetHeight, cardWidth);
|
||||
const s = handleAnchor(sourcePos, sourceHandle, cardWidth, sourceHeight);
|
||||
const t = handleAnchor(targetPos, targetHandle.replace(/-target$/, ""), cardWidth, targetHeight);
|
||||
const mid: Point = Math.abs(s.x - t.x) >= Math.abs(s.y - t.y) ? { x: t.x, y: s.y } : { x: s.x, y: t.y };
|
||||
return [s, mid, t];
|
||||
}
|
||||
|
||||
type RelationshipGeometryInput = {
|
||||
relationships: DiagramRelationship[];
|
||||
positions: Record<string, DiagramPosition>;
|
||||
tables: DiagramTable[];
|
||||
waypoints?: Record<string, Point[]>;
|
||||
cardWidth?: number;
|
||||
cardHeaderHeight?: number;
|
||||
columnRowHeight?: number;
|
||||
cardBottomPadding?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Build relationship polylines from live waypoints or table positions.
|
||||
*/
|
||||
export function buildTableRelationshipPolylines(input: RelationshipGeometryInput): Record<string, Point[]> {
|
||||
const cardWidth = input.cardWidth ?? CARD_WIDTH;
|
||||
const metrics: CardHeightMetrics = {
|
||||
cardHeaderHeight: input.cardHeaderHeight ?? CARD_HEADER_HEIGHT,
|
||||
columnRowHeight: input.columnRowHeight ?? COLUMN_ROW_HEIGHT,
|
||||
cardBottomPadding: input.cardBottomPadding ?? CARD_BOTTOM_PADDING,
|
||||
};
|
||||
const heightByName = new Map(input.tables.map((t) => [t.name, svgCardHeight(t.columns.length, metrics)]));
|
||||
const polylines: Record<string, Point[]> = {};
|
||||
|
||||
for (const rel of input.relationships) {
|
||||
const stored = input.waypoints?.[rel.id];
|
||||
if (stored && stored.length >= 2) {
|
||||
polylines[rel.id] = stored.map((p) => ({ ...p }));
|
||||
continue;
|
||||
}
|
||||
const sourcePos = input.positions[rel.sourceTable];
|
||||
const targetPos = input.positions[rel.targetTable];
|
||||
if (!sourcePos || !targetPos) continue;
|
||||
const sh = heightByName.get(rel.sourceTable) ?? svgCardHeight(0, metrics);
|
||||
const th = heightByName.get(rel.targetTable) ?? svgCardHeight(0, metrics);
|
||||
polylines[rel.id] = orthogonalPointsBetweenTables(sourcePos, targetPos, sh, th, cardWidth);
|
||||
}
|
||||
return polylines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build SVG path `d` strings for relationships from live waypoints or table positions.
|
||||
*/
|
||||
export function buildTableRelationshipPaths(input: RelationshipGeometryInput): Record<string, string> {
|
||||
const polylines = buildTableRelationshipPolylines(input);
|
||||
const paths: Record<string, string> = {};
|
||||
for (const [id, points] of Object.entries(polylines)) {
|
||||
paths[id] = pointsToSvgPath(points);
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
/** Compute canvas size that fits tables + layers + relationship polylines with padding. */
|
||||
export function computeTableDiagramCanvas(
|
||||
tables: DiagramTable[],
|
||||
positions: Record<string, DiagramPosition>,
|
||||
options: {
|
||||
cardWidth: number;
|
||||
cardHeaderHeight: number;
|
||||
columnRowHeight: number;
|
||||
cardBottomPadding?: number;
|
||||
layers?: DiagramSvgLayer[];
|
||||
relationshipPolylines?: Record<string, Point[]>;
|
||||
padding?: number;
|
||||
},
|
||||
): DiagramCanvas {
|
||||
const padding = options.padding ?? MARGIN;
|
||||
let minX = Infinity;
|
||||
let minY = Infinity;
|
||||
let maxX = -Infinity;
|
||||
let maxY = -Infinity;
|
||||
|
||||
const expand = (x1: number, y1: number, x2: number, y2: number) => {
|
||||
minX = Math.min(minX, x1);
|
||||
minY = Math.min(minY, y1);
|
||||
maxX = Math.max(maxX, x2);
|
||||
maxY = Math.max(maxY, y2);
|
||||
};
|
||||
|
||||
for (const layer of options.layers ?? []) {
|
||||
if (layer.width <= 0 || layer.height <= 0) continue;
|
||||
expand(layer.x, layer.y, layer.x + layer.width, layer.y + layer.height);
|
||||
}
|
||||
|
||||
for (const table of tables) {
|
||||
const pos = positions[table.name] ?? { x: 0, y: 0 };
|
||||
const height = svgCardHeight(table.columns.length, options);
|
||||
expand(pos.x, pos.y, pos.x + options.cardWidth, pos.y + height);
|
||||
}
|
||||
|
||||
for (const points of Object.values(options.relationshipPolylines ?? {})) {
|
||||
for (const point of points) {
|
||||
minX = Math.min(minX, point.x - relationshipPadding);
|
||||
minY = Math.min(minY, point.y - relationshipPadding);
|
||||
maxX = Math.max(maxX, point.x + relationshipPadding);
|
||||
maxY = Math.max(maxY, point.y + relationshipPadding);
|
||||
expand(point.x, point.y, point.x, point.y);
|
||||
}
|
||||
}
|
||||
|
||||
return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
|
||||
if (!Number.isFinite(minX) || !Number.isFinite(minY) || !Number.isFinite(maxX) || !Number.isFinite(maxY)) {
|
||||
return { width: 400 + padding, height: 300 + padding, originX: 0, originY: 0 };
|
||||
}
|
||||
|
||||
return {
|
||||
width: Math.ceil(maxX - minX + 2 * padding),
|
||||
height: Math.ceil(maxY - minY + 2 * padding),
|
||||
originX: minX - padding,
|
||||
originY: minY - padding,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildTableDiagramSvg(options: TableDiagramSvgOptions): string {
|
||||
const parts = [svgHeader(options.canvas, tableDiagramViewport(options)), tableDiagramDefs()];
|
||||
const ox = options.canvas.originX ?? 0;
|
||||
const oy = options.canvas.originY ?? 0;
|
||||
const parts = [svgHeader(options.canvas)];
|
||||
parts.push(`<g transform="translate(${svgNumber(-ox)} ${svgNumber(-oy)})">`);
|
||||
|
||||
for (const relationship of options.relationships) {
|
||||
const layout = options.relationshipLayouts[relationship.id];
|
||||
if (!layout?.path) continue;
|
||||
parts.push(`<g data-relationship-id="${escapeXml(relationship.id)}">`);
|
||||
parts.push(
|
||||
`<path d="${escapeXml(layout.path)}" fill="none" stroke="#2563eb" stroke-opacity="0.58" stroke-width="1.6" marker-end="url(#dbx-diagram-arrow)">` +
|
||||
`<title>${escapeXml(`${relationship.sourceTable}.${relationship.sourceColumn} (${relationship.sourceCardinality}:${relationship.targetCardinality}) -> ${relationship.targetTable}.${relationship.targetColumn}`)}</title>` +
|
||||
"</path>",
|
||||
);
|
||||
parts.push(
|
||||
svgText(relationship.sourceCardinality, layout.sourceCardinality.x, layout.sourceCardinality.y, {
|
||||
size: 12,
|
||||
weight: "600",
|
||||
anchor: "middle",
|
||||
stroke: "#fafafa",
|
||||
strokeWidth: 4,
|
||||
paintOrder: "stroke",
|
||||
attributes: { "data-cardinality-end": "source" },
|
||||
}),
|
||||
);
|
||||
parts.push(
|
||||
svgText(relationship.targetCardinality, layout.targetCardinality.x, layout.targetCardinality.y, {
|
||||
size: 12,
|
||||
weight: "600",
|
||||
anchor: "middle",
|
||||
stroke: "#fafafa",
|
||||
strokeWidth: 4,
|
||||
paintOrder: "stroke",
|
||||
attributes: { "data-cardinality-end": "target" },
|
||||
}),
|
||||
);
|
||||
const layers = (options.layers ?? []).filter((l) => l.width > 0 && l.height > 0);
|
||||
if (layers.length > 0) {
|
||||
parts.push('<g class="diagram-layers">');
|
||||
for (const layer of layers) {
|
||||
const fill = layer.color || "#9ca3af";
|
||||
parts.push(`<rect x="${svgNumber(layer.x)}" y="${svgNumber(layer.y)}" width="${svgNumber(layer.width)}" height="${svgNumber(layer.height)}" ` + `rx="8" fill="${escapeXml(fill)}" fill-opacity="0.08" stroke="${escapeXml(fill)}" stroke-opacity="0.55" stroke-width="1.5"/>`);
|
||||
parts.push(
|
||||
svgText(layer.name, layer.x + 12, layer.y + 18, {
|
||||
size: 12,
|
||||
weight: "600",
|
||||
fill: fill,
|
||||
}),
|
||||
);
|
||||
}
|
||||
parts.push("</g>");
|
||||
}
|
||||
|
||||
parts.push('<g fill="none" stroke="#2563eb" stroke-opacity="0.58" stroke-width="1.6">');
|
||||
for (const relationship of options.relationships) {
|
||||
const path = options.relationshipPaths[relationship.id];
|
||||
if (!path) continue;
|
||||
parts.push(`<path d="${escapeXml(path)}">` + `<title>${escapeXml(`${relationship.sourceTable}.${relationship.sourceColumn} -> ${relationship.targetTable}.${relationship.targetColumn}`)}</title>` + "</path>");
|
||||
}
|
||||
parts.push("</g>");
|
||||
|
||||
parts.push('<g class="diagram-cardinality">');
|
||||
for (const relationship of options.relationships) {
|
||||
const points = options.relationshipPolylines?.[relationship.id];
|
||||
if (!points || points.length < 2) continue;
|
||||
const sourcePos = pointAlongPolyline(points, SOURCE_CARDINALITY_T);
|
||||
const targetPos = pointAlongPolyline(points, TARGET_CARDINALITY_T);
|
||||
const sourceCard = relationship.sourceCardinality || "N";
|
||||
const targetCard = relationship.targetCardinality || "1";
|
||||
parts.push(
|
||||
svgText(sourceCard, sourcePos.x, sourcePos.y, {
|
||||
size: 11,
|
||||
weight: "700",
|
||||
anchor: "middle",
|
||||
fill: "#18181b",
|
||||
}),
|
||||
);
|
||||
parts.push(
|
||||
svgText(targetCard, targetPos.x, targetPos.y, {
|
||||
size: 11,
|
||||
weight: "700",
|
||||
anchor: "middle",
|
||||
fill: "#18181b",
|
||||
}),
|
||||
);
|
||||
}
|
||||
parts.push("</g>");
|
||||
|
||||
for (const table of options.tables) {
|
||||
const position = options.positions[table.name] ?? { x: 0, y: 0 };
|
||||
const height = tableHeight(table, options);
|
||||
const visibleColumns = table.columns.slice(0, options.maxVisibleColumns);
|
||||
const hiddenCount = Math.max(0, table.columns.length - options.maxVisibleColumns);
|
||||
const height = svgCardHeight(table.columns.length, options);
|
||||
parts.push(`<g transform="translate(${svgNumber(position.x)} ${svgNumber(position.y)})">`);
|
||||
parts.push(`<rect width="${options.cardWidth}" height="${svgNumber(height)}" rx="6" fill="#ffffff" stroke="#d4d4d8"/>`);
|
||||
parts.push(`<rect width="${options.cardWidth}" height="${options.cardHeaderHeight}" rx="6" fill="#f4f4f5"/>`);
|
||||
@@ -170,7 +291,7 @@ export function buildTableDiagramSvg(options: TableDiagramSvgOptions): string {
|
||||
}),
|
||||
);
|
||||
|
||||
visibleColumns.forEach((column, index) => {
|
||||
table.columns.forEach((column, index) => {
|
||||
const rowTop = options.cardHeaderHeight + index * options.columnRowHeight;
|
||||
const rowCenter = rowTop + options.columnRowHeight / 2;
|
||||
parts.push(`<path d="M 0 ${svgNumber(rowTop)} H ${options.cardWidth}" stroke="#f0f0f1"/>`);
|
||||
@@ -188,19 +309,10 @@ export function buildTableDiagramSvg(options: TableDiagramSvgOptions): string {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
if (hiddenCount > 0) {
|
||||
const y = options.cardHeaderHeight + visibleColumns.length * options.columnRowHeight + options.columnRowHeight / 2;
|
||||
parts.push(
|
||||
svgText(options.moreColumnsLabel?.(hiddenCount) ?? `+ ${hiddenCount} columns`, 12, y, {
|
||||
size: 11,
|
||||
fill: "#71717a",
|
||||
}),
|
||||
);
|
||||
}
|
||||
parts.push("</g>");
|
||||
}
|
||||
|
||||
parts.push("</g>");
|
||||
parts.push("</svg>");
|
||||
return parts.join("");
|
||||
}
|
||||
@@ -311,6 +423,8 @@ export function buildEngineeringDiagramSvg(diagram: EngineeringDiagram): string
|
||||
return parts.join("");
|
||||
}
|
||||
|
||||
type DiagramSvgMode = "table" | "engineering";
|
||||
|
||||
function fileToken(value: string): string {
|
||||
return value
|
||||
.trim()
|
||||
@@ -319,6 +433,7 @@ function fileToken(value: string): string {
|
||||
.replace(/^-|-$/g, "");
|
||||
}
|
||||
|
||||
/** Stable download name for SVG exports (shared with upstream contract tests). */
|
||||
export function diagramSvgFileName(connectionName: string, databaseName: string, mode: DiagramSvgMode): string {
|
||||
const context = [connectionName, databaseName].map(fileToken).filter(Boolean);
|
||||
const suffix = mode === "engineering" ? "engineering-er" : "table-structure";
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
|
||||
import { diagramExportDialogFilter, type DiagramExportFormat } from "./diagramFormats";
|
||||
|
||||
export async function saveDiagramTextExport(defaultPath: string, content: string, format: DiagramExportFormat): Promise<boolean> {
|
||||
if (isTauriRuntime()) {
|
||||
const [{ save }, { writeTextFile }] = await Promise.all([import("@tauri-apps/plugin-dialog"), import("@tauri-apps/plugin-fs")]);
|
||||
const path = await save({
|
||||
defaultPath,
|
||||
filters: [diagramExportDialogFilter(format)],
|
||||
});
|
||||
if (!path) return false;
|
||||
await writeTextFile(path, content);
|
||||
return true;
|
||||
}
|
||||
|
||||
const mime = format === "svg" ? "image/svg+xml" : format === "json" ? "application/json" : "text/plain";
|
||||
const blob = new Blob([content], { type: mime });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = defaultPath;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function saveDiagramBinaryExport(defaultPath: string, data: Blob, format: DiagramExportFormat): Promise<boolean> {
|
||||
if (isTauriRuntime()) {
|
||||
const [{ save }, { writeFile }] = await Promise.all([import("@tauri-apps/plugin-dialog"), import("@tauri-apps/plugin-fs")]);
|
||||
const path = await save({
|
||||
defaultPath,
|
||||
filters: [diagramExportDialogFilter(format)],
|
||||
});
|
||||
if (!path) return false;
|
||||
await writeFile(path, new Uint8Array(await data.arrayBuffer()));
|
||||
return true;
|
||||
}
|
||||
|
||||
const url = URL.createObjectURL(data);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = defaultPath;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
return true;
|
||||
}
|
||||
Reference in new issue
Block a user