-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathsql2er.html
More file actions
1164 lines (1072 loc) · 43 KB
/
sql2er.html
File metadata and controls
1164 lines (1072 loc) · 43 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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SQL/DBML2ER</title>
<link
rel="stylesheet"
href="https://unpkg.com/antd@5.19.1/dist/reset.css"
/>
<link
rel="stylesheet"
href="https://unpkg.com/antd@5.19.1/dist/antd.min.css"
/>
<!-- Anthropic 风格:先字体,后 base -->
<link rel="stylesheet" href="./assets/fonts/fonts.css" />
<link rel="stylesheet" href="./assets/base.css" />
<!-- 中文字体(霞鹜文楷)-->
<link rel="preconnect" href="https://cdn.jsdmirror.com" />
<link
href="https://cdn.jsdmirror.com/npm/lxgw-wenkai-webfont@1.7.0/style.css"
rel="stylesheet"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css"
/>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<a
href="https://github.com/ystemsrx/ER_diagram_generator"
class="github-corner"
aria-label="View source on GitHub"
target="_blank"
rel="noopener noreferrer"
>
<svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true">
<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
<path
d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
fill="currentColor"
class="octo-arm"
></path>
<path
d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
fill="currentColor"
class="octo-body"
></path>
</svg>
</a>
<div
class="lang-switch"
data-lang="zh"
role="tablist"
aria-label="切换语言 / Switch language"
>
<button type="button" class="lang-option is-active" data-lang="zh" role="tab" aria-selected="true">中</button>
<button type="button" class="lang-option" data-lang="en" role="tab" aria-selected="false">EN</button>
<span class="lang-thumb" aria-hidden="true"></span>
</div>
<div class="app-container lang-fade-target">
<div class="header">
<span class="header-eyebrow" data-i18n="eyebrow">Chen Model · Entity-Relationship</span>
<h1 data-i18n-html="title">SQL / DBML 转 <em>ER 图</em> 生成器</h1>
<p data-i18n="subtitle">把建表语句或 DBML 一键渲染为 Chen 模型实体-关系图</p>
<p class="header-hint" data-i18n="hint">双击编辑节点 · 滚轮缩放 · 拖拽排布</p>
</div>
<div id="root"></div>
</div>
<script>
window.SQL2ER_I18N = {
zh: {
eyebrow: "Chen Model · Entity-Relationship",
title: "SQL / DBML 转 <em>ER 图</em> 生成器",
subtitle: "把建表语句或 DBML 一键渲染为 Chen 模型实体-关系图",
hint: "双击编辑节点 · 滚轮缩放 · 拖拽排布",
pageTitle: "SQL/DBML2ER",
cardInputTitle: "SQL / DBML",
cardPreviewTitle: "ER 图预览",
showComment: "属性显示注释",
editorPlaceholder: "在此处粘贴您的 CREATE TABLE 或 DBML 语句...",
btnGenerate: "⚡ 生成 ER 图",
btnExport: "📥 导出 SVG",
btnSmartLayout: "✨ 智能布局",
btnForceAlign: "📐 强制对齐",
legendEntity: "实体",
legendRelation: "关系",
legendAttribute: "属性",
legendPk: "主键",
tipShowBg: "显示背景",
tipHideBg: "隐藏背景",
tipColorOn: "开启着色",
tipColorOff: "关闭着色",
errEmpty: "输入为空。",
errNoTable:
"未找到有效的 CREATE TABLE 或 Table 定义。请确保您的 SQL 或 DBML 语法正确。",
errParse: "SQL 解析失败",
errParseHint: "。请检查 SQL 语法是否正确。",
sample: `-- 示例 DBML,请在此处粘贴您的 DBML 或 SQL 语句
Table 用户 {
编号 INT [pk, increment]
用户名 VARCHAR(255) [not null]
邮箱 VARCHAR(255) [unique]
创建时间 TIMESTAMP
}
Table 国家 {
编号 INT [pk]
名称 VARCHAR(255) [not null]
}
Table 文章 {
文章编号 INT [pk]
内容 TEXT
}
Ref: 用户.属于 > 国家.编号
Ref: 文章.作者 > 用户.编号
`,
},
en: {
eyebrow: "Chen Model · Entity-Relationship",
title: "Turn SQL / DBML into an <em>ER Diagram</em>",
subtitle:
"Render CREATE TABLE statements or DBML as a Chen-model entity-relationship diagram",
hint: "Double-click to edit · Scroll to zoom · Drag to arrange",
pageTitle: "SQL/DBML2ER",
cardInputTitle: "SQL / DBML",
cardPreviewTitle: "ER Preview",
showComment: "Show comments",
editorPlaceholder: "Paste your CREATE TABLE or DBML statement here...",
btnGenerate: "⚡ Generate",
btnExport: "📥 Export SVG",
btnSmartLayout: "✨ Smart layout",
btnForceAlign: "📐 Force align",
legendEntity: "Entity",
legendRelation: "Relationship",
legendAttribute: "Attribute",
legendPk: "Primary key",
tipShowBg: "Show background",
tipHideBg: "Hide background",
tipColorOn: "Enable color",
tipColorOff: "Disable color",
errEmpty: "Input is empty.",
errNoTable:
"No valid CREATE TABLE or Table definition found. Make sure your SQL or DBML syntax is correct.",
errParse: "SQL parsing failed",
errParseHint: ". Please check your SQL syntax.",
sample: `-- Sample DBML — paste your DBML or SQL statements here
Table User {
ID INT [pk, increment]
Username VARCHAR(255) [not null]
Email VARCHAR(255) [unique]
CreatedAt TIMESTAMP
}
Table Country {
ID INT [pk]
Name VARCHAR(255) [not null]
}
Table Article {
ArticleID INT [pk]
Content TEXT
}
Ref: User.BelongsTo > Country.ID
Ref: Article.Author > User.ID
`,
},
};
(function () {
const root = document.documentElement;
const switcher = document.querySelector(".lang-switch");
const options = switcher.querySelectorAll(".lang-option");
const headerEls = {
i18n: document.querySelectorAll("[data-i18n]"),
html: document.querySelectorAll("[data-i18n-html]"),
};
function detectLang() {
const saved = localStorage.getItem("sql2er-lang");
if (saved === "zh" || saved === "en") return saved;
return (navigator.language || "en").toLowerCase().startsWith("zh")
? "zh"
: "en";
}
function applyHeader(lang) {
const dict = window.SQL2ER_I18N[lang];
headerEls.i18n.forEach((el) => {
const k = el.getAttribute("data-i18n");
if (dict[k] !== undefined) el.textContent = dict[k];
});
headerEls.html.forEach((el) => {
const k = el.getAttribute("data-i18n-html");
if (dict[k] !== undefined) el.innerHTML = dict[k];
});
document.title = dict.pageTitle;
root.setAttribute("lang", lang === "zh" ? "zh-CN" : "en");
switcher.setAttribute("data-lang", lang);
options.forEach((btn) => {
const active = btn.getAttribute("data-lang") === lang;
btn.classList.toggle("is-active", active);
btn.setAttribute("aria-selected", active ? "true" : "false");
});
}
function setLang(lang, opts) {
const initial = opts && opts.initial;
if (initial) {
applyHeader(lang);
localStorage.setItem("sql2er-lang", lang);
window.dispatchEvent(
new CustomEvent("sql2er-lang", { detail: { lang, initial: true } }),
);
return;
}
if (document.documentElement.getAttribute("lang") &&
((document.documentElement.getAttribute("lang").startsWith("zh") ? "zh" : "en") === lang)) {
return;
}
document.body.classList.add("is-lang-fading");
localStorage.setItem("sql2er-lang", lang);
setTimeout(() => {
applyHeader(lang);
window.dispatchEvent(
new CustomEvent("sql2er-lang", { detail: { lang } }),
);
requestAnimationFrame(() => {
document.body.classList.remove("is-lang-fading");
});
}, 200);
}
options.forEach((btn) => {
btn.addEventListener("click", () => {
setLang(btn.getAttribute("data-lang"));
});
});
window.SQL2ER_setLang = setLang;
window.SQL2ER_currentLang = detectLang();
setLang(window.SQL2ER_currentLang, { initial: true });
})();
</script>
<!-- Dependencies -->
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://unpkg.com/dayjs@1.11.10/dayjs.min.js"></script>
<script src="https://unpkg.com/antd@5.19.1/dist/antd.min.js"></script>
<script src="https://unpkg.com/@antv/g6@4.8.24/dist/g6.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/sql/sql.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/javascript/javascript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/addon/display/placeholder.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/addon/edit/matchbrackets.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/addon/edit/closebrackets.min.js"></script>
<!-- Parser Modules -->
<script src="js/parser-sql.js"></script>
<script src="js/parser-dbml.js"></script>
<!-- ER Builder Module -->
<script src="js/builder.js"></script>
<!-- Layout Module -->
<script src="js/layout.js"></script>
<!-- Editor Module -->
<script src="js/editor.js"></script>
<!-- Exporter Module -->
<script src="js/exporter.js"></script>
<!-- Main Application Script -->
<script type="text/babel">
window.addEventListener("load", () => {
const { useState, useEffect, useRef } = React;
const { Switch } = window.antd;
const G6 = window.G6;
// 注册 G6 自定义节点(entity, attribute, relationship)
window.ERBuilder.registerCustomNodes(G6);
// 从 ERBuilder 模块获取函数
const generateChenModelData = window.ERBuilder.generateChenModelData;
const patchRelationshipLinkPoints =
window.ERBuilder.patchRelationshipLinkPoints;
// 从 Layout 模块获取布局函数
const {
smoothFitView,
animateNodesToTargets,
deterministicHash,
deterministicRandom,
applyInitialComponentPositions,
spreadDisconnectedComponents,
forceAlignLayout,
arrangeLayout,
} = window.Layout;
// 从 Editor 模块获取 CodeEditor 组件
const CodeEditor = window.Editor.createCodeEditorComponent(React);
const App = () => {
const I18N = window.SQL2ER_I18N;
const [lang, setLang] = useState(
() => window.SQL2ER_currentLang || "zh",
);
const t = I18N[lang];
const [showBackground, setShowBackground] = useState(true);
const [inputText, setInputText] = useState(
() => I18N[window.SQL2ER_currentLang || "zh"].sample,
);
const [isColored, setIsColored] = useState(true);
const [showComment, setShowComment] = useState(false);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const [hasGraph, setHasGraph] = useState(false);
const lastInputRef = useRef(""); // 记录上次生成时的输入
const containerRef = useRef(null);
const graphRef = useRef(null);
// 更新图表样式
const updateGraphStyles = (graphInstance, colored) => {
if (!graphInstance || graphInstance.destroyed) return;
graphInstance.setAutoPaint(false);
const nodes = graphInstance.getNodes();
nodes.forEach((node) => {
const model = node.getModel();
const styles = {};
if (colored) {
if (model.nodeType === "entity") {
if (model.isPlaceholder) {
// Placeholder entity: same blue theme but dashed border
styles.style = {
fill: "#e0f2fe",
stroke: "#0ea5e9",
lineWidth: 2,
lineDash: [4, 4],
shadowColor: "rgba(14, 165, 233, 0.2)",
shadowBlur: 10,
};
styles.labelCfg = {
style: {
fill: "#0f172a",
fontWeight: "700",
fontFamily: "Poppins",
fontStyle: "italic",
},
};
} else {
// Sky Blue theme
styles.style = {
fill: "#e0f2fe",
stroke: "#0ea5e9",
lineWidth: 2,
shadowColor: "rgba(14, 165, 233, 0.2)",
shadowBlur: 10,
};
styles.labelCfg = {
style: {
fill: "#0f172a",
fontWeight: "700",
fontFamily: "Poppins",
},
};
}
} else if (model.nodeType === "relationship") {
// Violet theme
styles.style = {
fill: "#f5f3ff",
stroke: "#8b5cf6",
lineWidth: 2,
shadowColor: "rgba(139, 92, 246, 0.2)",
shadowBlur: 10,
};
styles.labelCfg = {
style: { fill: "#0f172a", fontFamily: "Poppins" },
};
} else if (model.nodeType === "attribute") {
if (model.keyType === "pk") {
// Emerald theme
styles.style = {
fill: "#ecfdf5",
stroke: "#10b981",
lineWidth: 2,
shadowColor: "rgba(16, 185, 129, 0.2)",
shadowBlur: 5,
};
styles.labelCfg = {
style: {
fill: "#0f172a",
fontWeight: "700",
fontFamily: "Poppins",
},
};
} else {
// Slate theme
styles.style = {
fill: "#ffffff",
stroke: "#94a3b8", // Slate 400
lineWidth: 2,
};
styles.labelCfg = {
style: {
fill: "#475569",
fontWeight: "normal",
fontFamily: "Poppins",
},
};
}
}
} else {
// 黑白模式 (无填充 = 白色背景)
styles.style = {
fill: "#ffffff",
stroke: "#1e293b",
lineWidth:
model.keyType === "pk" ||
model.nodeType === "entity" ||
model.nodeType === "relationship"
? 2
: 1,
shadowBlur: 0,
};
if (model.isPlaceholder) {
styles.style.lineDash = [4, 4];
styles.style.stroke = "#64748b";
styles.labelCfg = {
style: {
fill: "#64748b",
fontWeight: "bold",
fontStyle: "italic",
fontFamily: "Poppins",
},
};
} else {
styles.labelCfg = {
style: {
fill: "#1e293b",
fontWeight:
model.nodeType === "entity" || model.keyType === "pk"
? "bold"
: "normal",
fontFamily: "Poppins",
},
};
}
}
graphInstance.updateItem(node, styles);
});
// 刷新边
const edges = graphInstance.getEdges();
edges.forEach((edge) => {
graphInstance.updateItem(edge, {
style: {
stroke: "#000000",
lineWidth: 1.5,
endArrow: false,
},
labelCfg: {
style: {
fill: "#000000",
fontSize: 12,
background: {
fill: "#ffffff",
padding: [2, 4, 2, 4],
radius: 2,
},
},
},
});
});
graphInstance.paint();
graphInstance.setAutoPaint(true);
};
const pendingRegenRef = useRef(false);
// 监听语言切换事件(由顶部 vanilla 脚本派发)
useEffect(() => {
const onLang = (e) => {
const nextLang = e.detail && e.detail.lang;
if (!nextLang || nextLang === lang) return;
// 如果用户尚未修改示例,则切换为目标语言的示例
setInputText((prev) => {
if (prev === I18N.zh.sample || prev === I18N.en.sample) {
pendingRegenRef.current = true;
return I18N[nextLang].sample;
}
return prev;
});
setLang(nextLang);
};
window.addEventListener("sql2er-lang", onLang);
return () => window.removeEventListener("sql2er-lang", onLang);
}, [lang]);
// 语言切换后若示例已替换,则自动重新生成
useEffect(() => {
if (pendingRegenRef.current) {
pendingRegenRef.current = false;
handleGenerate();
}
}, [inputText]);
// 监听着色状态变化
useEffect(() => {
if (hasGraph && graphRef.current) {
updateGraphStyles(graphRef.current, isColored);
}
}, [isColored, hasGraph]);
// 监听 showComment 变化,重新生成图表
useEffect(() => {
if (hasGraph && lastInputRef.current) {
handleGenerate();
}
}, [showComment]);
const handleGenerate = () => {
try {
setError(null);
setLoading(true);
if (!inputText.trim()) {
setError(t.errEmpty);
setLoading(false);
return;
}
// 如果输入改变了,记录新输入
if (lastInputRef.current !== inputText.trim()) {
lastInputRef.current = inputText.trim();
}
let parsedData;
const potentialSQL = inputText.trim();
// Try parsing as SQL first, if it fails (no tables), try DBML.
parsedData = parseSQLTables(potentialSQL);
if (parsedData.tables.length === 0) {
parsedData = parseDBML(potentialSQL);
}
const { tables, relationships } = parsedData;
if (tables.length === 0) {
setError(t.errNoTable);
setLoading(false);
return;
}
const { nodes, edges } = generateChenModelData(
tables,
relationships,
isColored,
showComment ? "comment" : "name",
);
// 初始位置:先把不同组件分开围绕中心,避免初始交叉
applyInitialComponentPositions(
nodes,
edges,
containerRef.current,
0,
);
// Clear previous graph completely
if (graphRef.current) {
graphRef.current.clear(); // 先清空数据
graphRef.current.destroy(); // 再销毁图形
graphRef.current = null; // 重置引用
}
// Create G6 graph
const graph = new G6.Graph({
container: containerRef.current,
width: containerRef.current.offsetWidth,
height: containerRef.current.offsetHeight,
renderer: "canvas",
background: "#ffffff", // 设置白色背景,确保复制图片时背景为白色
modes: {
default: [
"drag-node", // 1. 先判断拖节点
{
type: "drag-canvas",
allowDragOnItem: true, // 2. 允许在 item 上拖画布
enableOptimize: false, // (性能优化,可留可删)
shouldBegin(e) {
// 3. 自定义开始条件
// e.item 为空 = 真空白处;组合 / 边也算"非 node"
return !e.item || e.item.getType() !== "node";
},
},
"zoom-canvas",
],
},
// 优化后的力导向布局配置,以完全避免重叠
layout: {
type: "force2", // 使用 force2 布局
preventOverlap: true, // 确保节点不重叠
// 忽略文本长度,统一处理椭圆/菱形尺寸,避免因内容长短造成布局偏差
nodeSize: (node) => {
const uniformSizes = {
entity: 140,
relationship: 90,
attribute: 90,
};
return uniformSizes[node.nodeType] || 90;
},
nodeSpacing: 20, // 增加节点间距
linkDistance: 120, // 连线长度
// force2 特定参数
coulombDisScale: 0.005, // 库仑力的缩放因子
damping: 0.9, // 阻尼系数
maxSpeed: 1000, // 最大速度
minMovement: 0.5, // 最小移动量
interval: 0.02, // 迭代间隔
factor: 1, // 斥力因子
maxIteration: 800, // 最大迭代次数
animate: true, // 启用动画以显示布局过程
center: [containerRef.current.offsetWidth / 2, 300], // 布局中心
clustering: false, // 不使用聚类
tick: () => {
// 逐帧刷新以展现自动调整过程
graph.refreshPositions();
},
onLayoutEnd: () => {
// 先让互不相连的组件环绕分布,避免十字交叉
setTimeout(() => {
if (graphRef.current && !graphRef.current.destroyed) {
spreadDisconnectedComponents(graphRef.current, () => {
// 布局完成后平滑调整视图
smoothFitView(graphRef.current, 800, "easeOutCubic");
});
}
}, 30);
},
},
defaultNode: {
style: {
lineWidth: 2,
stroke: "#000",
fill: "#fff",
},
labelCfg: {
style: {
fill: "#000",
fontSize: 16, // 从12增加到16
},
},
},
defaultEdge: {
style: {
lineWidth: 1,
stroke: "#000000",
},
labelCfg: {
style: {
fill: "#000000",
fontSize: 14, // 从10增加到14
background: {
fill: "#fff",
padding: [2, 4, 2, 4],
},
},
},
},
edgeStateStyles: {
hover: {
stroke: "#1890ff",
lineWidth: 2,
},
},
defaultEdgeConfig: {
type: "line",
},
nodeStateStyles: {
hover: {
fill: "#e6f7ff",
stroke: "#1890ff",
},
},
});
graphRef.current = graph;
setHasGraph(true); // 标记图形已生成
// Set data and render
graph.data({ nodes, edges });
graph.render();
// 应用初始样式
updateGraphStyles(graph, isColored);
// 修正菱形连线计算
patchRelationshipLinkPoints(graph);
// 初始渲染后使用平滑动画调整视图
setTimeout(() => {
smoothFitView(graph, 600, "easeOutQuart");
}, 200);
// Enable interactions
graph.on("node:mouseenter", (e) => {
graph.setItemState(e.item, "hover", true);
});
graph.on("node:mouseleave", (e) => {
graph.setItemState(e.item, "hover", false);
});
// 设置节点双击编辑功能(使用 Editor 模块)
window.Editor.setupNodeDoubleClickEdit(
graph,
containerRef.current,
);
// 自定义拖拽逻辑:拖动实体时带动相关属性一起移动
let draggedEntity = null;
let relatedAttributes = [];
let dragStartPositions = new Map();
graph.on("node:dragstart", (e) => {
const node = e.item;
const nodeModel = node.getModel();
// 只处理实体节点的拖拽
if (nodeModel.type === "entity") {
draggedEntity = node;
relatedAttributes = [];
dragStartPositions.clear();
// 记录实体的初始位置
dragStartPositions.set(nodeModel.id, {
x: nodeModel.x,
y: nodeModel.y,
});
// 找到所有相关的属性节点
const allNodes = graph.getNodes();
allNodes.forEach((n) => {
const model = n.getModel();
if (
model.type === "attribute" &&
model.parentEntity === nodeModel.id
) {
relatedAttributes.push(n);
// 记录属性的初始位置
dragStartPositions.set(model.id, {
x: model.x,
y: model.y,
});
}
});
}
});
graph.on("node:drag", (e) => {
const node = e.item;
const nodeModel = node.getModel();
// 只处理实体节点的拖拽
if (nodeModel.type === "entity" && draggedEntity === node) {
const currentPos = { x: nodeModel.x, y: nodeModel.y };
const startPos = dragStartPositions.get(nodeModel.id);
if (startPos) {
// 计算实体的移动距离
const deltaX = currentPos.x - startPos.x;
const deltaY = currentPos.y - startPos.y;
// 同步移动所有相关的属性节点
relatedAttributes.forEach((attrNode) => {
const attrModel = attrNode.getModel();
const attrStartPos = dragStartPositions.get(attrModel.id);
if (attrStartPos) {
const newX = attrStartPos.x + deltaX;
const newY = attrStartPos.y + deltaY;
// 更新属性节点位置
graph.updateItem(attrNode, { x: newX, y: newY });
}
});
}
}
});
graph.on("node:dragend", (e) => {
const node = e.item;
const nodeModel = node.getModel();
// 清理拖拽状态
if (nodeModel.type === "entity" && draggedEntity === node) {
draggedEntity = null;
relatedAttributes = [];
dragStartPositions.clear();
}
});
// 自动布局说明:
// 1. force布局会自动计算节点位置,避免重叠
// 2. 不同类型节点有不同的排斥力和间距
// 3. 连线长度根据关系类型自动调整
// 4. 布局完成后自动调整视图大小
} catch (e) {
console.error("SQL Parsing error:", e);
setError(`${t.errParse}: ${e.message}${t.errParseHint}`);
} finally {
setLoading(false);
}
};
useEffect(() => {
handleGenerate();
// Cleanup on unmount
return () => {
if (graphRef.current) {
graphRef.current.destroy();
}
};
}, []);
const handleResize = () => {
if (graphRef.current && containerRef.current) {
graphRef.current.changeSize(
containerRef.current.offsetWidth,
containerRef.current.offsetHeight,
);
}
};
// 导出SVG功能 - 使用 Exporter 模块
const handleExportSVG = () => {
window.Exporter.exportSVG({
graphRef: graphRef,
hasGraph: hasGraph,
containerRef: containerRef,
onError: setError,
patchRelationshipLinkPoints: patchRelationshipLinkPoints,
G6: G6,
});
};
useEffect(() => {
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
// 切换背景显示
const handleToggleBackground = () => {
setShowBackground(!showBackground);
};
// 强制对齐:忽略椭圆,主链水平,支线递归均分
const handleForceAlign = () => {
if (!graphRef.current || graphRef.current.destroyed) return;
const containerWidth = containerRef.current?.offsetWidth || 1200;
forceAlignLayout(graphRef.current, containerWidth);
};
// 环绕排布:让属性均匀围绕实体,同时可移动实体以满足关系距离
const handleArrangeLayout = () => {
if (!graphRef.current || graphRef.current.destroyed) return;
arrangeLayout(graphRef.current);
};
return (
<div className="main-content">
<div className="input-section">
<div className="card">
<div
className="card-header"
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
>
<h2 className="card-title">
<span style={{ fontSize: "1.5rem" }}>📄</span>
{t.cardInputTitle}
</h2>
<div
style={{
display: "flex",
alignItems: "center",
gap: "10px",
}}
>
<span className="inline-label">{t.showComment}</span>
<Switch
checked={showComment}
onChange={setShowComment}
size="small"
/>
</div>
</div>
<div className="card-content">
<div
style={{
height: "480px",
display: "flex",
flexDirection: "column",
}}
>
<CodeEditor
value={inputText}
onChange={setInputText}
placeholder={t.editorPlaceholder}
/>
</div>
<div className="button-group">
<button
className="btn btn-primary"
onClick={handleGenerate}
disabled={loading}
>
{loading ? (
<div
className="spinner"
style={{ width: 20, height: 20, borderWidth: 2 }}
></div>
) : (
t.btnGenerate
)}
</button>
<button
className="btn btn-secondary"
onClick={handleExportSVG}
disabled={!hasGraph}
>
{t.btnExport}
</button>
</div>
</div>
</div>
</div>
<div className="output-section">
<div className="card">
<div
className="card-header"
style={{ flexWrap: "wrap", gap: "16px", height: "auto" }}
>
<div
style={{
display: "flex",
alignItems: "center",
gap: "24px",
flex: 1,
minWidth: "300px",
}}
>
<h2
className="card-title"
style={{ whiteSpace: "nowrap" }}
>
<span style={{ fontSize: "1.5rem" }}>🎨</span>
{t.cardPreviewTitle}
</h2>
<div
style={{
display: "flex",
gap: "8px",
alignItems: "center",
flexWrap: "wrap",
}}
>
<div
className="legend-item"
style={{ padding: "4px 10px", fontSize: "0.8rem" }}