liemermaid 0.3.1

Mermaid diagram parser + renderer (SVG / vello_cpu PNG), unified through lievisual Scene IR.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
//! Stage 3: Materialize —— 视觉决策点(唯一消费主题常量的地方)。
//!
//! 消费 `Geograph`(+ 预留的 `StyleIntent`),把"几何 + 样式"解析成具体颜色 / 线型,
//! 产出视觉自足的 [`SceneGraph`]。之后 `paint` 不再有任何 theme 依赖、不再有任何图类型判断。
//!
//! 说明:`StyleIntent` 目前仅保留接口,具体颜色 / 线型仍按 `theme` 常量解析,
//! 详见 [`StyleIntent`] 的文档。
//!
//! 支持 flowchart + state:节点按 [`ShapeKind`](含 StartDot 实心圆 / EndDot 双环 /
//! Bar 横条),边按 [`EdgeKind`] 选 flowchart / state 主题,边标签绘制白底文本。

use std::collections::HashMap;

use lievisual::geometry::{Color, Point, Rect, Size};
use lievisual::scene::{Fill, LineCap, LineJoin, Stroke};
use lievisual::text::{
    FontWeight, LineMetrics, RichSpan, TextAlign, TextBaseline, TextLayout, TextStyle,
    layout_metrics, layout_text,
};

use crate::builder::ir::{
    self, SceneGraph, SceneItem, StyleIntent,
    common::{ArrowKind, ArrowSpec},
    geograph::{GGNode, Geograph},
    shape::{EdgeEnds, ShapeGeometry, ShapeKind},
    unigraph::EdgeKind,
};
use crate::builder::theme;

const NODE_STROKE_WIDTH: f64 = 1.0;

// ---------------------------------------------------------------------------
// 文本定位(以字体级视觉盒 cap/logical bounds 为基准)
// ---------------------------------------------------------------------------

/// 水平锚点:以**排版盒**(advance 宽度,即 [`TextLayout::width`])为基准。
///
/// 刻意不用墨迹的水平边界:字形的左右侧边距(side bearing)因字符而异,
/// 且部分字形(如 `A`)的墨迹宽度甚至为 0、CJK 缺字形时会退化为负值。
/// 按墨迹左对齐会让多行文本参差不齐、居中会让不同文本左右晃动;
/// 按排版盒对齐才是排版学意义上的对齐。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HAnchor {
    /// 排版盒左边缘落在锚点 x(左对齐)。
    Left,
    /// 排版盒中心落在锚点 x(居中)。
    Center,
}

/// 垂直锚点:以**字体级视觉盒**为基准([`TextLayout::cap_bounds`] / [`TextLayout::logical_bounds`])。
///
/// 排版盒高度 [`TextLayout::height`] 含行距(leading)与字体的 ascent/descent
/// 设计边距,用它在固定高度的框/行内居中会让文本明显偏下。lievisual 0.3 起移除了
/// 逐字形墨迹盒(`ink_bounds`),改用字体级盒:居中 / 顶对齐取 **cap 盒**
/// (`baseline − cap_height → baseline`,字体级常量、不随文本内容跳动),底对齐取
/// **logical 盒**(含 descent,避免 `g`/`y`/`p`/`q` 下伸部被裁)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum VAnchor {
    /// 墨迹垂直中心落在锚点 y(框内 / 行内垂直居中)。
    InkMiddle,
    /// 墨迹顶边落在锚点 y。
    InkTop,
    /// 墨迹底边落在锚点 y。
    InkBottom,
    /// 字母基线落在锚点 y(等价于 `TextBaseline::Alphabetic`)。
    Baseline,
}

/// 按锚点定位文本,返回 [`SceneItem::Label`] 应使用的 `position`。
///
/// 同时把 `style` 的 align / baseline **归一为 `Left` / `Top`**:这两个值的
/// [`lievisual::text::compute_text_offset`] 恒为 `(0, 0)`,且与渲染端完全同源
/// (实测 SVG 输出的 `y` 与预测值偏差为 0)。反之若交给渲染端解释
/// `TextBaseline::Middle`,渲染端与 `compute_text_offset` 的结果并不一致
/// (见 [`VAnchor`])。归一之后,本函数返回的 position 即**排版盒左上角**,
/// 文本位置完全由调用方掌控,不再受后端对 baseline 的解释影响。
fn place_text(
    layout: &TextLayout,
    style: &mut TextStyle,
    anchor: Point,
    h: HAnchor,
    v: VAnchor,
) -> Point {
    style.align = TextAlign::Left;
    style.baseline = TextBaseline::Top;

    // lievisual 0.3 起移除逐字形墨迹盒:居中 / 顶对齐用字体级 cap 盒,底对齐用 logical 盒。
    let cb = layout.cap_bounds();
    let cap_h = cb.height().max(0.0);
    let x = match h {
        HAnchor::Left => anchor.x,
        HAnchor::Center => anchor.x - layout.width / 2.0,
    };
    let y = match v {
        // cap 盒退化(空白文本 / 缺字形)时回退到排版盒,避免除零与跳变。
        VAnchor::InkMiddle => {
            if cap_h > 0.0 {
                anchor.y - (cb.min_y() + cap_h / 2.0)
            } else {
                anchor.y - layout.height / 2.0
            }
        }
        VAnchor::InkTop => anchor.y - cb.min_y(),
        VAnchor::InkBottom => {
            let lb = layout.logical_bounds();
            if lb.height() > 0.0 {
                anchor.y - lb.max_y()
            } else {
                anchor.y - layout.height
            }
        }
        VAnchor::Baseline => anchor.y - layout_metrics(layout).alphabetic_baseline,
    };
    Point::new(x, y)
}

/// 返回文本首行的字体 metrics(ascent / descent / baseline / line_height)。
/// 用于基线对齐场景:取同行多列的最大值拼成公共行框。
fn line_metrics(layout: &TextLayout) -> LineMetrics {
    layout
        .lines
        .first()
        .map(|l| l.metrics)
        .unwrap_or_else(|| LineMetrics {
            line_height: 0.0,
            baseline: 0.0,
            block_min: 0.0,
            block_max: 0.0,
            content_block_min: 0.0,
            content_block_max: 0.0,
            cap_height: 0.0,
            x_height: 0.0,
        })
}

/// 文本配套背景框:水平取排版盒(宽度稳定)、垂直取 logical 盒(含 ascent/descent)。
///
/// `box_left_top` 为 [`place_text`] 的返回值(排版盒左上角)。
fn text_bg_rect(layout: &TextLayout, box_left_top: Point, pad_x: f64, pad_y: f64) -> Rect {
    let lb = layout.logical_bounds();
    let (top, bottom) = if lb.height() > 0.0 {
        (box_left_top.y + lb.min_y(), box_left_top.y + lb.max_y())
    } else {
        (box_left_top.y, box_left_top.y + layout.height)
    };
    Rect::new(
        box_left_top.x - pad_x,
        top - pad_y,
        box_left_top.x + layout.width + pad_x,
        bottom + pad_y,
    )
}

/// 几何 + 视觉意图 → 视觉自足的场景图。
pub fn run(gg: &Geograph, _style: &StyleIntent) -> SceneGraph {
    let mut items = Vec::new();

    // —— pie(Radial 家族):整体绘制(扇区 + 百分比标签 + 标题)——
    // PieSlice 节点存在即视为 pie,走专属渲染,不经过通用节点/边循环。
    let is_pie = gg
        .nodes
        .iter()
        .any(|n| matches!(n.detail, ir::common::NodeDetail::PieSlice { .. }));
    if is_pie {
        emit_pie(&mut items, gg);
        return SceneGraph {
            size: gg.size,
            background: gg.background,
            items,
        };
    }

    // —— gitgraph(Hierarchy 家族):整体绘制(提交点 + 分支线 + 合并曲线 + 标签)——
    let is_gitgraph = gg
        .nodes
        .iter()
        .any(|n| matches!(n.detail, ir::common::NodeDetail::GitCommit { .. }));
    if is_gitgraph {
        emit_gitgraph(&mut items, gg);
        return SceneGraph {
            size: gg.size,
            background: gg.background,
            items,
        };
    }

    // —— sequence(Sequence 家族):整体绘制(参与者盒 + 生命线 + 消息 + 备注 + 分组块)——
    // 参与者(Lifeline 节点)存在即视为 sequence,走专属渲染,不经过通用节点/边循环。
    let is_sequence = gg
        .nodes
        .iter()
        .any(|n| n.role == ir::common::NodeRole::Lifeline);
    if is_sequence {
        emit_sequence(&mut items, gg);
        return SceneGraph {
            size: gg.size,
            background: gg.background,
            items,
        };
    }

    // —— timeline(Linear 家族):整体绘制(标题 + 时间轴 + 点 + 块 + 连线)——
    // TimelineSection 节点不参与普通节点渲染(下方循环中跳过)。
    let is_timeline = gg
        .nodes
        .iter()
        .any(|n| matches!(n.detail, ir::common::NodeDetail::TimelineSection { .. }));
    if is_timeline {
        emit_timeline(&mut items, gg);
    }

    // —— 子图容器:背景 + 边框 + 标题(z 低于节点,保证节点覆盖其上)——
    // flowchart subgraph:`.cluster rect{fill:#ffffde;stroke:#aaaa33}`,标题在簇顶**居中**
    // (官方 golden `flowchart__subgraph`:label foreignObject 左缘 = 簇中心 - 文本宽/2)。
    // state 复合状态:官方双矩形 —— 外框 `.statediagram-cluster rect{fill:#ECECFF;
    // stroke:#9370DB}` + `rect.outer{rx:5}`,其下 26px 为标题行,内容区是
    // `.inner{fill:white;rx:0}` 白矩形(顶 26 / 底 4 内缩),标题居中于顶部。
    for c in &gg.containers {
        let r = c.bounds;
        let is_composite = c.kind == ir::common::ContainerKind::StateComposite;
        let (fill_color, stroke_color, title_pos) = if is_composite {
            (
                theme::flowchart::SUBGRAPH_FILL,
                theme::state::STROKE,
                Point::new(r.min_x() + r.width() / 2.0, r.min_y() + 13.0),
            )
        } else {
            (
                theme::flowchart::SUBGRAPH_FILL,
                theme::flowchart::SUBGRAPH_STROKE,
                Point::new(r.min_x() + r.width() / 2.0, r.min_y() + 12.0),
            )
        };
        let container_stroke = Stroke {
            color: stroke_color,
            width: 1.0,
            line_cap: LineCap::Butt,
            line_join: LineJoin::Miter,
            dash_array: Vec::new(),
            dash_offset: 0.0,
            miter_limit: 4.0,
        };
        items.push(SceneItem::Shape {
            geometry: ShapeGeometry::RoundedRect {
                at: Point::new(r.min_x(), r.min_y()),
                size: Size::new(r.width(), r.height()),
                // 官方 `.statediagram-cluster rect.outer{rx:5px}`;flowchart 簇为直角。
                radius: if is_composite { 5.0 } else { 0.0 },
            },
            fill: Some(Fill::Solid(fill_color)),
            stroke: Some(container_stroke.clone()),
            name: None,
            z: -1,
        });
        if is_composite {
            // 官方 inner 白矩形:标题行(26px)之下、底边上缩 4px 的内容区。
            let inner_top = r.min_y() + 26.0;
            let inner_h = (r.max_y() - 4.0 - inner_top).max(0.0);
            if inner_h > 0.0 {
                items.push(SceneItem::Shape {
                    geometry: ShapeGeometry::Rect {
                        at: Point::new(r.min_x(), inner_top),
                        size: Size::new(r.width(), inner_h),
                    },
                    fill: Some(Fill::Solid(lievisual::geometry::Color::WHITE)),
                    stroke: None,
                    name: None,
                    z: -1,
                });
            }
        }
        if let Some(title) = &c.title
            && !title.is_empty()
        {
            let mut title_style = theme::text_style(
                theme::TEXT_COLOR,
                theme::FONT_SIZE,
                TextAlign::Center,
                TextBaseline::Middle,
            );
            let spans = vec![RichSpan::new(title.clone(), title_style.clone())];
            let layout = layout_text(&spans, None);
            let position = place_text(
                &layout,
                &mut title_style,
                title_pos,
                HAnchor::Center,
                VAnchor::InkMiddle,
            );
            items.push(SceneItem::Label {
                text: spans,
                position,
                style: title_style,
                anchor: ir::scenegraph::Anchor::Left,
                z: theme::Z_BACKGROUND,
            });
        }
    }

    // —— 节点:形状 + 文本 ——
    for n in &gg.nodes {
        // 结构化节点(类框 / 实体框)走专用多栏绘制。
        // TimelineSection 由 emit_timeline 统一绘制(轴/点/块/连线);SequenceNote
        // 属 Sequence 家族,引擎尚未接入(阶段 2 进行中),先回退到普通节点渲染占位。
        match &n.detail {
            ir::common::NodeDetail::Class { .. } => {
                emit_class_box(&mut items, n);
                continue;
            }
            ir::common::NodeDetail::Entity { .. } => {
                emit_entity_box(&mut items, n);
                continue;
            }
            ir::common::NodeDetail::TimelineSection { .. } => continue,
            ir::common::NodeDetail::SequenceNote { .. } => {}
            // pie / gitgraph 由 emit_pie / emit_gitgraph 整体绘制(本循环不可达,仅补穷尽)。
            ir::common::NodeDetail::PieSlice { .. } => {}
            ir::common::NodeDetail::GitCommit { .. } => {}
            ir::common::NodeDetail::None => {}
        }
        // 节点填充/描边按形状语义取色(state 与 flowchart 同色系,此处统一用 flowchart 常量)。
        let (fill, stroke) = node_fill_stroke(n.shape);
        match n.shape {
            // 双环(EndDot / DoubleCircle):外圈描边 + 内圈实心小圆,各占一个 Shape。
            ShapeKind::EndDot | ShapeKind::DoubleCircle => {
                let outer = Stroke {
                    color: theme::state::STROKE,
                    width: 1.5,
                    line_cap: LineCap::Butt,
                    line_join: LineJoin::Miter,
                    dash_array: Vec::new(),
                    dash_offset: 0.0,
                    miter_limit: 4.0,
                };
                items.push(SceneItem::Shape {
                    geometry: ShapeGeometry::Ellipse {
                        center: n.center,
                        rx: n.size.width / 2.0,
                        ry: n.size.height / 2.0,
                    },
                    fill: None,
                    stroke: Some(outer),
                    name: None,
                    z: theme::Z_BACKGROUND,
                });
                // 内圈实心小圆。
                let inner_r = (n.size.width / 2.0) * 0.6;
                items.push(SceneItem::Shape {
                    geometry: ShapeGeometry::Ellipse {
                        center: n.center,
                        rx: inner_r,
                        ry: inner_r,
                    },
                    fill: Some(Fill::Solid(theme::state::STROKE)),
                    stroke: None,
                    name: None,
                    z: theme::Z_BACKGROUND,
                });
            }
            _ => {
                let geometry = shape_to_geometry(n.shape, n.center, n.size);
                items.push(SceneItem::Shape {
                    geometry,
                    fill: Some(fill),
                    stroke: Some(stroke.clone()),
                    name: None,
                    z: theme::Z_BACKGROUND,
                });
                // 官方 subroutine(`[[X]]`)= 内矩形 + 左右各一条外竖线
                // (golden polygon 同时勾廓内外两个矩形,外侧各外扩 8px)。
                if n.shape == ShapeKind::Subroutine {
                    let half_w = n.size.width / 2.0;
                    let half_h = n.size.height / 2.0;
                    for sx in [-1.0, 1.0] {
                        let x = n.center.x + sx * half_w;
                        items.push(SceneItem::Edge {
                            path: ir::geograph::line_route(&[
                                Point::new(x, n.center.y - half_h),
                                Point::new(x, n.center.y + half_h),
                            ]),
                            stroke: stroke.clone(),
                            ends: (EdgeEnds::None, EdgeEnds::None),
                            z: theme::Z_BACKGROUND,
                        });
                    }
                }
            }
        }

        // 节点文本(Bar / StartDot / EndDot 无文本)。
        if let Some(label) = &n.label
            && !label.text.is_empty()
            && !matches!(n.shape, ShapeKind::Bar)
        {
            let mut style = theme::text_style(
                theme::flowchart::TEXT,
                theme::FONT_SIZE,
                TextAlign::Center,
                TextBaseline::Middle,
            );
            let spans = label.spans.clone();
            let layout = layout_text(&spans, None);
            let position = place_text(
                &layout,
                &mut style,
                n.center,
                HAnchor::Center,
                VAnchor::InkMiddle,
            );
            items.push(SceneItem::Label {
                text: spans,
                position,
                style,
                anchor: ir::scenegraph::Anchor::Center,
                z: theme::Z_SERIES,
            });
        }
    }

    // —— 边 ——
    for e in &gg.edges {
        // 线型决定颜色 / 宽度 / 虚线样式(Flow=实线,Dotted=虚线,Thick=粗线,Invisible=透明)。
        let (color, width) = edge_style(e.kind, e.line_kind);
        let dash_array = match e.line_kind {
            ir::common::LineKind::Dotted => vec![3.0, 4.0],
            _ => Vec::new(),
        };
        let color = if e.line_kind == ir::common::LineKind::Invisible {
            Color::new(0, 0, 0, 0)
        } else {
            color
        };
        let stroke = Stroke {
            color,
            width,
            line_cap: LineCap::Butt,
            line_join: LineJoin::Miter,
            dash_array,
            dash_offset: 0.0,
            miter_limit: 4.0,
        };
        let ends = edge_ends(e.kind, e.arrow);
        items.push(SceneItem::Edge {
            path: e.route.clone(),
            stroke: stroke.clone(),
            ends,
            z: theme::Z_SUBGRAPH,
        });

        // ER 基数符号(source / target 端,沿「远离节点」方向排列)。
        let (cs, ct) = e.cardinality;
        if let Some(c) = cs {
            emit_cardinality(
                &mut items,
                e.route.start(),
                e.route.first_direction(),
                c,
                &stroke,
                1,
            );
        }
        if let Some(c) = ct {
            let d = e.route.last_direction();
            emit_cardinality(
                &mut items,
                e.route.end(),
                Point::new(-d.x, -d.y),
                c,
                &stroke,
                1,
            );
        }

        // class 基数文本("1" / "*" 等),在关系线两端一侧。
        if let Some(t) = &e.cardinality_text.0 {
            emit_cardinality_text(&mut items, e.route.start(), e.route.first_direction(), t, 2);
        }
        if let Some(t) = &e.cardinality_text.1 {
            let d = e.route.last_direction();
            emit_cardinality_text(&mut items, e.route.end(), Point::new(-d.x, -d.y), t, 2);
        }

        // 边标签背景:按官方各图类型 `.labelBkg` 规则取色(golden 实测)——
        // flowchart `rgba(232,232,232,0.5)`、ER `rgba(248.67,255,236,0.5)`、
        // class `#ECECFF` 不透明、**state 无 labelBkg 规则 → 透明不画底**。
        let label_bg = match e.kind {
            EdgeKind::StateTransition => None,
            EdgeKind::Flow => Some(theme::flowchart::EDGE_LABEL_BG),
            EdgeKind::Generic => Some(theme::er::EDGE_LABEL_BG),
            EdgeKind::ClassExtends
            | EdgeKind::ClassComposition
            | EdgeKind::ClassAggregation
            | EdgeKind::ClassAssociation
            | EdgeKind::ClassDependency
            | EdgeKind::ClassRealization
            | EdgeKind::ClassLink
            | EdgeKind::ClassDashed => Some(theme::class::EDGE_LABEL_BG),
            _ => Some(theme::flowchart::EDGE_LABEL_BG),
        };
        // 边标签:半透明彩底 + 居中文本(锚点来自 route 中点)。
        if let (Some(text), Some(anchor)) = (&e.label_text, &e.label_anchor)
            && !text.is_empty()
        {
            let mut ts = theme::text_style(
                theme::flowchart::TEXT,
                theme::FONT_SIZE,
                TextAlign::Center,
                TextBaseline::Middle,
            );
            let spans = vec![RichSpan::new(text.clone(), ts.clone())];
            let layout = layout_text(&spans, None);
            let position = place_text(
                &layout,
                &mut ts,
                *anchor,
                HAnchor::Center,
                VAnchor::InkMiddle,
            );
            if let Some(bg_color) = label_bg {
                // 背景框纵向紧贴**墨迹**(而非含行距的排版盒),否则 24px 行高
                // 会让底色块比 12px 的字高出一大截、且文字不居中。
                let bg = text_bg_rect(&layout, position, 4.0, 2.0);
                items.push(SceneItem::Shape {
                    geometry: ShapeGeometry::Rect {
                        at: Point::new(bg.min_x(), bg.min_y()),
                        size: Size::new(bg.width(), bg.height()),
                    },
                    fill: Some(Fill::Solid(bg_color)),
                    stroke: None,
                    name: Some("edge-label".to_string()),
                    z: theme::Z_SUBGRAPH,
                });
            }
            items.push(SceneItem::Label {
                text: spans,
                position,
                style: ts,
                anchor: ir::scenegraph::Anchor::Center,
                z: theme::Z_SERIES,
            });
        }
    }

    SceneGraph {
        size: gg.size,
        background: gg.background,
        items,
    }
}

// 类框 / 实体框绘制常量(与 measure 阶段 `measure_structured_label` 保持一致;
// 值必须同步,否则文本起点与测量框宽/列距不符。修改请两处同改)。
const CLASS_PAD: f64 = 12.0;
const ENTITY_PAD: f64 = 18.0;
/// 类图成员 / 类名字号(官方 CSS: g.classGroup text{font-size:10px})。
const SMALL_FONT: f64 = theme::class::MEMBER_FONT_SIZE;
const ATTR_LINE_H: f64 = 24.0;
/// 空栏占位高度(官方空类成员/方法栏各 18px)。
const SECTION_MIN_H: f64 = 18.0;
/// ER 实体属性 type 列与 name 列之间的间距。
const ER_ATTR_GAP: f64 = 32.0;

/// 绘制 ER 基数符号(`||` / `|o` / `}|` / `}o`)在边端点处。
/// `p` = 端点,`away` = 远离节点方向的单位向量,`card` = 基数类型。
fn emit_cardinality(
    items: &mut Vec<SceneItem>,
    p: Point,
    away: Point,
    card: ir::common::ErCardinality,
    stroke: &Stroke,
    z: i32,
) {
    use ir::common::ErCardinality::*;
    let perp = Point::new(-away.y, away.x);
    const SHORT_HALF: f64 = 4.0;
    const STEP: f64 = 6.0;
    let at = |idx: f64| Point::new(p.x + away.x * idx * STEP, p.y + away.y * idx * STEP);

    // 短线:沿 perp 方向、中心 `center`,半长 SHORT_HALF。
    let short = |items: &mut Vec<SceneItem>, center: Point| {
        let s = Point::new(
            center.x - perp.x * SHORT_HALF,
            center.y - perp.y * SHORT_HALF,
        );
        let e = Point::new(
            center.x + perp.x * SHORT_HALF,
            center.y + perp.y * SHORT_HALF,
        );
        items.push(SceneItem::Edge {
            path: ir::geograph::line_route(&[s, e]),
            stroke: stroke.clone(),
            ends: (EdgeEnds::None, EdgeEnds::None),
            z,
        });
    };
    // 空心圆:半径 3。
    let circle = |items: &mut Vec<SceneItem>, center: Point| {
        items.push(SceneItem::Shape {
            geometry: ShapeGeometry::Ellipse {
                center,
                rx: 3.0,
                ry: 3.0,
            },
            fill: None,
            stroke: Some(stroke.clone()),
            name: None,
            z,
        });
    };
    // 大括号 `}`:3 点折线(top/mid/bot),mid 沿 away 凸出。
    let brace = |items: &mut Vec<SceneItem>, center: Point| {
        let top = Point::new(center.x - perp.x * 4.0, center.y - perp.y * 4.0);
        let mid = Point::new(center.x + away.x * 3.5, center.y + away.y * 3.5);
        let bot = Point::new(center.x + perp.x * 4.0, center.y + perp.y * 4.0);
        items.push(SceneItem::Shape {
            geometry: ShapeGeometry::Polygon {
                points: vec![top, mid, bot],
            },
            fill: None,
            stroke: Some(stroke.clone()),
            name: None,
            z,
        });
    };

    match card {
        ExactlyOne => {
            short(items, at(0.0));
            short(items, at(1.0));
        }
        ZeroOrOne => {
            short(items, at(0.0));
            circle(items, at(1.0));
        }
        OneOrMany => {
            short(items, at(0.0));
            brace(items, at(1.0));
        }
        ZeroOrMany => {
            circle(items, at(0.0));
            brace(items, at(1.0));
        }
    }
}

/// 绘制 class 关系基数文本(`"1"` / `"*"` / `"many"` 等),放在关系线端点一侧。
fn emit_cardinality_text(items: &mut Vec<SceneItem>, p: Point, dir: Point, text: &str, z: i32) {
    // 沿垂直于边的方向偏移,避免压在关系线上。
    let perp = Point::new(-dir.y, dir.x);
    let pos = Point::new(p.x + perp.x * 12.0, p.y + perp.y * 12.0);
    // 用 theme::text_style 保证带官方行高,与 measure 阶段的排版盒一致。
    let mut ts = theme::text_style(
        theme::class::TEXT,
        theme::FONT_SIZE,
        TextAlign::Center,
        TextBaseline::Middle,
    );
    let spans = vec![RichSpan::new(text.to_string(), ts.clone())];
    let layout = layout_text(&spans, None);
    let position = place_text(&layout, &mut ts, pos, HAnchor::Center, VAnchor::InkMiddle);
    items.push(SceneItem::Label {
        text: spans,
        position,
        style: ts,
        anchor: ir::scenegraph::Anchor::Center,
        z,
    });
}

/// class 主题描边(官方 1px)。
fn class_stroke() -> Stroke {
    Stroke {
        color: theme::class::STROKE,
        width: 1.0,
        line_cap: LineCap::Butt,
        line_join: LineJoin::Miter,
        dash_array: Vec::new(),
        dash_offset: 0.0,
        miter_limit: 4.0,
    }
}

/// 绘制 UML 类框(三栏:header + attrs + methods)。
fn emit_class_box(items: &mut Vec<SceneItem>, n: &GGNode) {
    let half_w = n.size.width / 2.0;
    let half_h = n.size.height / 2.0;
    let rect = Rect::new(
        n.center.x - half_w,
        n.center.y - half_h,
        n.center.x + half_w,
        n.center.y + half_h,
    );
    let stroke = class_stroke();

    let ir::common::NodeDetail::Class {
        annotation,
        attrs,
        methods,
    } = &n.detail
    else {
        return;
    };
    let header_layout_h = n.label.as_ref().map(|l| l.layout.height).unwrap_or(20.0);
    // 注解占位高度必须与 measure 阶段公式一致(真实行高 + 4),不能硬编码:
    // 原实现写死 16.0,而 measure 用 `ann.layout.height + 4.0`(16px 字号行高 24 →
    // 28),导致分隔线位置与整框测量高度不匹配。
    let ann_extra_h = annotation
        .as_ref()
        .map(|a| {
            let ts = theme::text_style(
                theme::class::TEXT,
                SMALL_FONT,
                TextAlign::Left,
                TextBaseline::Top,
            );
            layout_text(&[RichSpan::new(format!("«{}»", a), ts)], None).height + 4.0
        })
        .unwrap_or(0.0);
    let ann_h = ann_extra_h;
    let header_h = header_layout_h + 24.0 + ann_h;
    let attr_h = if attrs.is_empty() {
        SECTION_MIN_H
    } else {
        attrs.len() as f64 * ATTR_LINE_H
    };

    // 整体背景(body 色) + header 背景(HEADER_FILL)。
    items.push(SceneItem::Shape {
        geometry: ShapeGeometry::Rect {
            at: Point::new(rect.min_x(), rect.min_y()),
            size: n.size,
        },
        fill: Some(Fill::Solid(theme::class::FILL)),
        stroke: Some(stroke.clone()),
        name: None,
        z: theme::Z_BACKGROUND,
    });
    items.push(SceneItem::Shape {
        geometry: ShapeGeometry::Rect {
            at: Point::new(rect.min_x(), rect.min_y()),
            size: Size::new(n.size.width, header_h),
        },
        fill: Some(Fill::Solid(theme::class::HEADER_FILL)),
        stroke: Some(stroke.clone()),
        name: None,
        z: theme::Z_SUBGRAPH,
    });

    // 注解(header 顶部)。
    if let Some(ann) = annotation {
        let mut ts = theme::text_style(
            theme::class::TEXT,
            SMALL_FONT,
            TextAlign::Center,
            TextBaseline::Middle,
        );
        let spans = vec![RichSpan::new(format!("«{}»", ann), ts.clone())];
        let layout = layout_text(&spans, None);
        let position = place_text(
            &layout,
            &mut ts,
            Point::new(n.center.x, rect.min_y() + 9.0),
            HAnchor::Center,
            VAnchor::InkMiddle,
        );
        items.push(SceneItem::Label {
            text: spans,
            position,
            style: ts,
            anchor: ir::scenegraph::Anchor::Center,
            z: theme::Z_SERIES,
        });
    }
    // 类名(header 居中,官方 10px + 加粗)。
    if let Some(label) = &n.label {
        let name_y = rect.min_y() + header_h / 2.0 + if annotation.is_some() { 6.0 } else { 0.0 };
        let mut ts = theme::text_style(
            theme::class::TEXT,
            SMALL_FONT,
            TextAlign::Center,
            TextBaseline::Middle,
        )
        .with_weight(FontWeight::Bold);
        let spans = label.spans.clone();
        let layout = layout_text(&spans, None);
        let position = place_text(
            &layout,
            &mut ts,
            Point::new(n.center.x, name_y),
            HAnchor::Center,
            VAnchor::InkMiddle,
        );
        items.push(SceneItem::Label {
            text: spans,
            position,
            style: ts,
            anchor: ir::scenegraph::Anchor::Center,
            z: theme::Z_SERIES,
        });
    }

    // 两条分隔线:名称栏底部 + 成员栏底部(官方恒画,即使成员/方法为空)。
    for dy in [rect.min_y() + header_h, rect.min_y() + header_h + attr_h] {
        items.push(SceneItem::Shape {
            geometry: ShapeGeometry::Rect {
                at: Point::new(rect.min_x(), dy),
                size: Size::new(n.size.width, 1.0),
            },
            fill: Some(Fill::Solid(theme::class::SEPARATOR)),
            stroke: None,
            name: None,
            z: theme::Z_SUBGRAPH,
        });
    }

    // attrs 行(左对齐;垂直居中于行高 ATTR_LINE_H,而非把行顶当排版盒顶)。
    let mut line_y = rect.min_y() + header_h + 4.0;
    for a in attrs {
        let mut ts = theme::text_style(
            theme::class::TEXT,
            SMALL_FONT,
            TextAlign::Left,
            TextBaseline::Top,
        );
        let spans = vec![RichSpan::new(a.clone(), ts.clone())];
        let layout = layout_text(&spans, None);
        let position = place_text(
            &layout,
            &mut ts,
            Point::new(rect.min_x() + CLASS_PAD, line_y + ATTR_LINE_H / 2.0),
            HAnchor::Left,
            VAnchor::InkMiddle,
        );
        items.push(SceneItem::Label {
            text: spans,
            position,
            style: ts,
            anchor: ir::scenegraph::Anchor::Left,
            z: theme::Z_SERIES,
        });
        line_y += ATTR_LINE_H;
    }

    // methods 行(左对齐,从成员栏分隔线下方开始)。
    line_y = rect.min_y() + header_h + attr_h + 4.0;
    for m in methods {
        let mut ts = theme::text_style(
            theme::class::TEXT,
            SMALL_FONT,
            TextAlign::Left,
            TextBaseline::Top,
        );
        let spans = vec![RichSpan::new(m.clone(), ts.clone())];
        let layout = layout_text(&spans, None);
        let position = place_text(
            &layout,
            &mut ts,
            Point::new(rect.min_x() + CLASS_PAD, line_y + ATTR_LINE_H / 2.0),
            HAnchor::Left,
            VAnchor::InkMiddle,
        );
        items.push(SceneItem::Label {
            text: spans,
            position,
            style: ts,
            anchor: ir::scenegraph::Anchor::Left,
            z: theme::Z_SERIES,
        });
        line_y += ATTR_LINE_H;
    }
}

/// 绘制 ER 实体框(两栏:header + attrs)。
fn emit_entity_box(items: &mut Vec<SceneItem>, n: &GGNode) {
    let half_w = n.size.width / 2.0;
    let half_h = n.size.height / 2.0;
    let rect = Rect::new(
        n.center.x - half_w,
        n.center.y - half_h,
        n.center.x + half_w,
        n.center.y + half_h,
    );
    let stroke = Stroke {
        color: theme::er::STROKE,
        width: 1.0,
        line_cap: LineCap::Butt,
        line_join: LineJoin::Miter,
        dash_array: Vec::new(),
        dash_offset: 0.0,
        miter_limit: 4.0,
    };

    let ir::common::NodeDetail::Entity { attrs } = &n.detail else {
        return;
    };
    let header_h = n.label.as_ref().map(|l| l.layout.height).unwrap_or(20.0) + 20.0;

    items.push(SceneItem::Shape {
        geometry: ShapeGeometry::Rect {
            at: Point::new(rect.min_x(), rect.min_y()),
            size: n.size,
        },
        fill: Some(Fill::Solid(theme::er::FILL)),
        stroke: Some(stroke.clone()),
        name: None,
        z: theme::Z_BACKGROUND,
    });
    // header 仅作填充块(不带描边),左右/上边描边由外层实体框负责,
    // 底边横线由下方独立分隔线绘制,避免 header 框底边与分隔线重叠导致
    // "看不到 field 分隔线"。
    items.push(SceneItem::Shape {
        geometry: ShapeGeometry::Rect {
            at: Point::new(rect.min_x(), rect.min_y()),
            size: Size::new(n.size.width, header_h),
        },
        fill: Some(Fill::Solid(theme::er::HEADER_FILL)),
        stroke: None,
        name: None,
        z: theme::Z_SUBGRAPH,
    });

    // 实体名(header 居中)。
    if let Some(label) = &n.label {
        let mut ts = theme::text_style(
            theme::er::TEXT,
            theme::FONT_SIZE,
            TextAlign::Center,
            TextBaseline::Middle,
        );
        let spans = label.spans.clone();
        let layout = layout_text(&spans, None);
        let position = place_text(
            &layout,
            &mut ts,
            Point::new(n.center.x, rect.min_y() + header_h / 2.0),
            HAnchor::Center,
            VAnchor::InkMiddle,
        );
        items.push(SceneItem::Label {
            text: spans,
            position,
            style: ts,
            anchor: ir::scenegraph::Anchor::Center,
            z: theme::Z_LABEL,
        });
    }

    // 属性分 type / name / constraint 三列(16px,与官方 ER 属性字号一致)。
    // ER 属性行使用基线对齐(方案一):style 的 baseline 设为 Alphabetic,
    // position.y 即文字基线 y,渲染端 dominant-baseline="alphabetic" 直接对应。
    let attr_ts = theme::text_style(
        theme::er::TEXT,
        theme::FONT_SIZE,
        TextAlign::Left,
        TextBaseline::Alphabetic,
    );
    let mut type_max = 0.0f64;
    let mut name_max = 0.0f64;
    let mut constraint_max = 0.0f64;
    for a in attrs {
        let tl = layout_text(&[RichSpan::new(a.type_.clone(), attr_ts.clone())], None);
        let nl = layout_text(&[RichSpan::new(a.name.clone(), attr_ts.clone())], None);
        type_max = type_max.max(tl.width);
        name_max = name_max.max(nl.width);
        if let Some(c) = &a.constraint {
            let cl = layout_text(&[RichSpan::new(c.clone(), attr_ts.clone())], None);
            constraint_max = constraint_max.max(cl.width);
        }
    }
    let type_x = rect.min_x() + ENTITY_PAD;
    let name_x = type_x + type_max + ER_ATTR_GAP;
    let constraint_x = if constraint_max > 0.0 {
        name_x + name_max + ER_ATTR_GAP
    } else {
        name_x
    };

    // 分栏线(官方 golden:header 与属性区之间的横线 + 各列之间的竖线,
    // 均为 `fill-rule="evenodd"` 的细分隔线)。
    let header_line_y = rect.min_y() + header_h;
    let divider_stroke = Stroke {
        color: theme::er::STROKE,
        width: 1.0,
        line_cap: LineCap::Butt,
        line_join: LineJoin::Miter,
        dash_array: Vec::new(),
        dash_offset: 0.0,
        miter_limit: 4.0,
    };

    // 各列之间的竖线(从 header 底延伸到底边),仅在有属性时绘制。z=3,
    // 使其位于所有行底横线之上,保持视觉上连续贯穿。
    if !attrs.is_empty() {
        let div1_x = name_x - ER_ATTR_GAP / 2.0;
        items.push(SceneItem::Edge {
            path: ir::geograph::line_route(&[
                Point::new(div1_x, header_line_y),
                Point::new(div1_x, rect.max_y()),
            ]),
            stroke: divider_stroke.clone(),
            ends: (EdgeEnds::None, EdgeEnds::None),
            z: theme::Z_LABEL,
        });
        if constraint_max > 0.0 {
            let div2_x = constraint_x - ER_ATTR_GAP / 2.0;
            items.push(SceneItem::Edge {
                path: ir::geograph::line_route(&[
                    Point::new(div2_x, header_line_y),
                    Point::new(div2_x, rect.max_y()),
                ]),
                stroke: divider_stroke.clone(),
                ends: (EdgeEnds::None, EdgeEnds::None),
                z: theme::Z_LABEL,
            });
        }
    }
    // header 底部横线(横跨整宽)。z=3,与竖线同层;先画横线再画竖线,
    // 交点处竖线覆盖横线,符合官方效果。
    items.push(SceneItem::Edge {
        path: ir::geograph::line_route(&[
            Point::new(rect.min_x(), header_line_y),
            Point::new(rect.max_x(), header_line_y),
        ]),
        stroke: divider_stroke.clone(),
        ends: (EdgeEnds::None, EdgeEnds::None),
        z: theme::Z_LABEL,
    });

    // attribute 行:斑马纹背景 + 每行底部横线 + 文字
    let mut line_y = rect.min_y() + header_h + 6.0;
    for (i, a) in attrs.iter().enumerate() {
        let row_top = line_y - 6.0;
        let row_bottom = row_top + ATTR_LINE_H;

        // 斑马纹行背景(整行宽度):第 1/3/5 行白色,第 2/4/6 行淡紫。
        let row_fill = if i % 2 == 0 {
            theme::er::ATTR_ROW_LIGHT
        } else {
            theme::er::ATTR_ROW_DARK
        };
        items.push(SceneItem::Shape {
            geometry: ShapeGeometry::Rect {
                at: Point::new(rect.min_x(), row_top),
                size: Size::new(rect.width(), row_bottom - row_top),
            },
            fill: Some(Fill::Solid(row_fill)),
            stroke: None,
            name: None,
            z: theme::Z_SUBGRAPH,
        });

        // 每行底部横线(横跨整宽),z=2,位于行背景之上、竖线之下。
        items.push(SceneItem::Edge {
            path: ir::geograph::line_route(&[
                Point::new(rect.min_x(), row_bottom),
                Point::new(rect.max_x(), row_bottom),
            ]),
            stroke: divider_stroke.clone(),
            ends: (EdgeEnds::None, EdgeEnds::None),
            z: theme::Z_SERIES,
        });

        // 同行多单元格:用"公共视觉中线"对齐,比各自 ink 居中更统一。
        // ink_cy_i 表示"若把排版盒左上角放在 y=0,该列文本的 ink 视觉中心 y"。
        // 取两列 ink_cy 的平均值为 common_cy,再把每个单元格的 ink 中心都对齐到
        // 方案一:公共行框 + 基线对齐(符合传统排版)。
        // 取同行各列各自的 ascent/descent 最大值拼成公共行框 common_height,
        // 在单元格内垂直居中该虚拟行框,基线落在 virtual_top + max_ascent。
        // 这样整行所有文本严格基线对齐、且整体在行内居中。
        let type_spans = vec![RichSpan::new(a.type_.clone(), attr_ts.clone())];
        let name_spans = vec![RichSpan::new(a.name.clone(), attr_ts.clone())];
        let type_layout = layout_text(&type_spans, None);
        let name_layout = layout_text(&name_spans, None);
        let constraint_layout = a
            .constraint
            .as_ref()
            .map(|c| layout_text(&[RichSpan::new(c.clone(), attr_ts.clone())], None));
        let max_ascent = [
            &type_layout,
            &name_layout,
            constraint_layout.as_ref().unwrap_or(&type_layout),
        ]
        .iter()
        .map(|l| line_metrics(l).ascent() as f64)
        .fold(0.0, f64::max);
        let max_descent = [
            &type_layout,
            &name_layout,
            constraint_layout.as_ref().unwrap_or(&type_layout),
        ]
        .iter()
        .map(|l| line_metrics(l).descent() as f64)
        .fold(0.0, f64::max);
        let common_height = max_ascent + max_descent;
        // 虚拟行框顶部 = 单元格垂直居中 common_height;基线 = 顶部 + max_ascent。
        let baseline_y = row_top + (ATTR_LINE_H - common_height) / 2.0 + max_ascent;

        let type_ts = attr_ts.clone();
        let name_ts = attr_ts.clone();
        items.push(SceneItem::Label {
            text: type_spans,
            position: Point::new(type_x, baseline_y),
            style: type_ts,
            anchor: ir::scenegraph::Anchor::Left,
            z: theme::Z_TITLE,
        });
        items.push(SceneItem::Label {
            text: name_spans,
            position: Point::new(name_x, baseline_y),
            style: name_ts,
            anchor: ir::scenegraph::Anchor::Left,
            z: theme::Z_TITLE,
        });
        if let Some(c) = &a.constraint {
            let constraint_ts = attr_ts.clone();
            let constraint_spans = vec![RichSpan::new(c.clone(), constraint_ts.clone())];
            items.push(SceneItem::Label {
                text: constraint_spans,
                position: Point::new(constraint_x, baseline_y),
                style: constraint_ts,
                anchor: ir::scenegraph::Anchor::Left,
                z: theme::Z_TITLE,
            });
        }

        line_y += ATTR_LINE_H;
    }
}

/// 官方 gitgraph 无显式 id 的提交标签为 `<序号>-<7位十六进制>`(每次渲染随机),
/// 此处用确定性 FNV-1a 由节点 id 派生同格式标签(渲染可复现)。
/// 例:`c0` → `0-28a41f8` 形态的 `<idx>-<7hex>`。
fn auto_commit_label(node_id: &str) -> String {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in node_id.as_bytes() {
        h ^= *b as u64;
        h = h.wrapping_mul(0x0000_0100_0000_01b3);
    }
    // splitmix64 收尾混合:短 id(c0/c1/...)的 FNV 前缀相近,avalanche 后
    // 低 28 位才分散得开(官方随机哈希观感)。
    h ^= h >> 30;
    h = h.wrapping_mul(0xbf58_476d_1ce4_e5b9);
    h ^= h >> 27;
    h = h.wrapping_mul(0x94d0_49bb_1331_11eb);
    h ^= h >> 31;
    let seq = node_id.trim_start_matches('c');
    format!("{seq}-{:07x}", h & 0x0fff_ffff)
}

/// 绘制 gitgraph 图表(Hierarchy 家族):提交点 + 分支线 + 合并曲线 + 标签。
///
/// 几何由 engine `hierarchy_geometry` 产生:提交按声明序沿 x 推进、分支按容器序映射到 y 行;
/// 边(child → parent)留空路由,此处据两端节点中心画水平线(同分支)或曲线(跨分支)。
fn emit_gitgraph(items: &mut Vec<SceneItem>, gg: &Geograph) {
    use ir::common::NodeDetail;
    use ir::geograph::RouteSegment;

    let node_by_id: HashMap<&str, &GGNode> = gg.nodes.iter().map(|n| (n.id.as_str(), n)).collect();
    // 分支列表(顺序 = 容器序,含 main)与行映射。
    let branches: Vec<(String, Vec<String>)> = gg
        .containers
        .iter()
        .filter(|c| c.kind == ir::common::ContainerKind::GitBranch)
        .map(|c| (c.title.clone().unwrap_or_default(), c.member_ids.clone()))
        .collect();
    let branch_row: HashMap<&str, usize> = branches
        .iter()
        .enumerate()
        .map(|(i, (n, _))| (n.as_str(), i))
        .collect();
    let branch_color = |name: &str| -> Color {
        let i = branch_row.get(name).copied().unwrap_or(0);
        theme::gitgraph::BRANCH_COLORS[i % theme::gitgraph::BRANCH_COLORS.len()]
    };
    let git_stroke = |color: Color, width: f64| Stroke {
        color,
        width,
        line_cap: LineCap::Butt,
        line_join: LineJoin::Miter,
        dash_array: Vec::new(),
        dash_offset: 0.0,
        miter_limit: 4.0,
    };
    let cr = theme::gitgraph::COMMIT_RADIUS;

    // —— 提交点(HIGHLIGHT 方框 / merge 白芯 / 普通实心)+ commit id 标签 + tag 标签 ——
    for n in &gg.nodes {
        let NodeDetail::GitCommit {
            branch,
            id,
            tag,
            commit_type,
            is_merge,
        } = &n.detail
        else {
            continue;
        };
        let color = branch_color(branch);
        let line_y = n.center.y;
        let is_highlight = commit_type.as_deref() == Some("HIGHLIGHT");
        if is_highlight {
            // HIGHLIGHT:深色外方框 + 浅色内方框(对齐官方 commit-highlight-outer / inner)。
            items.push(SceneItem::Shape {
                geometry: ShapeGeometry::Rect {
                    at: Point::new(n.center.x - 10.0, line_y - 10.0),
                    size: Size::new(20.0, 20.0),
                },
                fill: Some(Fill::Solid(theme::gitgraph::HIGHLIGHT_OUTER)),
                stroke: None,
                name: None,
                z: theme::Z_SUBGRAPH,
            });
            items.push(SceneItem::Shape {
                geometry: ShapeGeometry::Rect {
                    at: Point::new(n.center.x - 6.0, line_y - 6.0),
                    size: Size::new(12.0, 12.0),
                },
                fill: Some(Fill::Solid(theme::gitgraph::MERGE_INNER)),
                stroke: None,
                name: None,
                z: theme::Z_SUBGRAPH,
            });
        } else if *is_merge {
            // merge:分支色外圆 + 白芯(对齐官方 commit + commit-merge 双圆)。
            items.push(SceneItem::Shape {
                geometry: ShapeGeometry::Ellipse {
                    center: n.center,
                    rx: cr,
                    ry: cr,
                },
                fill: Some(Fill::Solid(color)),
                stroke: None,
                name: None,
                z: theme::Z_SUBGRAPH,
            });
            items.push(SceneItem::Shape {
                geometry: ShapeGeometry::Ellipse {
                    center: n.center,
                    rx: cr * 0.6,
                    ry: cr * 0.6,
                },
                fill: Some(Fill::Solid(theme::gitgraph::MERGE_INNER)),
                stroke: None,
                name: None,
                z: theme::Z_SUBGRAPH,
            });
        } else {
            items.push(SceneItem::Shape {
                geometry: ShapeGeometry::Ellipse {
                    center: n.center,
                    rx: cr,
                    ry: cr,
                },
                fill: Some(Fill::Solid(color)),
                stroke: None,
                name: None,
                z: theme::Z_SUBGRAPH,
            });
        }
        // commit id 标签:显式 id 优先;merge 无显式 id 不显示(官方 merge 无 id 时无 commit-label);
        // 普通提交无 id 时显示官方同格式的 `<序号>-<7位十六进制>` 自动哈希标签。
        let commit_label = id.clone().or_else(|| {
            if *is_merge {
                None
            } else {
                Some(auto_commit_label(&n.id))
            }
        });
        if let Some(text) = commit_label {
            let mut ts = theme::text_style(
                theme::gitgraph::COMMIT_LABEL_FILL,
                theme::gitgraph::LABEL_FONT,
                TextAlign::Center,
                TextBaseline::Alphabetic,
            );
            let spans = vec![RichSpan::new(text, ts.clone())];
            let layout = layout_text(&spans, None);
            let position = place_text(
                &layout,
                &mut ts,
                Point::new(n.center.x, line_y + 25.0),
                HAnchor::Center,
                VAnchor::Baseline,
            );
            // 淡黄背景(官方 .commit-label-bkg #ffffde @0.5),纵向紧贴墨迹。
            let bg = text_bg_rect(&layout, position, 2.0, 2.0);
            items.push(SceneItem::Shape {
                geometry: ShapeGeometry::Rect {
                    at: Point::new(bg.min_x(), bg.min_y()),
                    size: Size::new(bg.width(), bg.height()),
                },
                fill: Some(Fill::Solid(theme::gitgraph::COMMIT_LABEL_BKG)),
                stroke: None,
                name: None,
                z: theme::Z_BACKGROUND,
            });
            items.push(SceneItem::Label {
                text: spans,
                position,
                style: ts,
                anchor: ir::scenegraph::Anchor::Center,
                z: theme::Z_SERIES,
            });
        }
        // tag 标签:位于 commit 上方,灰色「左尖角矩形」背景(官方 tag 标签的简化),文字居中。
        if let Some(tag_text) = tag {
            let mut ts = theme::text_style(
                theme::gitgraph::TAG_LABEL_FILL,
                theme::gitgraph::LABEL_FONT,
                TextAlign::Center,
                TextBaseline::Alphabetic,
            );
            let spans = vec![RichSpan::new(tag_text.clone(), ts.clone())];
            let layout = layout_text(&spans, None);
            let position = place_text(
                &layout,
                &mut ts,
                Point::new(n.center.x, line_y - 16.0),
                HAnchor::Center,
                VAnchor::Baseline,
            );
            // 背景盒:主体矩形 + 左侧尖角(指向 commit 一侧),纵向紧贴墨迹(上下各留 ~2px)。
            let bg = text_bg_rect(&layout, position, 4.0, 2.0);
            let x_left = bg.min_x();
            let x_right = bg.max_x();
            let y_top = bg.min_y();
            let y_bottom = bg.max_y();
            let tip = 6.0;
            let cy = (y_top + y_bottom) / 2.0;
            items.push(SceneItem::Shape {
                geometry: ShapeGeometry::Polygon {
                    points: vec![
                        Point::new(x_left - tip, cy), // 左尖角
                        Point::new(x_left, y_top),
                        Point::new(x_right, y_top),
                        Point::new(x_right, y_bottom),
                        Point::new(x_left, y_bottom),
                    ],
                },
                fill: Some(Fill::Solid(theme::gitgraph::TAG_BKG)),
                stroke: Some(git_stroke(theme::gitgraph::TAG_BKG_STROKE, 1.0)),
                name: None,
                z: theme::Z_BACKGROUND,
            });
            items.push(SceneItem::Label {
                text: spans,
                position,
                style: ts,
                anchor: ir::scenegraph::Anchor::Center,
                z: theme::Z_SERIES,
            });
        }
    }

    // —— 分支线 / 合并曲线(边:child → parent)——
    // 跨分支采用「直线 → 圆角贝塞尔 → 直线」的平滑连接,控制点落在与目标对齐的平行线 / 水平线上,
    // 曲线凸向 child 方向(不向内凹):fork(child 在下)= 垂直下 → 弧(在 child 行平行线上
    // 对齐父 commit 点的控制点)→ 水平进 child;merge(child 在上)= 水平右 → 弧(在父行水平线
    // 上对齐 child commit 点的控制点)→ 垂直进 child(连线回到 commit)。
    let curve_r = theme::gitgraph::BRANCH_SPACING / 3.0;
    for e in &gg.edges {
        let (Some(child), Some(parent)) = (
            node_by_id.get(e.source.as_str()),
            node_by_id.get(e.target.as_str()),
        ) else {
            continue;
        };
        let (
            NodeDetail::GitCommit {
                branch: cb,
                is_merge: cm,
                ..
            },
            NodeDetail::GitCommit { branch: pb, .. },
        ) = (&child.detail, &parent.detail)
        else {
            continue;
        };
        if cb == pb {
            // 同分支:水平线(父分支色)。
            items.push(SceneItem::Edge {
                path: ir::geograph::line_route(&[parent.center, child.center]),
                stroke: git_stroke(branch_color(cb), theme::gitgraph::LINE_WIDTH),
                ends: (EdgeEnds::None, EdgeEnds::None),
                z: theme::Z_BACKGROUND,
            });
        } else {
            // 跨分支:颜色 = fork 用子分支色、merge 用父分支色(对齐官方箭头)。
            let color = if *cm {
                branch_color(pb)
            } else {
                branch_color(cb)
            };
            let (pc, cc) = (parent.center, child.center);
            let mut path = ir::geograph::RoutePath::new();
            if cc.y >= pc.y {
                // fork:父(上)→ 垂直下 → 弧(控制点 = child 行平行线上对齐父 commit 点)
                // → 水平进 child(下)。曲线先落到 child 行的平行线上,再平滑弯向水平进 child。
                let a = Point::new(pc.x, cc.y - curve_r);
                let p1 = Point::new(pc.x, cc.y); // 平行线(child 行)上对齐父 commit 点
                let p2 = Point::new((cc.x - curve_r).max(pc.x), cc.y); // 平行线上 child 左侧,保证水平入
                path.push(RouteSegment::Line { from: pc, to: a });
                path.push(RouteSegment::CubicBezier {
                    p0: a,
                    p1,
                    p2,
                    p3: cc,
                });
            } else {
                // merge:父(下)→ 水平右 → 弧(控制点 = 父行水平线上对齐 child commit 点)
                // → 垂直进 child(上)。曲线先沿水平线走到 child 正下方,再垂直连线回到 commit。
                let a = Point::new(cc.x - curve_r, pc.y);
                let p1 = Point::new(cc.x, pc.y); // 水平线(父行)上对齐 child commit 点
                let p2 = Point::new(cc.x, (pc.y - curve_r).max(cc.y)); // child 列上 commit 下方,保证垂直入
                path.push(RouteSegment::Line { from: pc, to: a });
                path.push(RouteSegment::CubicBezier {
                    p0: a,
                    p1,
                    p2,
                    p3: cc,
                });
            }
            items.push(SceneItem::Edge {
                path,
                stroke: git_stroke(color, theme::gitgraph::LINE_WIDTH),
                ends: (EdgeEnds::None, EdgeEnds::None),
                z: theme::Z_BACKGROUND,
            });
        }
    }

    // —— 分支虚线(每行贯穿,标识分支平行状态)——
    let min_x = gg
        .nodes
        .iter()
        .map(|n| n.center.x)
        .fold(f64::INFINITY, f64::min);
    let max_x = gg
        .nodes
        .iter()
        .map(|n| n.center.x)
        .fold(f64::NEG_INFINITY, f64::max);
    let branch_dash = Stroke {
        color: Color::new(51, 51, 51, 255), // #333(对齐官方 .branch stroke)
        width: 1.0,
        line_cap: LineCap::Butt,
        line_join: LineJoin::Miter,
        dash_array: vec![2.0, 2.0],
        dash_offset: 0.0,
        miter_limit: 4.0,
    };

    // —— 分支标签块 + 尾部延伸线 ——
    for (i, (name, members)) in branches.iter().enumerate() {
        let color = theme::gitgraph::BRANCH_COLORS[i % theme::gitgraph::BRANCH_COLORS.len()];
        let y = theme::gitgraph::TOP_MARGIN + i as f64 * theme::gitgraph::BRANCH_SPACING;
        // 分支行虚线(贯穿内容区,标识该分支的平行轨道)。
        items.push(SceneItem::Edge {
            path: ir::geograph::line_route(&[
                Point::new(min_x - 10.0, y),
                Point::new(max_x + 40.0, y),
            ]),
            stroke: branch_dash.clone(),
            ends: (EdgeEnds::None, EdgeEnds::None),
            z: theme::Z_BACKGROUND,
        });
        let mut ts_label = theme::text_style(
            Color::rgb(255, 255, 255),
            theme::FONT_SIZE,
            TextAlign::Center,
            TextBaseline::Middle,
        );
        let spans = vec![RichSpan::new(name.clone(), ts_label.clone())];
        let layout = layout_text(&spans, None);
        let pad_x = 12.0;
        let pad_y = 6.0;
        let lw = layout.width + pad_x * 2.0;
        // 色块高度按 **logical 盒**(ascent + descent,而非含行距的排版盒),
        // 避免标签块过高,且文字在块内居中。
        let logical_h = layout.logical_bounds().height();
        let lh = if logical_h > 0.0 {
            logical_h
        } else {
            layout.height
        } + pad_y * 2.0;
        let lx = theme::gitgraph::LEFT_MARGIN - lw - 16.0;
        let ly = y - lh / 2.0;
        let label_pos = place_text(
            &layout,
            &mut ts_label,
            Point::new(lx + lw / 2.0, y),
            HAnchor::Center,
            VAnchor::InkMiddle,
        );
        items.push(SceneItem::Shape {
            geometry: ShapeGeometry::RoundedRect {
                at: Point::new(lx, ly),
                size: Size::new(lw, lh),
                radius: 4.0,
            },
            fill: Some(Fill::Solid(color)),
            stroke: Some(git_stroke(color, 1.0)),
            name: None,
            z: theme::Z_BACKGROUND,
        });
        items.push(SceneItem::Label {
            text: spans,
            position: label_pos,
            style: ts_label,
            anchor: ir::scenegraph::Anchor::Center,
            z: theme::Z_SERIES,
        });
        // 分支尾部延伸线(最后一个提交之后)。
        if let Some(last_id) = members.last()
            && let Some(last) = node_by_id.get(last_id.as_str())
        {
            items.push(SceneItem::Edge {
                path: ir::geograph::line_route(&[
                    Point::new(last.center.x + cr + 4.0, y),
                    Point::new(last.center.x + cr + 40.0, y),
                ]),
                stroke: git_stroke(Color::new(180, 180, 180, 255), 1.0),
                ends: (EdgeEnds::None, EdgeEnds::None),
                z: theme::Z_BACKGROUND,
            });
        }
    }
}

/// 绘制 pie 图表(Radial 家族):扇区(从 12 点方向顺时针)+ 百分比标签 + 标题。
///
/// 所有扇区共享圆心(原点),半径固定;fit_to_canvas 负责整体居中缩放。
fn emit_pie(items: &mut Vec<SceneItem>, gg: &Geograph) {
    let mut data: Vec<(String, f64)> = Vec::new();
    for n in &gg.nodes {
        if let ir::common::NodeDetail::PieSlice { label, value } = &n.detail {
            data.push((label.clone(), *value));
        }
    }
    if data.is_empty() {
        return;
    }
    let total: f64 = data.iter().map(|(_, v)| v).sum();
    if total <= 0.0 {
        return;
    }
    let center = Point::new(0.0, 0.0);
    let radius = theme::pie::RADIUS;

    // 标题(官方:`<text x="0" y="-200" class="pieTitleText">`,圆心正上方)。
    // 官方 `.pieTitleText` 用默认字母基线(`position.y` 即基线),故用 Alphabetic;
    // 若用 Top,渲染时基线会被下移一个 ascent,标题更靠近圆心而压到饼图。
    if let Some(title) = &gg.title
        && !title.is_empty()
    {
        let mut ts = theme::text_style(
            Color::BLACK,
            theme::pie::TITLE_FONT,
            TextAlign::Center,
            TextBaseline::Alphabetic,
        );
        let spans = vec![RichSpan::new(title.clone(), ts.clone())];
        let layout = layout_text(&spans, None);
        let position = place_text(
            &layout,
            &mut ts,
            Point::new(center.x, center.y - theme::pie::TITLE_DY),
            HAnchor::Center,
            VAnchor::Baseline,
        );
        items.push(SceneItem::Label {
            text: spans,
            position,
            style: ts,
            anchor: ir::scenegraph::Anchor::Center,
            z: theme::Z_SERIES,
        });
    }

    // 外圈(官方 `<circle r="186" class="pieOuterCircle"/>`:黑描边、无填充)。
    items.push(SceneItem::Shape {
        geometry: ShapeGeometry::Ellipse {
            center,
            rx: theme::pie::OUTER_RADIUS,
            ry: theme::pie::OUTER_RADIUS,
        },
        fill: None,
        stroke: Some(Stroke {
            color: theme::pie::OUTER_STROKE,
            width: theme::pie::OUTER_STROKE_WIDTH,
            line_cap: LineCap::Butt,
            line_join: LineJoin::Miter,
            dash_array: Vec::new(),
            dash_offset: 0.0,
            miter_limit: 4.0,
        }),
        name: None,
        z: theme::Z_SUBGRAPH,
    });

    // 扇区分隔线:官方 `.pieCircle{stroke:black;stroke-width:2px}`(黑描边勾出
    // 每个扇区的两条半径边与外弧,切分情况一目了然)。
    let slice_stroke = Stroke {
        color: theme::pie::SLICE_STROKE,
        width: theme::pie::SLICE_STROKE_WIDTH,
        line_cap: LineCap::Butt,
        line_join: LineJoin::Miter,
        dash_array: Vec::new(),
        dash_offset: 0.0,
        miter_limit: 4.0,
    };
    let slice_ts = theme::text_style(
        Color::BLACK,
        theme::pie::LABEL_FONT,
        TextAlign::Center,
        TextBaseline::Middle,
    );

    // 各扇区:从 12 点钟方向(-π/2)顺时针推进。
    let mut start = -std::f64::consts::FRAC_PI_2;
    for (idx, (_label, value)) in data.iter().enumerate() {
        let sweep = 2.0 * std::f64::consts::PI * value / total;
        let color = theme::pie::COLORS[idx % theme::pie::COLORS.len()];
        // ShapeGeometry::Pie 的第 4 字段即 sweep 角(paint 直传 Element::pie)。
        items.push(SceneItem::Shape {
            geometry: ShapeGeometry::Pie {
                center,
                radius,
                start_angle: start,
                end_angle: sweep,
            },
            fill: Some(Fill::Solid(color)),
            stroke: Some(slice_stroke.clone()),
            name: None,
            z: theme::Z_BACKGROUND,
        });

        // 扇区标签:官方只放**百分比**(`40%`),名称交给右侧图例。
        let mid = start + sweep / 2.0;
        let lr = radius * theme::pie::LABEL_RADIUS_RATIO;
        let lp = Point::new(center.x + lr * mid.cos(), center.y + lr * mid.sin());
        let pct = format!("{}%", (value / total * 100.0).round() as i64);
        let mut pct_ts = slice_ts.clone();
        let spans = vec![RichSpan::new(pct, pct_ts.clone())];
        let layout = layout_text(&spans, None);
        let position = place_text(
            &layout,
            &mut pct_ts,
            lp,
            HAnchor::Center,
            VAnchor::InkMiddle,
        );
        items.push(SceneItem::Label {
            text: spans,
            position,
            style: pct_ts,
            anchor: ir::scenegraph::Anchor::Center,
            z: theme::Z_SERIES,
        });

        start += sweep;
    }

    // 图例(官方 `<g class="legend" transform="translate(216, y)">`:色块 + 名称,
    // 竖直居中排布;`showData` 时名称后附 `[数值]`)。
    let n = data.len() as f64;
    let legend_x = center.x + radius + theme::pie::LEGEND_DX;
    let legend_top = center.y - (n - 1.0) / 2.0 * theme::pie::LEGEND_ROW_H;
    let legend_ts = theme::text_style(
        Color::BLACK,
        theme::pie::LABEL_FONT,
        TextAlign::Left,
        TextBaseline::Middle,
    );
    for (idx, (label, value)) in data.iter().enumerate() {
        let color = theme::pie::COLORS[idx % theme::pie::COLORS.len()];
        let row_y = legend_top + idx as f64 * theme::pie::LEGEND_ROW_H;
        let swatch_top = row_y - theme::pie::LEGEND_SWATCH / 2.0;
        items.push(SceneItem::Shape {
            geometry: ShapeGeometry::Rect {
                at: Point::new(legend_x, swatch_top),
                size: Size::new(theme::pie::LEGEND_SWATCH, theme::pie::LEGEND_SWATCH),
            },
            fill: Some(Fill::Solid(color)),
            stroke: Some(Stroke {
                color,
                width: 1.0,
                line_cap: LineCap::Butt,
                line_join: LineJoin::Miter,
                dash_array: Vec::new(),
                dash_offset: 0.0,
                miter_limit: 4.0,
            }),
            name: None,
            z: theme::Z_SUBGRAPH,
        });
        let text = if gg.show_data {
            format!("{} [{}]", label, *value as i64)
        } else {
            label.clone()
        };
        let mut ts = legend_ts.clone();
        let spans = vec![RichSpan::new(text, ts.clone())];
        let layout = layout_text(&spans, None);
        let position = place_text(
            &layout,
            &mut ts,
            Point::new(legend_x + theme::pie::LEGEND_TEXT_DX, row_y),
            HAnchor::Left,
            VAnchor::InkMiddle,
        );
        items.push(SceneItem::Label {
            text: spans,
            position,
            style: ts,
            anchor: ir::scenegraph::Anchor::Left,
            z: theme::Z_SERIES,
        });
    }
}

/// 绘制 sequence 图表(Sequence 家族):参与者盒 + 生命线 + 消息箭头 + 备注 + 分组块。
fn emit_sequence(items: &mut Vec<SceneItem>, gg: &Geograph) {
    let lifelines: Vec<&GGNode> = gg
        .nodes
        .iter()
        .filter(|n| n.role == ir::common::NodeRole::Lifeline)
        .collect();
    if lifelines.is_empty() {
        return;
    }

    // 生命线底端:最后一行消息 / 备注之下。
    let msg_bottom = gg
        .edges
        .iter()
        .flat_map(|e| e.route.anchors())
        .map(|p| p.y)
        .fold(0.0f64, f64::max);
    let note_bottom = gg
        .nodes
        .iter()
        .filter(|n| matches!(n.detail, ir::common::NodeDetail::SequenceNote { .. }))
        .map(|n| n.center.y + n.size.height / 2.0)
        .fold(0.0f64, f64::max);
    // 官方 golden:最后一条消息线 y=199、底部 actor 盒 y=219,间距 20。
    // 生命线止于底部盒上沿,底部盒在 content_bottom 处。
    let content_bottom = msg_bottom.max(note_bottom) + 20.0;

    // 生命线:与参与者描边同色的细虚线。
    let lifeline_stroke = Stroke {
        color: theme::sequence::LIFELINE,
        width: theme::sequence::LIFELINE_WIDTH,
        line_cap: LineCap::Butt,
        line_join: LineJoin::Miter,
        dash_array: theme::sequence::LIFELINE_DASH.to_vec(),
        dash_offset: 0.0,
        miter_limit: 4.0,
    };

    // —— 参与者盒 + 生命线 ——
    for n in &lifelines {
        let half_w = n.size.width / 2.0;
        let half_h = n.size.height / 2.0;
        let rect = Rect::new(
            n.center.x - half_w,
            n.center.y - half_h,
            n.center.x + half_w,
            n.center.y + half_h,
        );
        // 官方 golden:`<rect fill="#eaeaea" stroke="#666" rx="3" ry="3" class="actor"/>`。
        items.push(SceneItem::Shape {
            geometry: ShapeGeometry::RoundedRect {
                at: Point::new(rect.min_x(), rect.min_y()),
                size: n.size,
                radius: theme::sequence::ACTOR_RADIUS,
            },
            fill: Some(Fill::Solid(theme::sequence::ACTOR_FILL)),
            stroke: Some(Stroke {
                color: theme::sequence::ACTOR_STROKE,
                width: 1.0,
                line_cap: LineCap::Butt,
                line_join: LineJoin::Miter,
                dash_array: Vec::new(),
                dash_offset: 0.0,
                miter_limit: 4.0,
            }),
            name: None,
            z: theme::Z_BACKGROUND,
        });
        if let Some(label) = &n.label {
            let mut ts = theme::text_style(
                theme::sequence::ACTOR_TEXT,
                theme::FONT_SIZE,
                TextAlign::Center,
                TextBaseline::Middle,
            );
            let spans = label.spans.clone();
            let layout = layout_text(&spans, None);
            let position = place_text(
                &layout,
                &mut ts,
                n.center,
                HAnchor::Center,
                VAnchor::InkMiddle,
            );
            items.push(SceneItem::Label {
                text: spans,
                position,
                style: ts,
                anchor: ir::scenegraph::Anchor::Center,
                z: theme::Z_SERIES,
            });
        }
        // 生命线(单条虚线,从顶部盒底向下延伸到底部盒上沿)。
        items.push(SceneItem::Edge {
            path: ir::geograph::line_route(&[
                Point::new(n.center.x, n.center.y + half_h),
                Point::new(n.center.x, content_bottom),
            ]),
            stroke: lifeline_stroke.clone(),
            ends: (EdgeEnds::None, EdgeEnds::None),
            z: theme::Z_BACKGROUND,
        });
    }

    // —— 底部参与者盒(官方 `<rect class="actor actor-bottom">`,位于生命线终点)——
    for n in &lifelines {
        let half_w = n.size.width / 2.0;
        let bottom_y = content_bottom;
        items.push(SceneItem::Shape {
            geometry: ShapeGeometry::RoundedRect {
                at: Point::new(n.center.x - half_w, bottom_y),
                size: n.size,
                radius: theme::sequence::ACTOR_RADIUS,
            },
            fill: Some(Fill::Solid(theme::sequence::ACTOR_FILL)),
            stroke: Some(Stroke {
                color: theme::sequence::ACTOR_STROKE,
                width: 1.0,
                line_cap: LineCap::Butt,
                line_join: LineJoin::Miter,
                dash_array: Vec::new(),
                dash_offset: 0.0,
                miter_limit: 4.0,
            }),
            name: None,
            z: theme::Z_BACKGROUND,
        });
        if let Some(label) = &n.label {
            let mut ts = theme::text_style(
                theme::sequence::ACTOR_TEXT,
                theme::FONT_SIZE,
                TextAlign::Center,
                TextBaseline::Middle,
            );
            let spans = label.spans.clone();
            let layout = layout_text(&spans, None);
            let position = place_text(
                &layout,
                &mut ts,
                Point::new(n.center.x, bottom_y + n.size.height / 2.0),
                HAnchor::Center,
                VAnchor::InkMiddle,
            );
            items.push(SceneItem::Label {
                text: spans,
                position,
                style: ts,
                anchor: ir::scenegraph::Anchor::Center,
                z: theme::Z_SERIES,
            });
        }
    }

    // —— 激活条(`A->>+B` / `A-->>-B`):官方 `<rect fill="#EDF2AE" stroke="#666" width="10"/>` ——
    for a in &gg.activations {
        let y0 = a.y0.min(a.y1);
        let y1 = a.y0.max(a.y1);
        if (y1 - y0).abs() < 1.0 {
            continue;
        }
        items.push(SceneItem::Shape {
            geometry: ShapeGeometry::Rect {
                at: Point::new(a.x - theme::sequence::ACTIVATION_WIDTH / 2.0, y0),
                size: Size::new(theme::sequence::ACTIVATION_WIDTH, y1 - y0),
            },
            fill: Some(Fill::Solid(theme::sequence::ACTIVATION_FILL)),
            stroke: Some(Stroke {
                color: theme::sequence::ACTIVATION_STROKE,
                width: 1.0,
                line_cap: LineCap::Butt,
                line_join: LineJoin::Miter,
                dash_array: Vec::new(),
                dash_offset: 0.0,
                miter_limit: 4.0,
            }),
            name: None,
            z: theme::Z_BACKGROUND,
        });
    }

    // —— 消息边:水平线 + 箭头 + 标签 ——
    for e in &gg.edges {
        let (color, _w) = edge_style(e.kind, e.line_kind);
        // 官方 golden:消息线 `stroke-width="2"`,虚线消息 `stroke-dasharray: 3, 3`。
        let width = theme::sequence::MESSAGE_WIDTH;
        let dash_array = match e.line_kind {
            ir::common::LineKind::Dotted => theme::sequence::MESSAGE_DASH.to_vec(),
            _ => Vec::new(),
        };
        let stroke = Stroke {
            color,
            width,
            line_cap: LineCap::Butt,
            line_join: LineJoin::Miter,
            dash_array,
            dash_offset: 0.0,
            miter_limit: 4.0,
        };
        let ends = edge_ends(e.kind, e.arrow);
        items.push(SceneItem::Edge {
            path: e.route.clone(),
            stroke: stroke.clone(),
            ends,
            z: theme::Z_SUBGRAPH,
        });
        if let (Some(text), Some(anchor)) = (&e.label_text, &e.label_anchor)
            && !text.is_empty()
        {
            let mut ts = theme::text_style(
                theme::sequence::TEXT,
                theme::FONT_SIZE,
                TextAlign::Center,
                TextBaseline::Bottom,
            );
            let spans = vec![RichSpan::new(text.clone(), ts.clone())];
            let layout = layout_text(&spans, None);
            let position = place_text(
                &layout,
                &mut ts,
                *anchor,
                HAnchor::Center,
                VAnchor::InkBottom,
            );
            items.push(SceneItem::Label {
                text: spans,
                position,
                style: ts,
                anchor: ir::scenegraph::Anchor::Center,
                z: theme::Z_SERIES,
            });
        }
    }

    // —— 备注盒 ——
    for n in &gg.nodes {
        let ir::common::NodeDetail::SequenceNote { text, .. } = &n.detail else {
            continue;
        };
        let half_w = n.size.width / 2.0;
        let half_h = n.size.height / 2.0;
        let rect = Rect::new(
            n.center.x - half_w,
            n.center.y - half_h,
            n.center.x + half_w,
            n.center.y + half_h,
        );
        items.push(SceneItem::Shape {
            // 官方备注框为直角矩形(`<rect ... class="note"/>` 无 rx)。
            geometry: ShapeGeometry::Rect {
                at: Point::new(rect.min_x(), rect.min_y()),
                size: n.size,
            },
            fill: Some(Fill::Solid(theme::sequence::NOTE_FILL)),
            stroke: Some(Stroke {
                color: theme::sequence::NOTE_STROKE,
                width: 1.0,
                line_cap: LineCap::Butt,
                line_join: LineJoin::Miter,
                dash_array: Vec::new(),
                dash_offset: 0.0,
                miter_limit: 4.0,
            }),
            name: None,
            z: theme::Z_BACKGROUND,
        });
        let mut ts = theme::text_style(
            theme::sequence::NOTE_TEXT,
            theme::FONT_SIZE,
            TextAlign::Center,
            TextBaseline::Middle,
        );
        let spans = vec![RichSpan::new(text.clone(), ts.clone())];
        let layout = layout_text(&spans, None);
        let position = place_text(
            &layout,
            &mut ts,
            n.center,
            HAnchor::Center,
            VAnchor::InkMiddle,
        );
        items.push(SceneItem::Label {
            text: spans,
            position,
            style: ts,
            anchor: ir::scenegraph::Anchor::Center,
            z: theme::Z_SERIES,
        });
    }

    // —— 分组块边框 + 标签(loop / alt / opt / par) ——
    for c in &gg.containers {
        if c.kind != ir::common::ContainerKind::SequenceBlock {
            continue;
        }
        let r = c.bounds;
        // 官方 golden 计算样式:`.loopLine{stroke-width:2px;stroke-dasharray:2,2;stroke:#9370DB}`。
        let stroke = Stroke {
            color: theme::sequence::BLOCK_STROKE,
            width: 2.0,
            line_cap: LineCap::Butt,
            line_join: LineJoin::Miter,
            dash_array: vec![2.0, 2.0],
            dash_offset: 0.0,
            miter_limit: 4.0,
        };
        items.push(SceneItem::Shape {
            geometry: ShapeGeometry::RoundedRect {
                at: Point::new(r.min_x(), r.min_y()),
                size: Size::new(r.width(), r.height()),
                radius: theme::NODE_RADIUS,
            },
            fill: None,
            stroke: Some(stroke),
            name: None,
            z: -1,
        });
        if let Some(label) = &c.title {
            // 官方把标签拆成两段文本:`loop` + `[Each item]`(并列排布,非合并为
            // `loop [Each item]`),且关键字置于左上角的 labelBox 小tab内
            // (golden:`<polygon points="64,75 114,75 114,88 105.6,95 64,95"
            // class="labelBox"/>`,fill #ECECFF / stroke #9370DB,右下角斜切)。
            let (head, tail) = split_block_label(label);
            let head_ts = theme::text_style(
                theme::sequence::BLOCK_TEXT,
                theme::FONT_SIZE,
                TextAlign::Left,
                TextBaseline::Alphabetic,
            );
            let head_layout = layout_text(&[RichSpan::new(head.clone(), head_ts.clone())], None);
            // tab 宽 = 关键字文本宽 + 左右各 10(官方 "loop" ≈30 宽 → tab 50)。
            let tab_w = (head_layout.width + 20.0).max(40.0);
            let tab_x = r.min_x();
            let tab_y = r.min_y();
            let tab_h = 20.0;
            let chamfer_x = 8.4;
            let chamfer_y = 7.0;
            items.push(SceneItem::Shape {
                geometry: ShapeGeometry::Polygon {
                    points: vec![
                        Point::new(tab_x, tab_y),
                        Point::new(tab_x + tab_w, tab_y),
                        Point::new(tab_x + tab_w, tab_y + tab_h - chamfer_y),
                        Point::new(tab_x + tab_w - chamfer_x, tab_y + tab_h),
                        Point::new(tab_x, tab_y + tab_h),
                    ],
                },
                fill: Some(Fill::Solid(theme::sequence::BLOCK_FILL)),
                stroke: Some(Stroke {
                    color: theme::sequence::BLOCK_STROKE,
                    width: 1.0,
                    line_cap: LineCap::Butt,
                    line_join: LineJoin::Miter,
                    dash_array: Vec::new(),
                    dash_offset: 0.0,
                    miter_limit: 4.0,
                }),
                name: None,
                z: -1,
            });
            // 关键字文本:tab 内水平居中,基线距 tab 顶 13(官方 text y=88 = tab 顶 75 + 13)。
            let baseline_y = tab_y + 13.0;
            items.push(SceneItem::Label {
                text: vec![RichSpan::new(head, head_ts.clone())],
                position: Point::new(tab_x + tab_w / 2.0, baseline_y),
                style: head_ts.clone(),
                anchor: ir::scenegraph::Anchor::Center,
                z: theme::Z_BACKGROUND,
            });
            // 方括号描述段:紧随 tab 右侧(官方为独立 loopText 文本)。
            if let Some(tail) = tail {
                items.push(SceneItem::Label {
                    text: vec![RichSpan::new(tail, head_ts.clone())],
                    position: Point::new(tab_x + tab_w + 6.0, baseline_y),
                    style: head_ts,
                    anchor: ir::scenegraph::Anchor::Left,
                    z: theme::Z_BACKGROUND,
                });
            }
        }
    }

    // —— 分支分隔线(alt 的 else / par 的 and / critical 的 option)——
    // 与官方结构对齐:横贯块宽的虚线(loopLine + dasharray 3,3)+ 块内居中的
    // 分支标题(sectionTitle,文本已含方括号)。
    for d in &gg.sequence_dividers {
        let Some(c) = gg.containers.iter().find(|c| c.id == d.block_id) else {
            continue;
        };
        let r = c.bounds;
        let stroke = Stroke {
            color: theme::sequence::BLOCK_STROKE,
            width: 1.0,
            line_cap: LineCap::Butt,
            line_join: LineJoin::Miter,
            dash_array: vec![3.0, 3.0],
            dash_offset: 0.0,
            miter_limit: 4.0,
        };
        let mut path = ir::geograph::RoutePath::new();
        path.push(ir::geograph::RouteSegment::Line {
            from: Point::new(r.min_x(), d.y),
            to: Point::new(r.max_x(), d.y),
        });
        items.push(SceneItem::Edge {
            path,
            stroke,
            ends: (EdgeEnds::None, EdgeEnds::None),
            z: theme::Z_BACKGROUND,
        });
        if !d.label.is_empty() {
            let mut ts = theme::text_style(
                theme::sequence::BLOCK_TEXT,
                theme::FONT_SIZE * 0.85,
                TextAlign::Center,
                TextBaseline::Middle,
            );
            let spans = vec![RichSpan::new(d.label.clone(), ts.clone())];
            let layout = layout_text(&spans, None);
            let position = place_text(
                &layout,
                &mut ts,
                Point::new((r.min_x() + r.max_x()) / 2.0, d.y + 14.0),
                HAnchor::Center,
                VAnchor::InkMiddle,
            );
            items.push(SceneItem::Label {
                text: spans,
                position,
                style: ts,
                anchor: ir::scenegraph::Anchor::Center,
                z: theme::Z_BACKGROUND,
            });
        }
    }
}

/// 拆分分组块标签为「关键字」+「方括号描述」两段(官方两段独立文本)。
///
/// `"loop [Each item]"` → `("loop", Some("[Each item]]"))`;无方括号时返回 `("", None)`。
fn split_block_label(label: &str) -> (String, Option<String>) {
    match label.find(" [") {
        Some(i) => (label[..i].to_string(), Some(label[i + 1..].to_string())),
        None => (label.to_string(), None),
    }
}

/// 绘制 timeline 图表(Linear 家族):标题 + 时间轴 + section 块 + period 块 +
/// 事件块 + 连接虚线。
///
/// 坐标约定(由 engine 的 `linear_centers` 产生):LR(默认)时各 section 节点中心
/// 在同一水平线(时间轴)上、x 递增;TD 时在同一垂直线(时间轴)上、y 递增。
///
/// 结构对齐官方 golden `timeline__basic`(实测):
/// - 每列自上而下:section 块(轴上方 SECTION_DY)→ period 块(`events[0]`,
///   轴上方 PERIOD_DY)→ 主轴 → event 块(`events[1..]`,轴下方 EVENT_DY 起堆叠);
/// - 主轴 4px 黑实线 + 末端箭头,**轴上无圆点**;
/// - 每列一条 2px 黑虚线(dash 5,5)从 period 块底穿过主轴延伸到末个 event 块下方;
/// - 标题 `4ex` 粗体,左对齐于主轴起点上方。
fn emit_timeline(items: &mut Vec<SceneItem>, gg: &Geograph) {
    let sections: Vec<&GGNode> = gg
        .nodes
        .iter()
        .filter(|n| matches!(n.detail, ir::common::NodeDetail::TimelineSection { .. }))
        .collect();
    if sections.is_empty() {
        return;
    }
    use ir::common::NodeDetail;

    let axis_stroke = Stroke {
        color: theme::timeline::LINE,
        width: theme::timeline::AXIS_WIDTH,
        line_cap: LineCap::Butt,
        line_join: LineJoin::Miter,
        dash_array: Vec::new(),
        dash_offset: 0.0,
        miter_limit: 4.0,
    };

    // 主轴方向由节点分布推断:LR(水平轴)→ x 差异主导;TD(垂直轴)→ y 差异主导。
    let horizontal = if sections.len() >= 2 {
        let a = sections[0].center;
        let b = sections[1].center;
        (b.y - a.y).abs() < (b.x - a.x).abs()
    } else {
        true
    };
    let axis_c = if horizontal {
        sections[0].center.y
    } else {
        sections[0].center.x
    };
    let mut min_a = f64::INFINITY;
    let mut max_a = f64::NEG_INFINITY;
    for s in &sections {
        let c = if horizontal { s.center.x } else { s.center.y };
        min_a = min_a.min(c);
        max_a = max_a.max(c);
    }
    let span_mid = (min_a + max_a) / 2.0;
    let _ = span_mid;

    // 标题(官方 `<text x="轴起点" y="20" font-size="4ex" font-weight="bold">`):
    // 左对齐于主轴起点,基线在 section 块顶上方 30px。
    if let Some(title) = &gg.title
        && !title.is_empty()
    {
        let mut ts = theme::text_style(
            theme::timeline::TITLE,
            theme::timeline::TITLE_SIZE,
            TextAlign::Left,
            TextBaseline::Alphabetic,
        );
        // section 块顶 = 轴 - SECTION_DY - BLOCK_H/2;官方标题基线在块顶上方 30px,
        // 4ex(64px)字号的 ink 顶约在基线上 48px 处 → ink 顶 = 块顶 - 78。
        let sec_top_off = theme::timeline::SECTION_DY + theme::timeline::BLOCK_H / 2.0 + 78.0;
        let axis_start_off = theme::timeline::BLOCK_W / 2.0 + theme::timeline::AXIS_HEAD;
        let pos = if horizontal {
            Point::new(min_a - axis_start_off, axis_c - sec_top_off)
        } else {
            Point::new(axis_c - sec_top_off, min_a - axis_start_off)
        };
        let spans = vec![RichSpan::new(title.clone(), ts.clone())];
        let layout = layout_text(&spans, None);
        let position = place_text(&layout, &mut ts, pos, HAnchor::Left, VAnchor::InkTop);
        items.push(SceneItem::Label {
            text: spans,
            position,
            style: ts,
            anchor: ir::scenegraph::Anchor::Left,
            z: theme::Z_SERIES,
        });
    }

    // 主轴线(带末端箭头;官方轴上无圆点)。
    let arr = theme::timeline::ARROW_SIZE;
    if horizontal {
        let y = axis_c;
        let x0 = min_a - theme::timeline::BLOCK_W / 2.0 - theme::timeline::AXIS_HEAD;
        let x1 = max_a + theme::timeline::BLOCK_W / 2.0 + theme::timeline::AXIS_TAIL;
        let tip = x1 - arr * 1.5;
        items.push(SceneItem::Edge {
            path: ir::geograph::line_route(&[Point::new(x0, y), Point::new(tip, y)]),
            stroke: axis_stroke.clone(),
            ends: (EdgeEnds::None, EdgeEnds::None),
            z: theme::Z_BACKGROUND,
        });
        items.push(SceneItem::Edge {
            path: ir::geograph::line_route(&[
                Point::new(tip, y),
                Point::new(tip - arr * 0.7, y - arr * 0.5),
            ]),
            stroke: axis_stroke.clone(),
            ends: (EdgeEnds::None, EdgeEnds::None),
            z: theme::Z_BACKGROUND,
        });
        items.push(SceneItem::Edge {
            path: ir::geograph::line_route(&[
                Point::new(tip, y),
                Point::new(tip - arr * 0.7, y + arr * 0.5),
            ]),
            stroke: axis_stroke.clone(),
            ends: (EdgeEnds::None, EdgeEnds::None),
            z: theme::Z_BACKGROUND,
        });
    } else {
        let x = axis_c;
        let y0 = min_a - theme::timeline::BLOCK_W / 2.0 - theme::timeline::AXIS_HEAD;
        let y1 = max_a + theme::timeline::BLOCK_W / 2.0 + theme::timeline::AXIS_TAIL;
        let tip = y1 - arr * 1.5;
        items.push(SceneItem::Edge {
            path: ir::geograph::line_route(&[Point::new(x, y0), Point::new(x, tip)]),
            stroke: axis_stroke.clone(),
            ends: (EdgeEnds::None, EdgeEnds::None),
            z: theme::Z_BACKGROUND,
        });
        items.push(SceneItem::Edge {
            path: ir::geograph::line_route(&[
                Point::new(x, tip),
                Point::new(x - arr * 0.5, tip - arr * 0.7),
            ]),
            stroke: axis_stroke.clone(),
            ends: (EdgeEnds::None, EdgeEnds::None),
            z: theme::Z_BACKGROUND,
        });
        items.push(SceneItem::Edge {
            path: ir::geograph::line_route(&[
                Point::new(x, tip),
                Point::new(x + arr * 0.5, tip - arr * 0.7),
            ]),
            stroke: axis_stroke.clone(),
            ends: (EdgeEnds::None, EdgeEnds::None),
            z: theme::Z_BACKGROUND,
        });
    }

    // 每个 section 列:section 块 + period 块(轴上方)+ event 块(轴下方)+ 连接虚线。
    for (idx, s) in sections.iter().enumerate() {
        let color = theme::timeline::block_color(idx);
        let text_color = theme::timeline::block_text_color(idx);
        let (cx, cy) = if horizontal {
            (s.center.x, axis_c)
        } else {
            (axis_c, s.center.y)
        };
        let NodeDetail::TimelineSection { events } = &s.detail else {
            continue;
        };
        let label_text = s.label.as_ref().map(|l| l.text.clone()).unwrap_or_default();

        // section 块(轴上方)。
        let sec_center = if horizontal {
            Point::new(cx, cy - theme::timeline::SECTION_DY)
        } else {
            Point::new(cx - theme::timeline::SECTION_DY, cy)
        };
        emit_timeline_block(
            items,
            sec_center,
            color,
            text_color,
            idx,
            &label_text,
            theme::timeline::BLOCK_H,
        );

        // period 块(events[0],轴上方近轴处)。
        let mut last_block_bottom = if horizontal {
            sec_center.y
        } else {
            sec_center.x
        };
        if let Some(period) = events.first() {
            let per_center = if horizontal {
                Point::new(cx, cy - theme::timeline::PERIOD_DY)
            } else {
                Point::new(cx - theme::timeline::PERIOD_DY, cy)
            };
            emit_timeline_block(
                items,
                per_center,
                color,
                text_color,
                idx,
                period,
                theme::timeline::BLOCK_H,
            );
            last_block_bottom = if horizontal {
                per_center.y
            } else {
                per_center.x
            };
        }

        // event 块(events[1..],轴下方垂直堆叠)。
        let mut last_event_bottom: Option<f64> = None;
        for (j, ev) in events.iter().skip(1).enumerate() {
            let off = theme::timeline::EVENT_DY
                + j as f64 * (theme::timeline::EVENT_H + theme::timeline::EVENT_GAP);
            let ev_center = if horizontal {
                Point::new(cx, cy + off)
            } else {
                Point::new(cx + off, cy)
            };
            emit_timeline_block(
                items,
                ev_center,
                color,
                text_color,
                idx,
                ev,
                theme::timeline::EVENT_H,
            );
            last_event_bottom = Some(if horizontal { ev_center.y } else { ev_center.x });
        }

        // 连接虚线:period 块底 → 末个 event 块底 + TAIL(穿过主轴),带箭头。
        if let Some(ev_bottom) = last_event_bottom {
            let (from, to) = if horizontal {
                (
                    Point::new(cx, last_block_bottom + theme::timeline::BLOCK_H / 2.0),
                    Point::new(
                        cx,
                        ev_bottom
                            + theme::timeline::EVENT_H / 2.0
                            + theme::timeline::CONNECTOR_TAIL,
                    ),
                )
            } else {
                (
                    Point::new(last_block_bottom + theme::timeline::BLOCK_H / 2.0, cy),
                    Point::new(
                        ev_bottom
                            + theme::timeline::EVENT_H / 2.0
                            + theme::timeline::CONNECTOR_TAIL,
                        cy,
                    ),
                )
            };
            let stroke = Stroke {
                color: theme::timeline::LINE,
                width: theme::timeline::CONNECTOR_W,
                line_cap: LineCap::Butt,
                line_join: LineJoin::Miter,
                dash_array: vec![5.0, 5.0],
                dash_offset: 0.0,
                miter_limit: 4.0,
            };
            items.push(SceneItem::Edge {
                path: ir::geograph::line_route(&[from, to]),
                stroke,
                // 官方连接线箭头在**末端**(marker-end,位于 event 块下方)。
                ends: (EdgeEnds::None, EdgeEnds::Arrow),
                z: theme::Z_GRID,
            });
        }
    }
}

/// 画一个 timeline 任务块(section / period / event):**顶角圆**、底角直角的彩色
/// 矩形 + 底部 3px 互补色线 + 居中文本。
///
/// 官方块路径 `M0 65.8 v-55.8 q0,-5,5,-5 h180 q5,0,5,5 v65.8 H0 Z` 仅上角倒圆;
/// paint 层会把 Path 拍平为多边形,故此处直接用采样圆弧构造多边形。
fn emit_timeline_block(
    items: &mut Vec<SceneItem>,
    center: Point,
    color: Color,
    text_color: Color,
    idx: usize,
    text: &str,
    height: f64,
) {
    let w = theme::timeline::BLOCK_W;
    let at = Point::new(center.x - w / 2.0, center.y - height / 2.0);
    // 顶角圆(r=5)的采样多边形:左下 → 左上 → 顶左弧 → 顶右弧 → 右下 → 回闭。
    // 弧心分别在 (at.x+r, at.y+r) 与 (at.x+w-r, at.y+r):
    // 左弧角度 180°→270°(从左侧壁转到顶壁),右弧 270°→360°。
    let r = theme::timeline::BLOCK_RX.min(height / 2.0).min(w / 2.0);
    let steps = 4;
    let mut pts = vec![Point::new(at.x, at.y + height)];
    for i in 0..=steps {
        let t = std::f64::consts::PI * (1.0 + i as f64 / steps as f64); // 180° → 270°
        pts.push(Point::new(at.x + r + r * t.cos(), at.y + r + r * t.sin()));
    }
    for i in 0..=steps {
        let t = std::f64::consts::PI * (1.5 + i as f64 / steps as f64); // 270° → 360°
        pts.push(Point::new(
            at.x + w - r + r * t.cos(),
            at.y + r + r * t.sin(),
        ));
    }
    pts.push(Point::new(at.x + w, at.y + height));
    pts.push(Point::new(at.x, at.y + height));
    items.push(SceneItem::Shape {
        geometry: ShapeGeometry::Polygon { points: pts },
        fill: Some(Fill::Solid(color)),
        stroke: None,
        name: None,
        z: theme::Z_SERIES,
    });
    // 块底线(官方 `.section-N line{stroke-width:3}`,互补色提亮)。
    items.push(SceneItem::Edge {
        path: ir::geograph::line_route(&[
            Point::new(at.x, at.y + height),
            Point::new(at.x + w, at.y + height),
        ]),
        stroke: Stroke {
            color: theme::timeline::block_line_color(idx),
            width: theme::timeline::BLOCK_LINE_W,
            line_cap: LineCap::Butt,
            line_join: LineJoin::Miter,
            dash_array: Vec::new(),
            dash_offset: 0.0,
            miter_limit: 4.0,
        },
        ends: (EdgeEnds::None, EdgeEnds::None),
        z: theme::Z_SERIES,
    });
    let mut ts = theme::text_style(
        text_color,
        theme::timeline::BLOCK_TEXT_SIZE,
        TextAlign::Center,
        TextBaseline::Middle,
    );
    let spans = vec![RichSpan::new(text.to_string(), ts.clone())];
    let layout = layout_text(&spans, None);
    let position = place_text(
        &layout,
        &mut ts,
        center,
        HAnchor::Center,
        VAnchor::InkMiddle,
    );
    items.push(SceneItem::Label {
        text: spans,
        position,
        style: ts,
        anchor: ir::scenegraph::Anchor::Center,
        z: theme::Z_SERIES,
    });
}

/// 节点填充/描边按形状语义取色。
fn node_fill_stroke(shape: ShapeKind) -> (Fill, Stroke) {
    let default_stroke = Stroke {
        color: theme::flowchart::STROKE,
        width: NODE_STROKE_WIDTH,
        line_cap: LineCap::Butt,
        line_join: LineJoin::Miter,
        dash_array: Vec::new(),
        dash_offset: 0.0,
        miter_limit: 4.0,
    };
    match shape {
        // StartDot:实心深色圆(官方 `.node circle.state-start{fill:#333333}`)。
        ShapeKind::StartDot => (
            Fill::Solid(theme::state::SPECIAL),
            Stroke {
                width: 0.0,
                ..default_stroke
            },
        ),
        // Bar:fork/join 横条,实心深色(官方 `.node .fork-join{fill:#333333}`)。
        ShapeKind::Bar => (
            Fill::Solid(theme::state::SPECIAL),
            Stroke {
                width: 0.0,
                ..default_stroke
            },
        ),
        _ => (Fill::Solid(theme::flowchart::FILL), default_stroke),
    }
}

/// 边颜色/宽度按语义与线型取(flowchart 与 state 同色,class/er 用各自主题色)。
/// Thick 加粗,其余(Solid/Dotted/Invisible)用常规宽度。
fn edge_style(kind: EdgeKind, line: ir::common::LineKind) -> (Color, f64) {
    let width = if line == ir::common::LineKind::Thick {
        theme::EDGE_WIDTH_THICK
    } else {
        theme::EDGE_WIDTH
    };
    let color = match kind {
        EdgeKind::ClassExtends
        | EdgeKind::ClassComposition
        | EdgeKind::ClassAggregation
        | EdgeKind::ClassAssociation
        | EdgeKind::ClassDependency
        | EdgeKind::ClassRealization
        | EdgeKind::ClassLink
        | EdgeKind::ClassDashed => theme::class::EDGE,
        _ => theme::flowchart::EDGE,
    };
    (color, width)
}

/// 单端 ArrowKind → EdgeEnds(起止两端分别查表)。
fn map_ends(kind: ArrowKind) -> EdgeEnds {
    match kind {
        ArrowKind::Arrow => EdgeEnds::Arrow,
        ArrowKind::Circle => EdgeEnds::Circle,
        ArrowKind::Cross => EdgeEnds::Cross,
        ArrowKind::None => EdgeEnds::None,
    }
}

/// 边的起止标记:class 关系据 [`EdgeKind`] 生成特殊端点装饰(三角 / 菱形),
/// 其余据 [`ArrowSpec`] 映射。extract 阶段 class 关系的 arrow 为占位(None/Arrow),
/// 真正的三角 / 菱形在此据 kind 补出。
fn edge_ends(kind: EdgeKind, arrow: ArrowSpec) -> (EdgeEnds, EdgeEnds) {
    match kind {
        EdgeKind::ClassExtends => (EdgeEnds::Triangle, EdgeEnds::None),
        EdgeKind::ClassComposition => (EdgeEnds::DiamondFilled, EdgeEnds::None),
        EdgeKind::ClassAggregation => (EdgeEnds::DiamondHollow, EdgeEnds::None),
        EdgeKind::ClassAssociation => (EdgeEnds::None, EdgeEnds::TriangleFilled),
        EdgeKind::ClassDependency | EdgeKind::ClassRealization => {
            // 官方 class 依赖/实现用开口箭头(`classDiagram-dependencyEnd`,
            // marker `M 18,7 L9,13 L14,7 L9,1 Z` 内凹 chevron)。
            (EdgeEnds::None, EdgeEnds::ArrowOpen)
        }
        _ => (map_ends(arrow.start), map_ends(arrow.end)),
    }
}

/// 平行四边形 / 梯形的斜移量(官方 golden 实测固定值 19.5px,不随宽度缩放)。
const PARALLELOGRAM_SKEW: f64 = 19.5;
/// subroutine 双侧竖线与内矩形的间距(官方 golden:内矩形左右各外扩 8px)。
const SUBROUTINE_BAR_GAP: f64 = 8.0;

/// 据 ShapeKind + center + size 生成抽象几何描述(paint 据此选 Element 变体)。
fn shape_to_geometry(shape: ShapeKind, center: Point, size: Size) -> ShapeGeometry {
    let half_w = size.width / 2.0;
    let half_h = size.height / 2.0;
    let tl = Point::new(center.x - half_w, center.y - half_h);
    match shape {
        ShapeKind::Rectangle | ShapeKind::Bar => ShapeGeometry::Rect { at: tl, size },
        ShapeKind::Rounded => ShapeGeometry::RoundedRect {
            at: tl,
            size,
            // 官方默认节点圆角 radius=5(theme::NODE_RADIUS)。
            radius: theme::NODE_RADIUS,
        },
        // 官方 subroutine(`[[X]]`):内矩形(测量宽 - 16,即左右各内缩 8px),
        // 两条外竖线由节点绘制循环补画(见 emit 处的 Subroutine 分支)。
        ShapeKind::Subroutine => ShapeGeometry::Rect {
            at: Point::new(tl.x + SUBROUTINE_BAR_GAP, tl.y),
            size: Size::new(
                (size.width - 2.0 * SUBROUTINE_BAR_GAP).max(0.0),
                size.height,
            ),
        },
        ShapeKind::Stadium => ShapeGeometry::Stadium { at: tl, size },
        ShapeKind::Diamond => ShapeGeometry::Polygon {
            points: vec![
                Point::new(center.x, center.y - half_h),
                Point::new(center.x + half_w, center.y),
                Point::new(center.x, center.y + half_h),
                Point::new(center.x - half_w, center.y),
            ],
        },
        ShapeKind::Hexagon => {
            let w = half_w * 0.5;
            ShapeGeometry::Polygon {
                points: vec![
                    Point::new(center.x - w, center.y - half_h),
                    Point::new(center.x + w, center.y - half_h),
                    Point::new(center.x + half_w, center.y),
                    Point::new(center.x + w, center.y + half_h),
                    Point::new(center.x - w, center.y + half_h),
                    Point::new(center.x - half_w, center.y),
                ],
            }
        }
        ShapeKind::Circle | ShapeKind::StartDot | ShapeKind::EndDot | ShapeKind::DoubleCircle => {
            ShapeGeometry::Ellipse {
                center,
                rx: half_w,
                ry: half_h,
            }
        }
        ShapeKind::Asymmetric => {
            let skew = half_w * 0.25;
            ShapeGeometry::Polygon {
                points: vec![
                    Point::new(tl.x + skew, tl.y),
                    Point::new(tl.x + size.width, tl.y),
                    Point::new(tl.x + size.width - skew, tl.y + size.height),
                    Point::new(tl.x, tl.y + size.height),
                ],
            }
        }
        ShapeKind::Parallelogram => {
            // 官方 golden:平行四边形斜移量固定 19.5px(`H[/Parallelogram/]` 的
            // polygon points="-19.5,0 113.72,0 133.22,-39 0,-39"),且包围盒仅向
            // 单侧扩展 skew(测量宽 = 文本 + 2×17.25,绘制时整体宽 = 测量宽 + 19.5)。
            let skew = PARALLELOGRAM_SKEW;
            ShapeGeometry::Polygon {
                points: vec![
                    Point::new(tl.x - skew, tl.y),
                    Point::new(tl.x + size.width - skew, tl.y),
                    Point::new(tl.x + size.width, tl.y + size.height),
                    Point::new(tl.x, tl.y + size.height),
                ],
            }
        }
        ShapeKind::Trapezoid => {
            // 官方 golden:梯形下边单侧斜移 19.5px(`points="0,0 105.06,0 85.56,-39 -19.5,-39"`)。
            let skew = PARALLELOGRAM_SKEW;
            ShapeGeometry::Polygon {
                points: vec![
                    Point::new(tl.x, tl.y),
                    Point::new(tl.x + size.width, tl.y),
                    Point::new(tl.x + size.width - skew, tl.y + size.height),
                    Point::new(tl.x - skew, tl.y + size.height),
                ],
            }
        }
        ShapeKind::Cylinder => {
            // 官方 golden:`ry = 10.01`(总高 69.03 时占比 ≈ 0.29×半高),即上下
            // 椭圆弧各占总高约 14.5%;旧实现 half_h*0.2 弧顶偏平。
            let ry = half_h * 0.29;
            let top = center.y - half_h + ry;
            let bottom = center.y + half_h - ry;
            let mut pts = Vec::new();
            let steps = 12;
            for i in 0..=steps {
                let t = std::f64::consts::PI * (i as f64 / steps as f64);
                let x = center.x - half_w * (t.cos());
                let y = top - ry * (t.sin());
                pts.push(Point::new(x, y));
            }
            pts.push(Point::new(center.x + half_w, bottom));
            for i in 0..=steps {
                let t = std::f64::consts::PI * (i as f64 / steps as f64);
                let x = center.x + half_w * (t.cos());
                let y = bottom + ry * (t.sin());
                pts.push(Point::new(x, y));
            }
            pts.push(Point::new(center.x - half_w, top));
            ShapeGeometry::Polygon { points: pts }
        }
        ShapeKind::PieSlice => ShapeGeometry::Pie {
            center,
            radius: half_w.max(half_h),
            start_angle: 0.0,
            end_angle: std::f64::consts::FRAC_PI_2,
        },
    }
}