-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pather.tsx
More file actions
408 lines (381 loc) · 10.2 KB
/
er.tsx
File metadata and controls
408 lines (381 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import { Graph, Shape, Edge, Selection } from '@antv/x6'
import React, { useEffect, useRef } from 'react'
import './er.less'
import './tableNode'
interface Table {
id?: string
name: string
fields: {
name: string
type: string
isPrimary?: boolean
isForeign?: boolean
isUnique?: boolean
}[]
foreignKeys?: {
field: string
referencedTable: string
referencedField: string
isUnique?: boolean
}[]
}
interface ErDiagramProps {
tables: Table[]
}
type RelationshipType = '1:1' | '1:N' | 'N:N'
// 配置常量
const CONFIG = {
nodeWidth: 240,
baseSpacing: 120,
minSpacing: 60,
headerHeight: 40,
fieldHeight: 25,
bottomPadding: 16,
}
// 创建图实例
const createErGraph = (container: HTMLElement) =>
new Graph({
container,
background: { color: '#f8f9fa' },
width: container.clientWidth || 800,
height: container.clientHeight || 600,
autoResize: true,
interacting: {
nodeMovable: true,
edgeMovable: true,
edgeLabelMovable: false,
},
grid: { visible: true, type: 'dot', args: { color: '#ddd', thickness: 1 } },
mousewheel: {
enabled: true,
zoomAtMousePosition: true,
modifiers: 'ctrl',
minScale: 0.5,
maxScale: 1.5,
},
connecting: {
snap: true,
allowBlank: false,
allowLoop: false,
highlight: true,
connectionPoint: 'anchor',
router: { name: 'manhattan', args: { step: 10 } },
connector: { name: 'rounded', args: { radius: 8 } },
createEdge: () =>
new Shape.Edge({
attrs: {
line: {
stroke: '#999',
strokeWidth: 2,
targetMarker: { name: 'block', width: 12, height: 8 },
},
},
labels: [
{
attrs: {
text: {
text: '1:1',
fill: '#999',
fontSize: 14,
fontWeight: 'bold',
},
rect: {
fill: 'white',
stroke: '#999',
strokeWidth: 1,
rx: 3,
ry: 3,
},
},
position: 0.5,
draggable: false,
},
],
data: { relationshipType: '1:1' as RelationshipType },
}),
},
})
// 计算节点高度
const calculateNodeHeight = (fields: Table['fields']) =>
CONFIG.headerHeight +
fields.length * CONFIG.fieldHeight +
CONFIG.bottomPadding
// 创建节点配置
const createNode = (table: Table, x: number, y: number) => ({
id: table.name,
shape: 'er-table',
x,
y,
width: CONFIG.nodeWidth,
height: calculateNodeHeight(table.fields || []),
data: { tableName: table.name, fields: table.fields },
attrs: {
body: { stroke: '#1890ff', strokeWidth: 2, fill: '#fff', rx: 4, ry: 4 },
},
ports: {
groups: {
top: {
position: { name: 'top' },
attrs: {
circle: {
r: 4,
magnet: true,
stroke: '#5F95FF',
fill: '#fff',
},
},
},
bottom: {
position: { name: 'bottom' },
attrs: {
circle: {
r: 4,
magnet: true,
stroke: '#5F95FF',
fill: '#fff',
},
},
},
left: {
position: { name: 'left' },
attrs: {
circle: {
r: 4,
magnet: true,
stroke: '#5F95FF',
fill: '#fff',
},
},
},
right: {
position: { name: 'right' },
attrs: {
circle: {
r: 4,
magnet: true,
stroke: '#5F95FF',
fill: '#fff',
},
},
},
},
items: [
{ id: 'top', group: 'top' },
{ id: 'bottom', group: 'bottom' },
{ id: 'left', group: 'left' },
{ id: 'right', group: 'right' },
],
},
})
// 创建边配置
const createEdge = (source: string, target: string) => ({
id: `${source}-${target}`,
source: { cell: source, port: 'right' },
target: { cell: target, port: 'left' },
attrs: {
line: {
stroke: '#999',
strokeWidth: 2,
targetMarker: { name: 'block', width: 8, height: 6, fill: '#999' },
},
},
labels: [
{
attrs: {
text: { text: '1:1', fill: '#999', fontSize: 14, fontWeight: 'bold' },
rect: { fill: 'white', stroke: '#999', strokeWidth: 1, rx: 3, ry: 3 },
},
position: 0.5,
draggable: false,
},
],
data: { relationshipType: '1:1' as RelationshipType },
router: { name: 'manhattan' },
connector: { name: 'rounded' },
})
// 布局表格
const layoutTables = (tables: Table[]) => {
const nodes: any[] = []
const edges: any[] = []
const nodeData = tables.map((table) => ({
id: table.name,
width: CONFIG.nodeWidth,
height: calculateNodeHeight(table.fields || []),
table,
}))
const cols = 2
const colWidth = CONFIG.nodeWidth + CONFIG.baseSpacing
const rowHeight = 300 // 可以根据节点最大高度动态计算
nodeData.forEach((data, i) => {
const row = Math.floor(i / cols)
const col = i % cols
const x = col * colWidth
const y = row * rowHeight
nodes.push(createNode(data.table, x, y))
})
tables.forEach((table) => {
table.foreignKeys?.forEach((fk) => {
if (fk.field && fk.referencedTable && table.name !== fk.referencedTable) {
edges.push(createEdge(table.name, fk.referencedTable))
}
})
})
return { nodes, edges }
}
export const ErDiagram: React.FC<ErDiagramProps> = ({ tables }) => {
const containerRef = useRef<HTMLDivElement>(null)
const graphRef = useRef<Graph | null>(null)
const toggleType = (edge: Edge) => {
const types: RelationshipType[] = ['1:1', '1:N', 'N:N']
const current = edge.getData()?.relationshipType || '1:1'
const next = types[(types.indexOf(current) + 1) % types.length]
edge.setData({ relationshipType: next })
edge.setLabels([
{
attrs: {
text: { text: next, fill: '#999', fontSize: 14, fontWeight: 'bold' },
rect: { fill: 'white', stroke: '#999', strokeWidth: 1, rx: 3, ry: 3 },
},
position: 0.5,
},
])
}
useEffect(() => {
if (!containerRef.current) return
const graph = createErGraph(containerRef.current)
graphRef.current = graph
graph.use(
new Selection({
multiple: true,
rubberband: true,
showNodeSelectionBox: true,
resizable: true,
rotatable: { grid: 15 },
}),
)
graph.on('edge:click', ({ edge }) => {
toggleType(edge)
})
graph.on('edge:mouseenter', ({ edge }) => {
edge.addTools([
{ name: 'target-arrowhead', args: { attrs: { fill: '#999' } } },
{
name: 'button-remove',
args: {
distance: -40,
offset: 0,
attrs: { 'font-size': 12, fill: 'red' },
},
},
])
})
graph.on('edge:mouseleave', ({ edge }) => edge.removeTools())
return () => {
if (graphRef.current) {
graphRef.current.dispose()
graphRef.current = null
}
}
}, [])
useEffect(() => {
if (!graphRef.current) return
const validTables = tables.filter((t) => t?.name && Array.isArray(t.fields))
if (!validTables.length) return
const { nodes, edges } = layoutTables(validTables)
graphRef.current.addNodes(nodes)
graphRef.current.addEdges(edges)
graphRef.current.centerContent()
requestAnimationFrame(() => {
if (graphRef.current) {
graphRef.current.zoomToFit({ padding: 20 })
}
})
}, [tables])
return (
<div className="relative" style={{ height: '600px' }}>
<div style={{ paddingBottom: 10, textAlign: 'center' }}>
<div>操作提示</div>
<div>点击边的标签切换关系类型</div>
<div>循环:1:1 → 1:N → N:N</div>
</div>
<div
ref={containerRef}
className="w-full h-full"
style={{ background: '#f8f9fa' }}
/>
</div>
)
}
const data = [
{
id: 'profiles',
name: 'profiles',
fields: [
{ name: 'id', type: 'bigint', isPrimary: true },
{ name: 'user_id', type: 'bigint', isForeign: true },
{ name: 'first_name', type: 'varchar(50)' },
{ name: 'last_name', type: 'varchar(50)' },
{ name: 'avatar_url', type: 'varchar(255)' },
{ name: 'bio', type: 'text' },
{ name: 'birth_date', type: 'date' },
{ name: 'phone', type: 'varchar(20)' },
],
foreignKeys: [
{
field: 'user_id',
referencedTable: 'users',
referencedField: 'id',
isUnique: true,
},
],
},
{
id: 'users',
name: 'users',
fields: [
{ name: 'id', type: 'bigint', isPrimary: true },
{ name: 'username', type: 'varchar(50)', isUnique: true },
{ name: 'email', type: 'varchar(100)', isUnique: true },
{ name: 'password_hash', type: 'varchar(255)' },
{ name: 'created_at', type: 'timestamp' },
{ name: 'updated_at', type: 'timestamp' },
{ name: 'status', type: 'tinyint' },
],
foreignKeys: [],
},
{
id: 'posts',
name: 'posts',
fields: [
{ name: 'id', type: 'bigint', isPrimary: true },
{ name: 'user_id', type: 'bigint', isForeign: true },
{ name: 'title', type: 'varchar(200)' },
{ name: 'content', type: 'text' },
{ name: 'status', type: 'varchar(20)' },
{ name: 'created_at', type: 'timestamp' },
{ name: 'updated_at', type: 'timestamp' },
{ name: 'published_at', type: 'timestamp' },
],
foreignKeys: [
{ field: 'user_id', referencedTable: 'users', referencedField: 'id' },
],
},
{
id: 'categories',
name: 'categories',
fields: [
{ name: 'id', type: 'bigint', isPrimary: true },
{ name: 'name', type: 'varchar(100)', isUnique: true },
{ name: 'slug', type: 'varchar(100)', isUnique: true },
{ name: 'description', type: 'text' },
{ name: 'parent_id', type: 'bigint', isForeign: true },
{ name: 'created_at', type: 'timestamp' },
],
foreignKeys: [],
},
]
export const CaseErExample = () => (
<div className="x6-graph-wrap">
<ErDiagram tables={data} />
</div>
)