lievisual 0.3.3

Declarative visual scene IR + pluggable rendering backends (SVG / vello_cpu / GPU).
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
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
//! SVG vector output backend.
//!
//! Purely declarative, without depending on vello / parley. Maps each [`Element`] to native
//! SVG tags:
//! - Rect/Circle/Ellipse/RoundedRect/Line/Polyline/Polygon → the corresponding SVG shape element.
//! - Arc/Pie → `<path d="...">` (SVG's native arc command `A`).
//! - Path/GradientPath → kurbo's SVG path serialization (`d` attribute).
//! - Text → `<text>` element (no parley dependency; the `layout` field is ignored, the browser
//!   does the typesetting).
//!
//! Transforms are realized via `<g transform="...">`, decoupled from a backend state stack; a
//! node's `opacity` / `name` are emitted as `<g opacity>` / `<g id>`; the scene's `title` /
//! `description` / `scale` are captured at [`Renderer::render_scene`].
//!
//! Gradients uniformly use `gradientUnits="userSpaceOnUse"` (user coordinates, consistent with
//! the IR's absolute coordinates).

use crate::geometry::{Color, Point, Rect, Transform, Vec2};
use crate::render::Renderer;
use crate::scene::{
    BlendMode, ColorMatrix, Fill, FillStrokeStyle, GradientSpread, GradientStop, LineCap, LineJoin,
    LinearGradient, Scene, SketchFill, SketchFillStyle, Stroke, SweepGradient,
};
use crate::text::TextStyle;
use kurbo::Shape as _;
use std::fmt::Write;

/// 根节点 `width` / `height` 的写法 —— 即 SVG **视口**尺寸的来源。
///
/// SVG 的视口(`width` / `height`)与用户坐标系(`viewBox`)是两回事:后者始终按
/// `输出尺寸 / scale` 输出,这里的选项只决定前者要不要写、怎么写。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SvgSizing {
    /// 写死输出尺寸:`width="{w}" height="{h}"`(默认)。
    ///
    /// 栅格 / 打印语义:文档在任意宿主下都是同一像素尺寸,不做任何自适应。
    #[default]
    Fixed,
    /// 只写 `viewBox`,省略 `width` / `height`:视口尺寸交给宿主 CSS 决定。
    ///
    /// SVG 2 中这两个属性的初始值是 `auto`(解析为 `100%`),配合 `viewBox` 的固有宽高比
    /// 即得到"跟随容器、等比缩放"的响应式行为。官方 mermaid 的
    /// `width="100%" style="max-width: Wpx"` 是同一效果的另一种写法 —— 需要给宽容器封顶
    /// 时,用 [`SvgRenderer::with_style`] 补一条 `max-width` 即可。
    Intrinsic,
}

/// SVG renderer: accumulates the SVG string.
pub struct SvgRenderer {
    buf: String,
    width: f64,
    height: f64,
    /// `None` → fall back to [`Scene::background`] (the Scene is the authoritative IR).
    background: Option<Color>,
    gradient_id: usize,
    clip_id: usize,
    mask_id: usize,
    filter_id: usize,
    /// Id counter for `<pattern>`s built from tiled images.
    image_id: usize,
    /// Composed colour-matrix stack: the last entry is baked into every paint colour emitted.
    color_matrices: Vec<ColorMatrix>,
    /// Anti-aliasing stack: the top value is the active setting (`true` = anti-aliased).
    antialias_stack: Vec<bool>,
    /// Hand-drawn fill patterns already emitted: index = `sk{n}` id, deduplicated by value so
    /// a hundred same-coloured cells share one `<pattern>`. Keyed by the active colour matrix too,
    /// since the tile's ink is baked with it.
    patterns: Vec<(SketchFill, ColorMatrix)>,
    title: Option<String>,
    description: Option<String>,
    /// `None` → fall back to [`Scene::scale`]; an explicit renderer value wins.
    scale: Option<f64>,
    /// Root `width` / `height` strategy (the viewport); `viewBox` is always emitted.
    sizing: SvgSizing,
    /// Extra CSS appended to the root's `style` attribute, e.g. `max-width: 130px`.
    style: Option<String>,
}

impl SvgRenderer {
    /// Create a renderer for an output canvas of `width × height` (scene units / px).
    ///
    /// A non-positive size means "unset": the value from the rendered [`Scene`] is then used,
    /// so `SvgRenderer::new(0.0, 0.0)` still produces a correctly sized document.
    pub fn new(width: f64, height: f64) -> Self {
        Self {
            buf: String::new(),
            width,
            height,
            background: None,
            gradient_id: 0,
            clip_id: 0,
            mask_id: 0,
            filter_id: 0,
            image_id: 0,
            color_matrices: Vec::new(),
            antialias_stack: Vec::new(),
            patterns: Vec::new(),
            title: None,
            description: None,
            scale: None,
            sizing: SvgSizing::Fixed,
            style: None,
        }
    }

    /// Explicit background color; when unset, [`Scene::background`] is used.
    #[must_use]
    pub fn with_background(mut self, bg: Color) -> Self {
        self.background = Some(bg);
        self
    }

    /// Output scale (pixel density): enlarges `width`/`height` while keeping `viewBox` unchanged.
    ///
    /// Takes precedence over [`Scene::scale`]; when unset, the scene's scale is used.
    #[must_use]
    pub fn with_scale(mut self, scale: f64) -> Self {
        self.scale = Some(scale);
        self
    }

    /// Root `width` / `height` strategy; see [`SvgSizing`].
    #[must_use]
    pub fn with_sizing(mut self, sizing: SvgSizing) -> Self {
        self.sizing = sizing;
        self
    }

    /// CSS appended to the root's `style` attribute (XML-attribute escaped).
    ///
    /// Used for things the backends cannot express: capping the rendered width
    /// (`max-width: 130px`), declaring a `background-color`, ...
    #[must_use]
    pub fn with_style(mut self, style: impl Into<String>) -> Self {
        self.style = Some(style.into());
        self
    }

    /// Document title.
    #[must_use]
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Document description.
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Take the complete SVG document (including the `<svg>` root and background).
    ///
    /// Sizing contract (same as the raster backend): **the size given to
    /// [`SvgRenderer::new`] is the output size** — it lands verbatim in the root
    /// `width`/`height` attributes, and `viewBox` is that size divided by `scale`:
    ///
    /// ```text
    /// width/height = 输出尺寸            (SvgRenderer::new 传入)
    /// viewBox      = 0 0 (输出尺寸/scale) (绘制使用的用户坐标系)
    /// ```
    ///
    /// `scale` is therefore a *density* knob, applied symmetrically on both backends, and it
    /// never silently enlarges the output. To export a scene at 2× density, pass
    /// `new(w * 2.0, h * 2.0)` (the `new(0.0, 0.0)` fallback does this for you, treating
    /// `scene.width`/`scene.height` as logical size).
    ///
    /// That size only reaches the root `width` / `height` attributes under
    /// [`SvgSizing::Fixed`]; under [`SvgSizing::Intrinsic`] the viewport is left to the host
    /// CSS and only `viewBox` carries the geometry.
    pub fn into_string(self) -> String {
        let mut out = String::new();
        let scale = self.scale.unwrap_or(1.0);
        // viewBox 用"用户坐标系":输出尺寸 / scale。scale=1 时与输出尺寸相同。
        let vw = self.width / scale;
        let vh = self.height / scale;
        let _ = write!(out, r#"<svg xmlns="http://www.w3.org/2000/svg""#);
        // 视口:写死输出尺寸,或省略让宿主 CSS 决定(见 SvgSizing)。
        if self.sizing == SvgSizing::Fixed {
            let _ = write!(
                out,
                r#" width="{:.2}" height="{:.2}""#,
                self.width, self.height
            );
        }
        let _ = write!(out, r#" viewBox="0 0 {:.2} {:.2}""#, vw, vh);
        if let Some(style) = &self.style {
            let _ = write!(out, r#" style="{}""#, escape_attr(style));
        }
        let _ = writeln!(out, ">");
        if let Some(t) = &self.title {
            let _ = writeln!(out, "<title>{}</title>", escape_text(t));
        }
        if let Some(d) = &self.description {
            let _ = writeln!(out, "<desc>{}</desc>", escape_text(d));
        }
        // Background rectangle (viewBox / user coordinates, so it always covers exactly the
        // logical canvas). Always output the full-canvas background so the base color is correct
        // (a transparent background is also an overlay layer, matching common-library semantics).
        let _ = write!(
            out,
            r#"<rect x="0" y="0" width="{:.2}" height="{:.2}""#,
            vw, vh
        );
        out.push_str(&color_attr_str(
            "fill",
            self.background.unwrap_or(Color::WHITE),
        ));
        let _ = writeln!(out, "/>");
        // content
        out.push_str(&self.buf);
        out.push_str("</svg>\n");
        out
    }

    fn next_gradient_id(&mut self) -> usize {
        let id = self.gradient_id;
        self.gradient_id += 1;
        id
    }
}

impl Renderer for SvgRenderer {
    fn render_scene(&mut self, scene: &Scene) {
        // Capture scene metadata, then reuse the default traversal. Values explicitly set on
        // the renderer take precedence; the rest falls back to the scene (the authoritative IR),
        // so `SvgRenderer::new(0.0, 0.0)` still yields a correctly sized document.
        self.title = scene.title.clone();
        self.description = scene.description.clone();
        // scale: an explicit renderer value wins, otherwise the scene's.
        let scale = self
            .scale
            .unwrap_or(if scene.scale.is_finite() && scene.scale > 0.0 {
                scene.scale
            } else {
                1.0
            });
        self.scale = Some(scale);
        if self.background.is_none() {
            self.background = Some(scene.background);
        }
        // Size fallback: treat `scene.width/height` as the **logical** size and multiply by
        // `scale` to get the output size — i.e. `new(0.0, 0.0)` behaves exactly like the
        // pre-existing "scale enlarges the export" behaviour, while an explicit size is honoured
        // verbatim as the output size.
        if self.width <= 0.0 {
            self.width = scene.width * scale;
        }
        if self.height <= 0.0 {
            self.height = scene.height * scale;
        }
        self.render_scene_ordered(scene);
    }

    fn draw_rect(&mut self, rect: Rect, style: &FillStrokeStyle) {
        let mut el = String::new();
        let _ = write!(
            el,
            r#"<rect x="{:.2}" y="{:.2}" width="{:.2}" height="{:.2}" "#,
            rect.min_x(),
            rect.min_y(),
            rect.width(),
            rect.height()
        );
        self.apply_fill_stroke(&mut el, style, rect);
        let _ = writeln!(el, "/>");
        self.buf.push_str(&el);
    }

    fn draw_circle(&mut self, center: Point, radius: f64, style: &FillStrokeStyle) {
        let mut el = String::new();
        let _ = write!(
            el,
            r#"<circle cx="{:.2}" cy="{:.2}" r="{:.2}" "#,
            center.x, center.y, radius
        );
        self.apply_fill_stroke(&mut el, style, square_bbox(center, radius));
        let _ = writeln!(el, "/>");
        self.buf.push_str(&el);
    }

    fn draw_ellipse(&mut self, center: Point, radii: Vec2, rotation: f64, style: &FillStrokeStyle) {
        let mut el = String::new();
        let _ = write!(
            el,
            r#"<ellipse cx="{:.2}" cy="{:.2}" rx="{:.2}" ry="{:.2}" "#,
            center.x, center.y, radii.x, radii.y
        );
        if rotation != 0.0 {
            let _ = write!(
                el,
                r#"transform="rotate({:.2} {:.2} {:.2})" "#,
                rotation.to_degrees(),
                center.x,
                center.y
            );
        }
        // A rotated ellipse is covered by the square around its larger semi-axis.
        self.apply_fill_stroke(
            &mut el,
            style,
            square_bbox(center, radii.x.abs().max(radii.y.abs())),
        );
        let _ = writeln!(el, "/>");
        self.buf.push_str(&el);
    }

    fn draw_rounded_rect(&mut self, rect: Rect, radius: f64, style: &FillStrokeStyle) {
        // Consistent with the PNG backend: derive non-negative width/height from the geometry
        // bounds (a Rect may have min > max).
        let (x, y) = (
            rect.min_x().min(rect.max_x()),
            rect.min_y().min(rect.max_y()),
        );
        let w = (rect.max_x() - rect.min_x()).abs();
        let h = (rect.max_y() - rect.min_y()).abs();
        let mut el = String::new();
        let _ = write!(
            el,
            r#"<rect x="{:.2}" y="{:.2}" width="{:.2}" height="{:.2}" rx="{:.2}" "#,
            x, y, w, h, radius
        );
        self.apply_fill_stroke(&mut el, style, Rect::new(x, y, x + w, y + h));
        let _ = writeln!(el, "/>");
        self.buf.push_str(&el);
    }

    fn draw_line(&mut self, start: Point, end: Point, style: &Stroke) {
        let mut el = String::new();
        let _ = write!(
            el,
            r#"<line x1="{:.2}" y1="{:.2}" x2="{:.2}" y2="{:.2}" "#,
            start.x, start.y, end.x, end.y
        );
        self.apply_stroke_only(&mut el, style);
        let _ = writeln!(el, "/>");
        self.buf.push_str(&el);
    }

    fn draw_polyline(&mut self, points: &[Point], style: &Stroke) {
        let pts: Vec<String> = points
            .iter()
            .map(|p| format!("{:.2},{:.2}", p.x, p.y))
            .collect();
        let mut el = String::new();
        let _ = write!(el, r#"<polyline points="{}" "#, pts.join(" "));
        self.apply_stroke_only(&mut el, style);
        let _ = writeln!(el, "/>");
        self.buf.push_str(&el);
    }

    fn draw_polygon(&mut self, points: &[Point], style: &FillStrokeStyle) {
        let pts: Vec<String> = points
            .iter()
            .map(|p| format!("{:.2},{:.2}", p.x, p.y))
            .collect();
        let mut el = String::new();
        let _ = write!(el, r#"<polygon points="{}" "#, pts.join(" "));
        self.apply_fill_stroke(&mut el, style, points_bbox(points));
        let _ = writeln!(el, "/>");
        self.buf.push_str(&el);
    }

    fn draw_arc(
        &mut self,
        center: Point,
        radii: Vec2,
        start_angle: f64,
        sweep_angle: f64,
        style: &Stroke,
    ) {
        let d = arc_path_d(center, radii, start_angle, sweep_angle, false);
        let mut el = String::new();
        let _ = write!(el, r#"<path d="{}" "#, d);
        self.apply_stroke_only(&mut el, style);
        let _ = writeln!(el, "/>");
        self.buf.push_str(&el);
    }

    fn draw_pie(
        &mut self,
        center: Point,
        radius: f64,
        start_angle: f64,
        sweep_angle: f64,
        style: &FillStrokeStyle,
    ) {
        let d = arc_path_d(
            center,
            Vec2::new(radius, radius),
            start_angle,
            sweep_angle,
            true,
        );
        let mut el = String::new();
        let _ = write!(el, r#"<path d="{}" "#, d);
        self.apply_fill_stroke(&mut el, style, square_bbox(center, radius));
        let _ = writeln!(el, "/>");
        self.buf.push_str(&el);
    }

    fn draw_path(&mut self, path: &kurbo::BezPath, style: &FillStrokeStyle, closed: bool) {
        let d = if closed {
            let mut p = path.clone();
            p.close_path();
            p.to_svg()
        } else {
            path.to_svg()
        };
        let mut el = String::new();
        let _ = write!(el, r#"<path d="{}" "#, d);
        self.apply_fill_stroke(&mut el, style, path.bounding_box());
        let _ = writeln!(el, "/>");
        self.buf.push_str(&el);
    }

    fn draw_gradient_path(
        &mut self,
        path: &kurbo::BezPath,
        gradient: &LinearGradient,
        stroke: Option<&Stroke>,
    ) {
        let mut p = path.clone();
        p.close_path();
        let d = p.to_svg();
        let matrix = self.current_color_matrix();
        let fill = self.linear_gradient_fill(gradient, matrix);
        let mut el = String::new();
        let _ = write!(el, r#"<path d="{d}""#);
        el.push_str(&fill);
        if let Some(s) = stroke {
            self.append_stroke(&mut el, s);
        }
        let _ = writeln!(el, "/>");
        self.buf.push_str(&el);
    }

    fn draw_text(
        &mut self,
        spans: &[crate::text::RichSpan],
        position: Point,
        style: &TextStyle,
        layout: Option<&crate::text::TextLayout>,
    ) {
        // SVG uses a native <text> element, typeset by the browser; layout is used only for the
        // background rectangle's exact dimensions. Plain text is derived by concatenating spans,
        // keeping glyph content consistent with the vello backend.
        let content = spans.iter().map(|s| s.text.as_str()).collect::<String>();
        // A pre-laid-out layout provides the text block's exact dimensions.
        //
        // `Element::text` / `Element::rich_text` typeset eagerly, so the normal path always has
        // one. The `None` branch is only a fallback for a hand-built `Element::Text { layout: None
        // }` and is a **coarse `font_size`-based approximation** — it can overshoot the block
        // width by ~20%, so do not rely on it for background rectangles.
        let metrics = layout.map(crate::text::layout_metrics);
        // Anchor: text-anchor (horizontal, maps to align) + dominant-baseline (vertical, maps to
        // baseline).
        let anchor = match style.align {
            crate::text::TextAlign::Left | crate::text::TextAlign::Justify => "start",
            crate::text::TextAlign::Center => "middle",
            crate::text::TextAlign::Right => "end",
        };
        // SVG's dominant-baseline has no "top"/"bottom" values; we uniformly convert to
        // alphabetic-baseline coordinates so browser typesetting matches the canvas fillText
        // semantics of the vello/parley backend. position.y is the anchor (its meaning decided by
        // baseline); first compute the text-block top, then derive the alphabetic baseline.
        let (anchor_offset, alphabetic_baseline) = match &metrics {
            Some(m) => (style.baseline.anchor_offset(m), m.alphabetic_baseline),
            None => {
                let ab = style.font_size * 0.85;
                let off = match style.baseline {
                    crate::text::TextBaseline::Top => 0.0,
                    crate::text::TextBaseline::Hanging => style.font_size * 0.75,
                    crate::text::TextBaseline::Middle => style.font_size * 0.5,
                    crate::text::TextBaseline::Alphabetic => ab,
                    crate::text::TextBaseline::Ideographic => style.font_size * 0.9,
                    crate::text::TextBaseline::Bottom => style.font_size * 1.3,
                };
                (off, ab)
            }
        };
        let block_top_y = position.y - anchor_offset;
        let alphabetic_y = block_top_y + alphabetic_baseline;
        let baseline = "alphabetic";
        let fstyle = match style.font_style {
            crate::text::FontStyle::Normal => "normal",
            crate::text::FontStyle::Italic => "italic",
            crate::text::FontStyle::Oblique => "oblique",
        };
        let rot = if style.rotation != 0.0 {
            format!(
                r#" transform="rotate({:.2} {:.2} {:.2})""#,
                style.rotation.to_degrees(),
                position.x,
                position.y
            )
        } else {
            String::new()
        };
        let lh = match style.line_height {
            Some(h) => format!(r#" style="line-height:{:.2}""#, h),
            None => String::new(),
        };
        // Optional typographic attributes: font width (font-stretch), letter spacing
        // (letter-spacing), text decoration (underline / line-through, output per the style's
        // block-level defaults).
        let fwidth = if style.font_width != crate::text::FontWidth::Normal {
            format!(
                r#" font-stretch="{:.0}%""#,
                style.font_width.ratio() * 100.0
            )
        } else {
            String::new()
        };
        let letter = if style.letter_spacing != 0.0 {
            format!(r#" letter-spacing="{:.2}""#, style.letter_spacing)
        } else {
            String::new()
        };
        let decoration: Vec<&str> = match (style.underline, style.strikethrough) {
            (true, true) => vec!["underline", "line-through"],
            (true, false) => vec!["underline"],
            (false, true) => vec!["line-through"],
            (false, false) => vec![],
        };
        let deco = if decoration.is_empty() {
            String::new()
        } else {
            format!(r#" text-decoration="{}""#, decoration.join(" "))
        };
        // Baseline shift (superscript / subscript): positive baseline-shift = up (superscript),
        // negative = down (subscript).
        let bshift = if style.baseline_shift != 0.0 {
            format!(r#" baseline-shift="{:.2}px""#, -style.baseline_shift)
        } else {
            String::new()
        };
        // Text background (inline highlight): prefer the pre-laid-out layout's exact width/height;
        // fall back to an approximation without layout.
        // width = metrics.width (with layout) or char_count*0.6*font-size; height = metrics.height
        // or font-size*1.3.
        if let Some(bg) = style.background_color {
            let (w, h) = match &metrics {
                Some(m) => (m.width, m.height),
                None => {
                    let avg_w = style.font_size * 0.6;
                    (
                        (content.chars().count() as f64 * avg_w).max(avg_w),
                        style.font_size * 1.3,
                    )
                }
            };
            // The background rectangle aligns with the text-block top, consistent with the vello
            // backend.
            let rx = position.x;
            let ry = block_top_y;
            // For right alignment, the background extends leftward.
            let bx = match style.align {
                crate::text::TextAlign::Right => rx - w,
                crate::text::TextAlign::Center => rx - w / 2.0,
                crate::text::TextAlign::Left | crate::text::TextAlign::Justify => rx,
            };
            let mut bg_el = String::new();
            let _ = write!(
                bg_el,
                r#"<rect x="{:.2}" y="{:.2}" width="{:.2}" height="{:.2}""#,
                bx,
                ry - style.baseline_shift,
                w,
                h
            );
            bg_el.push_str(&self.color_attr("fill", bg));
            bg_el.push_str("/>\n");
            self.buf.push_str(&bg_el);
        }
        let mut el = String::new();
        let _ = write!(
            el,
            r#"<text x="{:.2}" y="{:.2}" text-anchor="{}" dominant-baseline="{}" font-family="{}" font-size="{:.2}" font-style="{}" font-weight="{:.0}""#,
            position.x,
            alphabetic_y,
            anchor,
            baseline,
            escape_attr(&style.font_family_css()),
            style.font_size,
            fstyle,
            style.font_weight.value(),
        );
        el.push_str(&self.color_attr("fill", style.color));
        el.push_str(&fwidth);
        el.push_str(&letter);
        el.push_str(&deco);
        el.push_str(&lh);
        el.push_str(&rot);
        el.push_str(&bshift);
        el.push('>');
        if spans.len() > 1 || content.contains('\n') {
            // Rich text: emit one line-`<tspan>` per physical line and one style-`<tspan>`
            // per span fragment, so per-span color / size / weight / family and explicit
            // `\n` breaks survive (a single flat `<text>` cannot express them).
            el.push_str(&self.rich_text_tspans(spans, position.x, style, metrics.as_ref()));
        } else {
            // Single span without line breaks: keep the flat text output (no tspan).
            el.push_str(&escape_text(&content));
        }
        el.push_str("</text>\n");
        self.buf.push_str(&el);
    }

    fn draw_image(&mut self, image: &crate::SceneImage, frame: Rect, opacity: f64) {
        // Bitmap → PNG encode → data: URI (base64), output as <image>, the browser decodes it
        // and applies object-fit.
        let data_uri = image_data_uri(&image.pixmap);
        let op = if (opacity - 1.0).abs() > 1e-6 {
            format!(r#" opacity="{:.3}""#, opacity)
        } else {
            String::new()
        };
        // preserveAspectRatio controls object-fit; x/y/width/height are the display frame.
        // None: no scaling, place at the frame's top-left at original pixel size.
        let (w, h) = match image.object_fit {
            crate::ObjectFit::None => (image.pixmap.width() as f64, image.pixmap.height() as f64),
            _ => (frame.width(), frame.height()),
        };
        // The browser does the resampling; `image-rendering` is the only lever available, and it
        // is only a hint (`Bilinear` = the default, so nothing is emitted).
        let rendering = match image.quality {
            crate::scene::ImageQuality::Nearest => r#" image-rendering="pixelated""#,
            crate::scene::ImageQuality::Bilinear => "",
            crate::scene::ImageQuality::Bicubic => r#" image-rendering="high-quality""#,
        };
        let (x, y) = (frame.min_x(), frame.min_y());
        // A tile is a `<pattern>` holding one copy at natural pixel size (anchored at the frame
        // origin) plus a rect covering the frame — the rect clips the overflow.
        if image.object_fit == crate::ObjectFit::Tile {
            let id = self.image_id;
            self.image_id += 1;
            let (iw, ih) = (image.pixmap.width() as f64, image.pixmap.height() as f64);
            let (tw, th) = (frame.width(), frame.height());
            let _ = write!(
                self.buf,
                r#"<defs><pattern id="img{id}" patternUnits="userSpaceOnUse" x="{x:.2}" y="{y:.2}" width="{iw:.2}" height="{ih:.2}"><image x="0" y="0" width="{iw:.2}" height="{ih:.2}" href="{data_uri}" preserveAspectRatio="none"{rendering}/></pattern></defs>"#
            );
            let _ = writeln!(
                self.buf,
                r#"<rect x="{x:.2}" y="{y:.2}" width="{tw:.2}" height="{th:.2}" fill="url(#img{id})"{op}/>"#
            );
            return;
        }
        let el = format!(
            r#"<image x="{:.2}" y="{:.2}" width="{:.2}" height="{:.2}" href="{}" preserveAspectRatio="{}"{op}{rendering}/>"#,
            frame.min_x(),
            frame.min_y(),
            w,
            h,
            data_uri,
            image.preserve_aspect_ratio(),
        );
        self.buf.push_str(&el);
        self.buf.push('\n');
    }

    fn push_transform(&mut self, t: Transform) {
        let m = format!(
            r#"<g transform="matrix({:.6} {:.6} {:.6} {:.6} {:.6} {:.6})">"#,
            t.a, t.b, t.c, t.d, t.e, t.f
        );
        self.buf.push_str(&m);
    }

    fn pop_transform(&mut self) {
        self.buf.push_str("</g>");
    }

    fn push_opacity(&mut self, opacity: f64) {
        let m = format!(r#"<g opacity="{:.3}">"#, opacity);
        self.buf.push_str(&m);
    }

    fn pop_opacity(&mut self) {
        self.buf.push_str("</g>");
    }

    fn push_blend(&mut self, mode: BlendMode) {
        match mode.css_keyword() {
            Some(kw) => {
                let m = format!(r#"<g style="mix-blend-mode:{kw}">"#);
                self.buf.push_str(&m);
            }
            // Porter-Duff ops have no `mix-blend-mode` equivalent: emit a plain group so push/pop
            // stay balanced (the op is raster-only; SVG degrades to `Normal`).
            None => self.buf.push_str("<g>"),
        }
    }

    fn pop_blend(&mut self) {
        self.buf.push_str("</g>");
    }

    fn push_mask(&mut self, mask: &crate::scene::Mask) {
        let id = self.mask_id;
        self.mask_id += 1;
        let d = mask.shape.to_bezpath().to_svg();
        // `mask_fill_attr` may push gradient `<defs>` into `buf`; `d` is already materialised, so
        // the mask `<defs>` below is emitted after them (SVG allows multiple `<defs>`).
        let fill_attr = self.mask_fill_attr(&mask.fill);
        // `mask-type="alpha"` 是关键:SVG `<mask>` 默认按 **luminance** 取值,而 IR 合同
        // (`scene::Mask`)与 vello 端(`Mask::new_alpha`)都是 **alpha** 遮罩——不声明的话,
        // 不透明黑遮罩在 SVG 端亮度为 0(全隐藏)、vello 端 alpha=255(全显示)。
        let defs = format!(
            r#"<defs><mask id="mask{id}" mask-type="alpha" maskContentUnits="userSpaceOnUse"><path d="{d}"{fill_attr}/></mask></defs>"#
        );
        self.buf.push_str(&defs);
        let m = format!(r#"<g mask="url(#mask{id})">"#);
        self.buf.push_str(&m);
    }

    fn pop_mask(&mut self) {
        self.buf.push_str("</g>");
    }

    fn push_filter(&mut self, filter: &crate::scene::Filter) {
        let id = self.filter_id;
        self.filter_id += 1;
        let prim = match filter {
            crate::scene::Filter::Blur { std_dev } => {
                format!(r#"<feGaussianBlur stdDeviation="{std_dev:.2}"/>"#)
            }
            crate::scene::Filter::DropShadow {
                dx,
                dy,
                std_dev,
                color,
            } => {
                let opacity = if color.a == 255 {
                    String::new()
                } else {
                    format!(r#" flood-opacity="{:.3}""#, color.a as f64 / 255.0)
                };
                format!(
                    r##"<feDropShadow dx="{dx:.2}" dy="{dy:.2}" stdDeviation="{std_dev:.2}" flood-color="#{:02x}{:02x}{:02x}"{opacity}/>"##,
                    color.r, color.g, color.b
                )
            }
        };
        // Generous filter region: the default -10%/120% of the bbox would clip the blur / shadow.
        let defs = format!(
            r#"<defs><filter id="filter{id}" x="-50%" y="-50%" width="200%" height="200%" filterUnits="objectBoundingBox">{prim}</filter></defs>"#
        );
        self.buf.push_str(&defs);
        let m = format!(r#"<g filter="url(#filter{id})">"#);
        self.buf.push_str(&m);
    }

    fn pop_filter(&mut self) {
        self.buf.push_str("</g>");
    }

    fn push_name(&mut self, name: Option<&str>) {
        match name {
            Some(id) => self
                .buf
                .push_str(&format!(r#"<g id="{}">"#, escape_attr(id))),
            None => self.buf.push_str("<g>"),
        }
    }

    fn pop_name(&mut self) {
        self.buf.push_str("</g>");
    }

    fn push_clip(&mut self, clip: &crate::scene::Clip) {
        let id = self.clip_id;
        self.clip_id += 1;
        // Map a Clip to a native SVG element inside <clipPath>.
        let inner = match clip {
            crate::scene::Clip::Rect(rect) => format!(
                r#"<rect x="{:.2}" y="{:.2}" width="{:.2}" height="{:.2}"/>"#,
                rect.min_x(),
                rect.min_y(),
                rect.width(),
                rect.height()
            ),
            crate::scene::Clip::RoundedRect { rect, radius } => format!(
                r#"<rect x="{:.2}" y="{:.2}" width="{:.2}" height="{:.2}" rx="{:.2}"/>"#,
                rect.min_x(),
                rect.min_y(),
                rect.width(),
                rect.height(),
                radius
            ),
            crate::scene::Clip::Circle { center, radius } => format!(
                r#"<circle cx="{:.2}" cy="{:.2}" r="{:.2}"/>"#,
                center.x, center.y, radius
            ),
            crate::scene::Clip::Ellipse {
                center,
                radii,
                rotation,
            } => {
                let rot = if *rotation != 0.0 {
                    format!(
                        r#" transform="rotate({:.2} {:.2} {:.2})""#,
                        rotation.to_degrees(),
                        center.x,
                        center.y
                    )
                } else {
                    String::new()
                };
                format!(
                    r#"<ellipse cx="{:.2}" cy="{:.2}" rx="{:.2}" ry="{:.2}"{} />"#,
                    center.x, center.y, radii.x, radii.y, rot
                )
            }
            crate::scene::Clip::Path(path) => {
                format!(r#"<path d="{}"/>"#, path.to_svg())
            }
        };
        let defs = format!(
            r#"<defs><clipPath id="clip{}">{}</clipPath></defs>"#,
            id, inner
        );
        self.buf.push_str(&defs);
        let m = format!(r#"<g clip-path="url(#clip{})">"#, id);
        self.buf.push_str(&m);
    }

    fn pop_clip(&mut self) {
        self.buf.push_str("</g>");
    }

    fn push_color_matrix(&mut self, matrix: ColorMatrix) {
        // Compose with the enclosing scope so a child's matrix is applied to the raw colours and
        // its ancestors' afterwards.
        let composed = match self.color_matrices.last() {
            Some(outer) => matrix.then(*outer),
            None => matrix,
        };
        self.color_matrices.push(composed);
    }

    fn pop_color_matrix(&mut self) {
        self.color_matrices.pop();
    }

    fn push_antialias(&mut self, enabled: bool) {
        self.antialias_stack.push(enabled);
    }

    fn pop_antialias(&mut self) {
        self.antialias_stack.pop();
    }
}

impl SvgRenderer {
    /// The colour matrix currently baked into paint colours (identity outside any such scope).
    fn current_color_matrix(&self) -> ColorMatrix {
        self.color_matrices
            .last()
            .copied()
            .unwrap_or(ColorMatrix::IDENTITY)
    }

    /// A colour attribute fragment with the active colour matrix baked into `c`.
    fn color_attr(&self, prefix: &str, c: Color) -> String {
        color_attr_str(prefix, self.current_color_matrix().apply(c))
    }

    /// Whether shapes are currently anti-aliased (the default outside any such scope).
    fn current_antialias(&self) -> bool {
        self.antialias_stack.last().copied().unwrap_or(true)
    }

    /// Append the shape-rendering hint when the active scope turns anti-aliasing off.
    fn append_antialias_hint(&self, el: &mut String) {
        if !self.current_antialias() {
            let _ = write!(el, r#" shape-rendering="crispEdges""#);
        }
    }

    /// A ` fill="…"` attribute for mask content (same emission as a normal fill).
    ///
    /// Two deviations, both deliberate: a sketch fill uses its flat pen colour (a mask only reads
    /// the paint's *alpha*, and a `<pattern>` would make the mask depend on the tile phase), and a
    /// sweep gradient degrades to the colour at the middle of its ramp (wedge geometry is a poor
    /// fit for a `<mask>`).
    fn mask_fill_attr(&mut self, fill: &Fill) -> String {
        match fill {
            // A mask's paint is *scope machinery*, not subtree content: it is never colour-filtered.
            Fill::Sketch(sf) => color_attr_str("fill", sf.color),
            Fill::SweepGradient(g) => {
                color_attr_str("fill", g.sample(0.5 * (g.start_angle + g.end_angle)))
            }
            other => self.fill_attr(other, ColorMatrix::IDENTITY),
        }
    }

    fn apply_fill_stroke(&mut self, el: &mut String, style: &FillStrokeStyle, bbox: Rect) {
        match &style.fill {
            // A sweep gradient has no SVG paint: bake it into clipped wedges *before* the shape and
            // leave the shape itself unfilled (its stroke, if any, is drawn on top).
            Some(Fill::SweepGradient(g)) => {
                self.emit_sweep_overlay(el, g, bbox);
                let _ = write!(el, r#" fill="none""#);
            }
            Some(fill) => {
                let matrix = self.current_color_matrix();
                el.push_str(&self.fill_attr(fill, matrix));
            }
            None => {
                let _ = write!(el, r#" fill="none""#);
            }
        }
        if let Some(s) = &style.stroke {
            self.append_stroke(el, s);
        }
        self.append_antialias_hint(el);
    }

    /// Emit a `<linearGradient>` `<defs>` into `buf` and return the matching ` fill="url(#…)"`.
    fn linear_gradient_fill(&mut self, g: &LinearGradient, matrix: ColorMatrix) -> String {
        let gid = self.next_gradient_id();
        let stops: String = g.stops.iter().map(|s| stop_svg(s, matrix)).collect();
        let defs = format!(
            r#"<defs><linearGradient id="grad{gid}" gradientUnits="userSpaceOnUse" x1="{:.2}" y1="{:.2}" x2="{:.2}" y2="{:.2}"{}>{stops}</linearGradient></defs>"#,
            g.start.x,
            g.start.y,
            g.end.x,
            g.end.y,
            spread_attr(g.spread),
        );
        self.buf.push_str(&defs);
        format!(r#" fill="url(#grad{gid})""#)
    }

    /// A ` fill="…"` attribute for `fill`, emitting gradient / pattern `<defs>` into `buf` as
    /// needed.
    ///
    /// Sweep gradients are **not** painted here — SVG (and the browsers) have no conic paint. See
    /// [`SvgRenderer::emit_sweep_overlay`], which bakes the ramp into clipped geometry and returns
    /// `fill="none"`.
    fn fill_attr(&mut self, fill: &Fill, matrix: ColorMatrix) -> String {
        match fill {
            Fill::Solid(c) => color_attr_str("fill", matrix.apply(*c)),
            Fill::Sketch(sf) => {
                let pid = self.sketch_pattern(sf, matrix);
                format!(r#" fill="url(#sk{pid})""#)
            }
            Fill::LinearGradient(g) => self.linear_gradient_fill(g, matrix),
            Fill::RadialGradient(g) => {
                let gid = self.next_gradient_id();
                let stops: String = g.stops.iter().map(|s| stop_svg(s, matrix)).collect();
                let defs = format!(
                    r#"<defs><radialGradient id="grad{gid}" gradientUnits="userSpaceOnUse" cx="{:.2}" cy="{:.2}" r="{:.2}"{}>{stops}</radialGradient></defs>"#,
                    g.center.x,
                    g.center.y,
                    g.radius,
                    spread_attr(g.spread),
                );
                self.buf.push_str(&defs);
                format!(r#" fill="url(#grad{gid})""#)
            }
            // Handled by the caller (see `apply_fill_stroke`).
            Fill::SweepGradient(_) => r#" fill="none""#.to_string(),
            Fill::Image(f) => {
                // One `<pattern>` per fill: the bitmap is stretched into the tile cell and the
                // pattern repeats it across the shape.
                let id = self.image_id;
                self.image_id += 1;
                let data_uri = image_data_uri(&f.image);
                let (x, y) = (f.tile.min_x(), f.tile.min_y());
                let (w, h) = (f.tile.width(), f.tile.height());
                let defs = format!(
                    r#"<defs><pattern id="img{id}" patternUnits="userSpaceOnUse" x="{x:.2}" y="{y:.2}" width="{w:.2}" height="{h:.2}"><image x="0" y="0" width="{w:.2}" height="{h:.2}" href="{data_uri}" preserveAspectRatio="none"/></pattern></defs>"#
                );
                self.buf.push_str(&defs);
                format!(r#" fill="url(#img{id})""#)
            }
        }
    }

    /// Approximate a sweep (conic) gradient with clipped pie wedges.
    ///
    /// SVG has no conic paint, so the ramp is **baked into geometry**: the shape's own markup
    /// (everything already written into `el`, minus the final `/>`) becomes a `<clipPath>`, and
    /// `SWEEP_WEDGES` solid wedges — one per sector, sampled at the sector's mid angle with the
    /// spread applied — are painted inside it. `bbox` is the shape's bounds and only has to give a
    /// radius that reaches the farthest corner; the clip trims everything outside the shape.
    fn emit_sweep_overlay(&mut self, shape: &str, g: &SweepGradient, bbox: Rect) {
        let cid = self.next_gradient_id();
        let _ = write!(
            self.buf,
            r#"<defs><clipPath id="swc{cid}">{shape}/></clipPath></defs><g clip-path="url(#swc{cid})">"#
        );
        let (cx, cy) = (g.center.x, g.center.y);
        // Farthest bbox corner from the centre; never below 1pt so a degenerate box still paints.
        let x0 = bbox.min_x().min(bbox.max_x());
        let x1 = bbox.min_x().max(bbox.max_x());
        let y0 = bbox.min_y().min(bbox.max_y());
        let y1 = bbox.min_y().max(bbox.max_y());
        let r = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
            .iter()
            .map(|&(x, y)| (x - cx).hypot(y - cy))
            .fold(1.0_f64, f64::max);
        // A whole turn is always painted (the ramp's `spread` decides what the angles outside
        // `start_angle..end_angle` look like), so `Pad` clamps and `Repeat` / `Reflect` tile.
        let step = std::f64::consts::TAU / SWEEP_WEDGES as f64;
        let large = u8::from(step > std::f64::consts::PI);
        let matrix = self.current_color_matrix();
        for i in 0..SWEEP_WEDGES {
            let a0 = g.start_angle + step * i as f64;
            let a1 = a0 + step;
            // Sample at the wedge's angle **mod 2π**: the raster backend evaluates the ramp at the
            // per-pixel unit angle in `[0, 2π)`, so a partial ramp's out-of-range behaviour is
            // decided by the *wrapped* position — angles just below `start_angle` take the start
            // colour (Pad) / mirrored colours (Reflect), while only angles past `end_angle` (but
            // before a full turn) take the end colour. Sampling the unwrapped angle instead would
            // paint the whole `[end_angle, start_angle)` gap with the end colour, creating a
            // visible seam mismatch against vello whenever `start_angle ≠ 0`.
            let mid = (0.5 * (a0 + a1)).rem_euclid(std::f64::consts::TAU);
            let color = matrix.apply(g.sample(mid));
            let (p0x, p0y) = (cx + r * a0.cos(), cy + r * a0.sin());
            let (p1x, p1y) = (cx + r * a1.cos(), cy + r * a1.sin());
            let fill = color_attr_str("fill", color);
            let _ = write!(
                self.buf,
                r#"<path d="M {cx:.2} {cy:.2} L {p0x:.2} {p0y:.2} A {r:.2} {r:.2} 0 {large} 1 {p1x:.2} {p1y:.2} Z"{fill}/>"#
            );
        }
        self.buf.push_str("</g>");
    }

    /// Emit (or reuse) the `<pattern>` for a hand-drawn fill, returning its numeric id.
    ///
    /// Two things make this work:
    /// - **The tile is axis-aligned; the angle lives in `patternTransform`.** Drawing the
    ///   diagonal inside the tile leaves visible seams at every tile edge for most angles, while
    ///   rotating a tile that contains a plain vertical line tiles seamlessly at *any* angle.
    /// - **Content is inset by half the stroke weight.** A pattern tile clips at its edges, so a
    ///   line sitting exactly at `x = 0` would survive at half weight with a matching gap in the
    ///   neighbour tile.
    ///
    /// The pool is keyed by the whole [`SketchFill`] (colour, style, angle, gap, weight) **and the
    /// active colour matrix** — the tile's ink is baked with it — so N identical shapes still cost
    /// exactly one `<pattern>`.
    fn sketch_pattern(&mut self, sf: &SketchFill, matrix: ColorMatrix) -> usize {
        if let Some(id) = self
            .patterns
            .iter()
            .position(|(f, m)| f == sf && *m == matrix)
        {
            return id;
        }
        let id = self.patterns.len();
        self.patterns.push((sf.clone(), matrix));

        let gap = sf.gap();
        let w = sf.weight();
        let inset = (w * 0.5).min(gap * 0.25);
        let a = inset;
        let b = gap - inset;
        let mid = gap * 0.5;
        // cross-hatch = two orthogonal families; rotating a "vertical + horizontal" tile by
        // angle+45 yields exactly {angle-45, angle+45}, i.e. rough.js' cross-hatch.
        let angle = match sf.style {
            SketchFillStyle::CrossHatch => sf.angle + 45.0,
            _ => sf.angle,
        };
        let content = match sf.style {
            SketchFillStyle::Hachure => format!(
                r#"<line x1="{mid:.2}" y1="0" x2="{mid:.2}" y2="{gap:.2}"{stroke} stroke-width="{w:.2}"/>"#,
                stroke = color_attr_str("stroke", matrix.apply(sf.color))
            ),
            SketchFillStyle::CrossHatch => format!(
                r#"<line x1="{mid:.2}" y1="0" x2="{mid:.2}" y2="{gap:.2}"{stroke} stroke-width="{w:.2}"/><line x1="0" y1="{mid:.2}" x2="{gap:.2}" y2="{mid:.2}"{stroke} stroke-width="{w:.2}"/>"#,
                stroke = color_attr_str("stroke", matrix.apply(sf.color))
            ),
            SketchFillStyle::Zigzag => format!(
                r#"<polyline fill="none" points="{a:.2},0 {b:.2},{q:.2} {a:.2},{m:.2} {b:.2},{t:.2} {a:.2},{gap:.2}"{stroke} stroke-width="{w:.2}"/>"#,
                q = gap * 0.25,
                m = gap * 0.5,
                t = gap * 0.75,
                stroke = color_attr_str("stroke", matrix.apply(sf.color))
            ),
            SketchFillStyle::Dots => format!(
                r#"<circle cx="{mid:.2}" cy="{mid:.2}" r="{r:.2}"{fill}/>"#,
                r = crate::sketch::fill::dot_radius(sf),
                fill = color_attr_str("fill", matrix.apply(sf.color))
            ),
        };
        let defs = format!(
            r#"<defs><pattern id="sk{id}" width="{gap:.2}" height="{gap:.2}" patternUnits="userSpaceOnUse" patternTransform="rotate({angle:.2})">{content}</pattern></defs>"#
        );
        self.buf.push_str(&defs);
        id
    }

    fn apply_stroke_only(&self, el: &mut String, style: &Stroke) {
        // SVG shapes default to a black fill; stroke-only elements must explicitly turn off the
        // fill, otherwise the browser would fill the polyline/arc area black.
        let _ = write!(el, r#" fill="none""#);
        self.append_stroke(el, style);
        self.append_antialias_hint(el);
    }

    fn append_stroke(&self, el: &mut String, s: &Stroke) {
        el.push_str(&self.color_attr("stroke", s.color));
        let _ = write!(
            el,
            r#" stroke-width="{:.2}" stroke-miterlimit="{:.2}""#,
            s.width, s.miter_limit
        );
        let cap = match s.line_cap {
            LineCap::Butt => "butt",
            LineCap::Round => "round",
            LineCap::Square => "square",
        };
        let join = match s.line_join {
            LineJoin::Miter => "miter",
            LineJoin::Round => "round",
            LineJoin::Bevel => "bevel",
        };
        let _ = write!(
            el,
            r#" stroke-linecap="{}" stroke-linejoin="{}""#,
            cap, join
        );
        if !s.dash_array.is_empty() {
            let da = s
                .dash_array
                .iter()
                .map(|d| format!("{:.2}", d))
                .collect::<Vec<_>>()
                .join(",");
            let _ = write!(el, r#" stroke-dasharray="{}""#, da);
            if s.dash_offset != 0.0 {
                let _ = write!(el, r#" stroke-dashoffset="{:.2}""#, s.dash_offset);
            }
        }
    }

    /// Rich-text `<tspan>` body: one line-`<tspan>` per physical line, plus one style-`<tspan>`
    /// per span fragment inside each line.
    ///
    /// Multi-span colors / sizes / weights / families and explicit `\n` breaks are preserved,
    /// which a single flat `<text>` cannot express. Fragments that match the block style carry
    /// no attributes and inherit the outer `<text>`. Returns an empty string when there is no
    /// text to lay out.
    fn rich_text_tspans(
        &self,
        spans: &[crate::text::RichSpan],
        x: f64,
        base: &TextStyle,
        metrics: Option<&crate::text::TextMetrics>,
    ) -> String {
        // 行距:显式 line_height > 布局首行行高 > 1.2×font-size。
        let line_h = base.line_height.unwrap_or_else(|| {
            metrics
                .filter(|m| m.line_height > 0.0)
                .map_or(base.font_size * 1.2, |m| m.line_height)
        });
        // 切行:`\n` 是换行;同一行内的片段保持各自的样式。空行保留以维持行距。
        let mut lines: Vec<Vec<(&str, &TextStyle)>> = vec![Vec::new()];
        for span in spans {
            for (i, seg) in span.text.split('\n').enumerate() {
                if i > 0 {
                    lines.push(Vec::new());
                }
                lines
                    .last_mut()
                    .expect("lines starts with one empty line")
                    .push((seg, &span.style));
            }
        }
        // 文本末尾的换行不产生额外空行(与 parley 一致)。
        while lines.len() > 1 && lines.last().is_some_and(|l| l.is_empty()) {
            lines.pop();
        }
        let mut out = String::new();
        for (i, segs) in lines.iter().enumerate() {
            let dy = if i == 0 { 0.0 } else { line_h };
            let _ = write!(out, r#"<tspan x="{:.2}" dy="{:.2}">"#, x, dy);
            if segs.is_empty() {
                // 显式空行:零宽占位符保住行高(空 tspan 会被浏览器折叠)。
                out.push_str("&#8203;");
            } else {
                for (text, span_style) in segs {
                    let _ = write!(out, "<tspan{}>", self.rich_span_attrs(span_style, base));
                    out.push_str(&escape_text(text));
                    out.push_str("</tspan>");
                }
            }
            out.push_str("</tspan>");
        }
        out
    }

    /// Per-span typographic attribute overrides relative to the block style. Empty when the
    /// span matches the block (it then inherits the outer `<text>` attributes).
    fn rich_span_attrs(&self, span: &TextStyle, base: &TextStyle) -> String {
        let mut attrs = String::new();
        if span.font_family != base.font_family {
            let _ = write!(
                attrs,
                r#" font-family="{}""#,
                escape_attr(&span.font_family_css())
            );
        }
        if (span.font_size - base.font_size).abs() > f64::EPSILON {
            let _ = write!(attrs, r#" font-size="{:.2}""#, span.font_size);
        }
        if span.color != base.color {
            attrs.push_str(&self.color_attr("fill", span.color));
        }
        if span.font_weight != base.font_weight {
            let _ = write!(attrs, r#" font-weight="{:.0}""#, span.font_weight.value());
        }
        if span.font_style != base.font_style {
            let f = match span.font_style {
                crate::text::FontStyle::Normal => "normal",
                crate::text::FontStyle::Italic => "italic",
                crate::text::FontStyle::Oblique => "oblique",
            };
            let _ = write!(attrs, r#" font-style="{f}""#);
        }
        if span.font_width != base.font_width {
            let _ = write!(
                attrs,
                r#" font-stretch="{:.0}%""#,
                span.font_width.ratio() * 100.0
            );
        }
        if span.letter_spacing != base.letter_spacing {
            let _ = write!(attrs, r#" letter-spacing="{:.2}""#, span.letter_spacing);
        }
        // text-decoration 可继承;只有与块级默认不同才输出(含显式取消)。
        if span.underline != base.underline || span.strikethrough != base.strikethrough {
            let _ = write!(
                attrs,
                r#" text-decoration="{}""#,
                deco_keyword(span.underline, span.strikethrough)
            );
        }
        attrs
    }
}

/// SVG color attribute fragment: ` prefix="#rrggbb"`, with a translucent color also emitting
/// ` prefix-opacity="…"`.
///
/// 8-digit hex (`#rrggbbaa`) is CSS Color 4 / SVG 2 only and is rejected by many
/// SVG → PDF / SVG 1.1 consumers; the alpha channel is therefore always split into a separate
/// `fill-opacity` / `stroke-opacity` attribute (consistent with how gradient stops use
/// `stop-opacity`). An opaque color produces exactly the old ` prefix="#rrggbb"` form.
fn color_attr_str(prefix: &str, c: Color) -> String {
    // 注意:必须用 r## —— 字面量 `"#`(引号后的 # 属于 hex 前缀)会提前终止 r#" 字符串。
    let mut s = format!(r##" {prefix}="#{:02x}{:02x}{:02x}""##, c.r, c.g, c.b);
    if c.a != 255 {
        s.push_str(&format!(r#" {prefix}-opacity="{:.3}""#, c.a as f64 / 255.0));
    }
    s
}

/// text-decoration keyword for an underline / strikethrough pair (used per span and for the
/// block-level default).
fn deco_keyword(underline: bool, strikethrough: bool) -> &'static str {
    match (underline, strikethrough) {
        (false, false) => "none",
        (true, false) => "underline",
        (false, true) => "line-through",
        (true, true) => "underline line-through",
    }
}

/// Number of wedges used to approximate a sweep gradient in SVG (2π/120 = 3° per step).
const SWEEP_WEDGES: usize = 120;

/// PNG-encode a bitmap into a `data:` URI (the browser decodes it).
fn image_data_uri(pixmap: &crate::Pixmap) -> String {
    format!("data:image/png;base64,{}", base64_encode(&pixmap.to_png()))
}

/// A square box of half-side `r` around `center` (bounds helper for sweep overlay radii).
fn square_bbox(center: Point, r: f64) -> Rect {
    Rect::new(center.x - r, center.y - r, center.x + r, center.y + r)
}

/// Bounding box of a point list (an empty list yields an empty box at the origin).
fn points_bbox(points: &[Point]) -> Rect {
    let Some(first) = points.first() else {
        return Rect::ZERO;
    };
    points
        .iter()
        .fold(Rect::new(first.x, first.y, first.x, first.y), |r, p| {
            Rect::new(
                r.min_x().min(p.x),
                r.min_y().min(p.y),
                r.max_x().max(p.x),
                r.max_y().max(p.y),
            )
        })
}

/// The ` spreadMethod` fragment for a gradient. `Pad` is the SVG default, so it is omitted
/// (keeping the common case byte-identical to before).
fn spread_attr(spread: GradientSpread) -> &'static str {
    match spread {
        GradientSpread::Pad => "",
        GradientSpread::Repeat => r#" spreadMethod="repeat""#,
        GradientSpread::Reflect => r#" spreadMethod="reflect""#,
    }
}

/// A gradient stop, with `matrix` baked into its colour. `stop-color` always uses the 6-digit
/// form; a translucent stop carries its alpha through `stop-opacity`. 8-digit hex is CSS Color 4 /
/// SVG 2 only and is rejected by many SVG -> PDF / SVG 1.1 consumers.
fn stop_svg(s: &GradientStop, matrix: ColorMatrix) -> String {
    let color = matrix.apply(s.color);
    let opacity = if color.a == 255 {
        String::new()
    } else {
        format!(r#" stop-opacity="{:.3}""#, f64::from(color.a) / 255.0)
    };
    format!(
        r##"<stop offset="{:.3}" stop-color="#{:02x}{:02x}{:02x}"{} />"##,
        s.offset, color.r, color.g, color.b, opacity
    )
}

/// Build the SVG path `d` for an arc / pie sector (using the native arc command `A` rather than
/// a Bézier approximation).
///
/// A full turn (|sweep| ≥ 360°) is emitted as **two** 180° arcs: per the SVG spec an `A`
/// segment whose start and end points coincide is dropped entirely, which would make a
/// 100%-slice pie (or a full circle stroke) render nothing on the SVG backend while the
/// raster backend draws a full circle.
fn arc_path_d(
    center: Point,
    radii: Vec2,
    start_angle: f64,
    sweep_angle: f64,
    sector: bool,
) -> String {
    let point_at = |angle: f64| -> (f64, f64) {
        (
            center.x + radii.x * angle.cos(),
            center.y + radii.y * angle.sin(),
        )
    };
    // 整圆(|sweep| ≥ 360°)拆成两段 180°:SVG 规范规定起终点重合的 A 段被整体忽略。
    let segments: Vec<(f64, f64)> = if sweep_angle.abs() >= std::f64::consts::TAU - 1e-9 {
        let half = sweep_angle / 2.0;
        vec![(start_angle, half), (start_angle + half, half)]
    } else {
        vec![(start_angle, sweep_angle)]
    };

    let mut d = String::new();
    let start = point_at(start_angle);
    if sector {
        // 扇形:M center L start [A ...]+ Z(与栅格端的 "M center L start [弧] end Z" 一致)。
        let _ = write!(
            d,
            "M {:.2} {:.2} L {:.2} {:.2}",
            center.x, center.y, start.0, start.1
        );
    } else {
        let _ = write!(d, "M {:.2} {:.2}", start.0, start.1);
    }
    for (a, s) in segments {
        // 大弧标志按单段弧度判断(拆分后每段恒为 180°,取 0 更稳妥)。
        let large_arc = if s.abs() > std::f64::consts::PI { 1 } else { 0 };
        // y-down 坐标系:正向 sweep = 顺时针 = SVG sweep-flag 1。
        let sweep_flag = if s >= 0.0 { 1 } else { 0 };
        let end = point_at(a + s);
        let _ = write!(
            d,
            " A {:.2} {:.2} 0 {} {} {:.2} {:.2}",
            radii.x, radii.y, large_arc, sweep_flag, end.0, end.1
        );
    }
    if sector {
        d.push_str(" Z");
    }
    d
}

/// XML text escaping (for `<text>` content).
fn escape_text(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            _ => out.push(c),
        }
    }
    out
}

fn escape_attr(s: &str) -> String {
    escape_text(s).replace('"', "&quot;")
}

/// Minimal base64 encoding (for SVG `data:` URIs), avoiding an extra dependency.
fn base64_encode(data: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
    for chunk in data.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
        let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
        let n = (b0 << 16) | (b1 << 8) | b2;
        out.push(ALPHABET[((n >> 18) & 0x3f) as usize] as char);
        out.push(ALPHABET[((n >> 12) & 0x3f) as usize] as char);
        if chunk.len() > 1 {
            out.push(ALPHABET[((n >> 6) & 0x3f) as usize] as char);
        } else {
            out.push('=');
        }
        if chunk.len() > 2 {
            out.push(ALPHABET[(n & 0x3f) as usize] as char);
        } else {
            out.push('=');
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::Vec2;
    use crate::scene::{Element, Scene, SceneNode};
    use crate::text::{FontStyle, FontWeight, FontWidth, TextAlign, TextBaseline, TextStyle};

    fn render(scene: &Scene) -> String {
        let mut svg = SvgRenderer::new(scene.width, scene.height).with_background(scene.background);
        scene.render(&mut svg);
        svg.into_string()
    }

    /// BlendMode 输出为 `mix-blend-mode`(Normal 不输出)。
    #[test]
    fn blend_mode_emits_mix_blend_mode() {
        let mut scene = Scene::new(20.0, 20.0);
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 20.0, 20.0),
                FillStrokeStyle::fill(Color::rgb(0x80, 0x80, 0x80)),
            ))
            .with_blend_mode(BlendMode::Multiply),
        );
        let out = render(&scene);
        assert!(out.contains("mix-blend-mode:multiply"), "{out}");
        // Normal 节点不产生 blend 包装。
        let mut plain = Scene::new(20.0, 20.0);
        plain.push(Element::rect(
            Rect::new(0.0, 0.0, 20.0, 20.0),
            FillStrokeStyle::fill(Color::BLACK),
        ));
        assert!(!render(&plain).contains("mix-blend-mode"));
    }

    /// Porter-Duff 无法用 `mix-blend-mode` 表达:SVG 端退化为普通 `<g>`(不输出 blend)。
    #[test]
    fn porter_duff_degrades_without_mix_blend_mode() {
        let mut scene = Scene::new(20.0, 20.0);
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 10.0, 10.0),
                FillStrokeStyle::fill(Color::BLACK),
            ))
            .with_blend_mode(BlendMode::Clear),
        );
        let out = render(&scene);
        assert!(!out.contains("mix-blend-mode"), "{out}");
        assert!(BlendMode::Clear.is_porter_duff());
        assert!(!BlendMode::Multiply.is_porter_duff());
    }

    /// Mask 输出 `<mask>` 定义 + `mask="url(#mask0)"`。
    #[test]
    fn mask_emits_svg_mask() {
        let mut scene = Scene::new(20.0, 20.0);
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 20.0, 20.0),
                FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
            ))
            .with_mask(crate::scene::Mask::new(crate::scene::Clip::Rect(
                Rect::new(0.0, 0.0, 10.0, 20.0),
            ))),
        );
        let out = render(&scene);
        assert!(out.contains(r#"<mask id="mask0""#), "{out}");
        assert!(out.contains(r#"mask="url(#mask0)""#), "{out}");
    }

    /// Filter 输出 `<filter>` 定义(feGaussianBlur / feDropShadow)+ `filter="url(#filterN)"`。
    #[test]
    fn filter_emits_svg_filter() {
        let make = |f: crate::scene::Filter| {
            let mut scene = Scene::new(20.0, 20.0);
            scene.push_node(
                SceneNode::new(Element::rect(
                    Rect::new(0.0, 0.0, 10.0, 10.0),
                    FillStrokeStyle::fill(Color::BLACK),
                ))
                .with_filter(f),
            );
            render(&scene)
        };
        let blur = make(crate::scene::Filter::blur(2.0));
        assert!(blur.contains(r#"<filter id="filter0""#), "{blur}");
        assert!(blur.contains("feGaussianBlur"), "{blur}");
        assert!(blur.contains(r#"filter="url(#filter0)""#), "{blur}");

        let shadow = make(crate::scene::Filter::drop_shadow(
            3.0,
            3.0,
            2.0,
            Color::rgba(0x00, 0x00, 0x00, 128),
        ));
        assert!(shadow.contains("feDropShadow"), "{shadow}");
        assert!(shadow.contains(r#"flood-opacity="0.502""#), "{shadow}");
    }

    #[test]
    fn scene_metadata_title_desc_scale() {
        let scene = Scene::new(100.0, 50.0)
            .with_title("T")
            .with_description("D")
            .with_scale(2.0);
        // 尺寸收敛后:渲染器尺寸 = 输出尺寸;viewBox = 输出尺寸 / scale。
        // 这里显式传 scene 尺寸 → 输出 100×50,用户坐标系 50×25。
        let out = render(&scene);
        assert!(out.contains("<title>T</title>"));
        assert!(out.contains("<desc>D</desc>"));
        assert!(out.contains(r#"width="100.00" height="50.00" viewBox="0 0 50.00 25.00""#));
    }

    /// 未显式给出尺寸时回落为"scene 尺寸 × scale"(保持"scale 放大导出"的旧行为)。
    #[test]
    fn size_fallback_multiplies_scene_by_scale() {
        let scene = Scene::new(100.0, 50.0).with_scale(2.0);
        let mut svg = SvgRenderer::new(0.0, 0.0);
        scene.render(&mut svg);
        let out = svg.into_string();
        assert!(
            out.contains(r#"width="200.00" height="100.00" viewBox="0 0 100.00 50.00""#),
            "回落应把 scene 尺寸 × scale 作为输出尺寸,实际: {out}"
        );
        // 背景矩形应覆盖整个用户坐标系(viewBox 尺寸),而非输出尺寸。
        assert!(out.contains(r##"width="100.00" height="50.00" fill="#ffffff""##));
    }

    #[test]
    fn ellipse_rounded_rect_polygon_native_tags() {
        let mut scene = Scene::new(200.0, 200.0);
        scene.push(Element::ellipse(
            Point::new(10.0, 10.0),
            Vec2::new(30.0, 15.0),
            0.0,
            FillStrokeStyle::fill(Color::BLACK),
        ));
        scene.push(Element::rounded_rect(
            Rect::new(50.0, 50.0, 90.0, 70.0),
            5.0,
            FillStrokeStyle::fill(Color::BLACK),
        ));
        scene.push(Element::polygon(
            vec![
                Point::new(0.0, 0.0),
                Point::new(10.0, 0.0),
                Point::new(5.0, 10.0),
            ],
            FillStrokeStyle::fill(Color::BLACK),
        ));
        let out = render(&scene);
        assert!(out.contains("<ellipse cx=\"10.00\" cy=\"10.00\" rx=\"30.00\" ry=\"15.00\""));
        assert!(
            out.contains(r#"<rect x="50.00" y="50.00" width="40.00" height="20.00" rx="5.00""#)
        );
        assert!(out.contains("<polygon points=\"0.00,0.00 10.00,0.00 5.00,10.00\""));
    }

    #[test]
    fn arc_and_pie_native_path() {
        let mut scene = Scene::new(100.0, 100.0);
        scene.push(Element::arc(
            Point::new(50.0, 50.0),
            Vec2::new(40.0, 30.0),
            0.0,
            std::f64::consts::FRAC_PI_2,
            Stroke::new(Color::BLACK, 2.0),
        ));
        scene.push(Element::pie(
            Point::new(50.0, 50.0),
            30.0,
            0.0,
            std::f64::consts::FRAC_PI_2,
            FillStrokeStyle::fill(Color::BLACK),
        ));
        let out = render(&scene);
        // Arcs use the SVG native A command; a pie sector includes the center start point and a
        // Z close.
        assert!(out.contains("A 40.00 30.00"));
        assert!(out.contains("M 50.00 50.00 L "));
        assert!(out.contains(" Z"));
    }

    #[test]
    fn radial_gradient_and_dash() {
        let mut scene = Scene::new(100.0, 100.0);
        let radial = crate::scene::RadialGradient::new(
            Point::new(50.0, 50.0),
            20.0,
            vec![
                GradientStop {
                    offset: 0.0,
                    color: Color::WHITE,
                },
                GradientStop {
                    offset: 1.0,
                    color: Color::BLACK,
                },
            ],
        );
        scene.push(Element::circle(
            Point::new(50.0, 50.0),
            20.0,
            FillStrokeStyle {
                fill: Some(radial.into()),
                stroke: Some(Stroke::dashed(Color::BLACK, 1.0, vec![3.0, 2.0])),
            },
        ));
        let out = render(&scene);
        assert!(out.contains("<radialGradient"));
        assert!(out.contains("gradientUnits=\"userSpaceOnUse\""));
        assert!(out.contains("stroke-dasharray=\"3.00,2.00\""));
        assert!(out.contains("stroke-miterlimit=\"10.00\""));
    }

    /// spread:`Pad` 是 SVG 默认值(不写属性),其余映射到同名的 `spreadMethod`。
    #[test]
    fn gradient_spread_maps_to_spread_method() {
        let grad = LinearGradient::new(
            Point::new(0.0, 0.0),
            Point::new(10.0, 0.0),
            vec![
                GradientStop {
                    offset: 0.0,
                    color: Color::WHITE,
                },
                GradientStop {
                    offset: 1.0,
                    color: Color::BLACK,
                },
            ],
        );
        let scene_with = |g: LinearGradient| {
            let mut s = Scene::new(100.0, 100.0);
            s.push(Element::rect(
                Rect::new(0.0, 0.0, 100.0, 100.0),
                FillStrokeStyle::fill_gradient(g),
            ));
            s
        };
        let pad = render(&scene_with(grad.clone()));
        assert!(!pad.contains("spreadMethod"), "Pad 应省略属性: {pad}");
        let reflect = render(&scene_with(
            grad.clone().with_spread(GradientSpread::Reflect),
        ));
        assert!(reflect.contains(r#"spreadMethod="reflect""#));
        let repeat = render(&scene_with(grad.with_spread(GradientSpread::Repeat)));
        assert!(repeat.contains(r#"spreadMethod="repeat""#));
    }

    /// sweep:SVG 无 conic 画法,退化为「形状作 clipPath + 逐扇区实心填充」,形状自身不再填充。
    #[test]
    fn sweep_gradient_becomes_clipped_wedges() {
        let mut scene = Scene::new(100.0, 100.0);
        let g = crate::scene::SweepGradient::full(
            Point::new(50.0, 50.0),
            0.0,
            vec![
                GradientStop {
                    offset: 0.0,
                    color: Color::rgb(0xff, 0x00, 0x00),
                },
                GradientStop {
                    offset: 1.0,
                    color: Color::rgb(0x00, 0x00, 0xff),
                },
            ],
        );
        scene.push(Element::circle(
            Point::new(50.0, 50.0),
            40.0,
            FillStrokeStyle::fill_gradient(g),
        ));
        let out = render(&scene);
        assert!(out.contains("<clipPath"), "应有裁切路径: {out}");
        assert!(out.contains(r#"clip-path="url(#swc"#));
        assert_eq!(
            out.matches(r#"<path d="M 50.00 50.00 L"#).count(),
            SWEEP_WEDGES,
            "每个扇区一个 wedge"
        );
        assert!(
            out.contains(r#"fill="none""#),
            "形状自身不再填充(由 wedge 着色)"
        );
    }

    /// sweep(部分角度 + Pad):`[0, start_angle)` 的回卷扇区应取**起始色**——与栅格后端
    /// (逐像素按 mod-2π 角度取值,ramp 之前 Pad 钳到起始色)对齐;此前整段
    /// `[end_angle, start_angle)` gap 都被涂成结束色,在 start_angle ≠ 0 时产生可见接缝。
    #[test]
    fn sweep_partial_wrapped_wedges_take_start_color() {
        let mut scene = Scene::new(100.0, 100.0);
        let g = crate::scene::SweepGradient::new(
            Point::new(50.0, 50.0),
            std::f64::consts::FRAC_PI_2,
            std::f64::consts::PI,
            vec![
                GradientStop {
                    offset: 0.0,
                    color: Color::rgb(0xff, 0x00, 0x00),
                },
                GradientStop {
                    offset: 1.0,
                    color: Color::rgb(0x00, 0x00, 0xff),
                },
            ],
        );
        scene.push(Element::circle(
            Point::new(50.0, 50.0),
            40.0,
            FillStrokeStyle::fill_gradient(g),
        ));
        let out = render(&scene);
        // 角度位置 0 处的 wedge:弧起点 (cx+R, cy),R = bbox 最远角距 = 40√2 ≈ 56.57;
        // 该 wedge 的角度回卷后位于 ramp 之前 → 起始色红(修复前被钳到结束色蓝)。
        let anchor = out
            .find(r#"L 106.57 50.00"#)
            .expect("应存在弧起点在角度 0 位置的 wedge");
        let close = out[anchor..]
            .find("/>")
            .map(|i| anchor + i + 2)
            .expect("wedge path 元素应闭合");
        let elem = &out[anchor..close];
        assert!(
            elem.contains(r##"fill="#ff0000""##),
            "角度 0(回卷到 ramp 之前)应为起始色红: {elem}"
        );
    }

    /// 圆角矩形:统一半径走原生 `<rect rx>`(输出与旧版一致),每角半径退化为 `<path>`。
    #[test]
    fn rounded_rect_uniform_uses_rect_per_corner_uses_path() {
        let scene_with = |radii: crate::scene::CornerRadii| {
            let mut s = Scene::new(20.0, 20.0);
            s.push(Element::rounded_rect(
                Rect::new(0.0, 0.0, 20.0, 20.0),
                radii,
                FillStrokeStyle::fill(Color::BLACK),
            ));
            s
        };
        let uniform = render(&scene_with(3.0.into()));
        assert!(
            uniform.contains(r#"<rect x="0.00" y="0.00" width="20.00" height="20.00" rx="3.00""#)
        );

        let per_corner = render(&scene_with(crate::scene::CornerRadii::new(
            6.0, 0.0, 0.0, 0.0,
        )));
        assert!(
            !per_corner.contains("rx="),
            "每角半径不能用 <rect rx>: {per_corner}"
        );
        assert!(
            per_corner.contains(r#"<path d=""#),
            "应退化为路径: {per_corner}"
        );
    }

    /// 4×4 测试图:四个 2×2 象限色块(左上红 / 右上绿 / 左下蓝 / 右下白)。
    fn quad_pixmap() -> crate::Pixmap {
        let mut px = Vec::with_capacity(4 * 4 * 4);
        for y in 0..4u32 {
            for x in 0..4u32 {
                let (r, g, b) = match (x < 2, y < 2) {
                    (true, true) => (255u8, 0u8, 0u8),
                    (false, true) => (0, 255, 0),
                    (true, false) => (0, 0, 255),
                    (false, false) => (255, 255, 255),
                };
                px.extend_from_slice(&[r, g, b, 255]);
            }
        }
        crate::Pixmap::from_rgba8(4, 4, px).unwrap()
    }

    /// 图片采样质量 → `image-rendering` 提示(Bilinear 是默认值,不输出)。
    #[test]
    fn image_quality_maps_to_image_rendering() {
        use crate::scene::ImageQuality;
        let scene_with = |q: ImageQuality| {
            let mut s = Scene::new(8.0, 8.0);
            s.push(Element::image(
                crate::SceneImage::from_pixmap(quad_pixmap()).with_quality(q),
                Rect::new(0.0, 0.0, 8.0, 8.0),
            ));
            s
        };
        assert!(
            render(&scene_with(ImageQuality::Nearest)).contains(r#"image-rendering="pixelated""#)
        );
        assert!(!render(&scene_with(ImageQuality::Bilinear)).contains("image-rendering"));
        assert!(
            render(&scene_with(ImageQuality::Bicubic))
                .contains(r#"image-rendering="high-quality""#)
        );
    }

    /// `ObjectFit::Tile` → `<pattern>`(瓦片按原始像素尺寸)+ 覆盖 frame 的 `<rect>`。
    #[test]
    fn tile_object_fit_emits_a_pattern() {
        let mut scene = Scene::new(8.0, 8.0);
        scene.push(Element::image(
            crate::SceneImage::from_pixmap(quad_pixmap()).with_object_fit(crate::ObjectFit::Tile),
            Rect::new(0.0, 0.0, 8.0, 8.0),
        ));
        let out = render(&scene);
        assert!(
            out.contains(r#"<pattern id="img0" patternUnits="userSpaceOnUse""#),
            "{out}"
        );
        assert!(
            out.contains(r#"width="4.00" height="4.00""#),
            "瓦片按原始像素尺寸: {out}"
        );
        assert!(out.contains(r#"fill="url(#img0)""#), "{out}");
    }

    /// `Fill::Image` → `<pattern>` + 形状上的 `fill="url(#img…)"`。
    #[test]
    fn image_fill_emits_a_pattern() {
        let mut scene = Scene::new(8.0, 8.0);
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 8.0, 8.0),
            FillStrokeStyle::fill_gradient(crate::scene::ImageFill::natural(
                quad_pixmap(),
                Point::new(0.0, 0.0),
            )),
        ));
        let out = render(&scene);
        assert!(out.contains(r#"<pattern id="img0""#), "{out}");
        assert!(out.contains(r#"fill="url(#img0)""#), "{out}");
    }

    /// 抗锯齿开关:关闭的形状带 `shape-rendering="crispEdges"`,且能被整棵子树继承。
    #[test]
    fn antialias_off_emits_crisp_edges() {
        let rect = |w: f64| {
            Element::rect(
                Rect::new(0.0, 0.0, w, w),
                FillStrokeStyle::fill(Color::BLACK),
            )
        };

        let mut scene = Scene::new(20.0, 20.0);
        scene.push(SceneNode::new(rect(10.0)).with_antialias(false));
        scene.push(rect(5.0));
        let out = render(&scene);
        assert_eq!(
            out.matches(r#"shape-rendering="crispEdges""#).count(),
            1,
            "只有关闭的那个形状带提示: {out}"
        );

        // 容器关闭 → 子树两个形状都带上(属性沿子树继承)。
        let mut nested = Scene::new(20.0, 20.0);
        nested.push_node(
            SceneNode::group(vec![SceneNode::new(rect(2.0)), SceneNode::new(rect(3.0))])
                .with_antialias(false),
        );
        let out = render(&nested);
        assert_eq!(
            out.matches(r#"shape-rendering="crispEdges""#).count(),
            2,
            "子树继承容器的设置: {out}"
        );
    }

    /// 色彩矩阵烘进 paint(方案 B):灰度后输出的是灰 hex,而不是原色。
    #[test]
    fn color_matrix_is_baked_into_paints() {
        let mut scene = Scene::new(20.0, 20.0);
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 20.0, 20.0),
                FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
            ))
            .with_color_matrix(crate::scene::ColorMatrix::grayscale()),
        );
        let out = render(&scene);
        // 0.213 × 255 ≈ 54 = 0x36。
        assert!(out.contains(r##"fill="#363636""##), "灰化后的填充: {out}");
        assert!(!out.contains(r##"fill="#ff0000""##), "不应保留原色: {out}");
    }

    /// 嵌套色彩矩阵:子节点灰化 + 父容器增亮 0.5 → 54 × 0.5 = 27 = 0x1b。
    #[test]
    fn nested_color_matrices_compose() {
        let child = SceneNode::new(Element::rect(
            Rect::new(0.0, 0.0, 20.0, 20.0),
            FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
        ))
        .with_color_matrix(crate::scene::ColorMatrix::grayscale());
        let group = SceneNode::group(vec![child])
            .with_color_matrix(crate::scene::ColorMatrix::brightness(0.5));
        let mut scene = Scene::new(20.0, 20.0);
        scene.push_node(group);
        let out = render(&scene);
        assert!(out.contains(r##"fill="#1b1b1b""##), "组合后的填充: {out}");
    }

    #[test]
    fn opacity_name_visibility() {
        let mut scene = Scene::new(100.0, 100.0);
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 10.0, 10.0),
                FillStrokeStyle::fill(Color::BLACK),
            ))
            .with_opacity(0.4)
            .with_name("a"),
        );
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(20.0, 0.0, 30.0, 10.0),
                FillStrokeStyle::fill(Color::BLACK),
            ))
            .with_visible(false),
        );
        let out = render(&scene);
        assert!(out.contains(r#"<g id="a">"#));
        assert!(out.contains(r#"<g opacity="0.400">"#));
        // Hidden nodes should not output their rectangle.
        assert!(!out.contains(r#"x="20.00""#));
    }

    #[test]
    fn text_escaping() {
        let mut scene = Scene::new(100.0, 100.0);
        scene.push(Element::text(
            "a <b> & \"c\"",
            Point::new(1.0, 2.0),
            TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
        ));
        let out = render(&scene);
        assert!(out.contains("a &lt;b&gt; &amp; \"c\""));
    }

    #[test]
    fn text_align_anchor() {
        let mut scene = Scene::new(200.0, 100.0);
        let style = |align| TextStyle::new(Color::BLACK, 12.0, "sans-serif").with_align(align);
        scene.push(Element::text(
            "L",
            Point::new(10.0, 10.0),
            style(TextAlign::Left),
        ));
        scene.push(Element::text(
            "C",
            Point::new(100.0, 10.0),
            style(TextAlign::Center),
        ));
        scene.push(Element::text(
            "R",
            Point::new(190.0, 10.0),
            style(TextAlign::Right),
        ));
        let out = render(&scene);
        assert!(out.contains(r#"text-anchor="start""#));
        assert!(out.contains(r#"text-anchor="middle""#));
        assert!(out.contains(r#"text-anchor="end""#));
    }

    #[test]
    fn text_baseline_and_font_attrs() {
        let mut scene = Scene::new(200.0, 100.0);
        scene.push(Element::text(
            "b",
            Point::new(10.0, 10.0),
            TextStyle::new(Color::BLACK, 12.0, "sans-serif")
                .with_baseline(TextBaseline::Middle)
                .with_weight(FontWeight::Bold)
                .with_style(FontStyle::Italic)
                .with_line_height(18.0),
        ));
        let out = render(&scene);
        assert!(out.contains(r#"dominant-baseline="alphabetic""#));
        assert!(out.contains(r#"font-weight="700""#));
        assert!(out.contains(r#"font-style="italic""#));
        assert!(out.contains(r#"style="line-height:18.00""#));
    }

    #[test]
    fn node_and_layer_transform_matrix() {
        use crate::geometry::Transform;
        use crate::scene::Layer;
        let mut scene = Scene::new(100.0, 100.0);
        // Node transform → <g transform="matrix(...)">
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 10.0, 10.0),
                FillStrokeStyle::fill(Color::BLACK),
            ))
            .with_transform(Transform::translate(5.0, 7.0)),
        );
        // Layer transform
        scene.push_layer(Layer::new("l").with_transform(Transform::translate(1.0, 2.0)));
        let out = render(&scene);
        assert!(out.contains(r#"matrix(1.000000 0.000000 0.000000 1.000000 5.000000 7.000000)"#));
        assert!(out.contains(r#"matrix(1.000000 0.000000 0.000000 1.000000 1.000000 2.000000)"#));
    }

    #[test]
    fn layer_render_order_bottom_to_top() {
        use crate::scene::Layer;
        let mut scene = Scene::new(100.0, 100.0);
        // Default layer nodes (bottom-most)
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 10.0, 10.0),
            FillStrokeStyle::fill(Color::BLACK),
        ));
        scene.push_layer(
            Layer::new("bottom").with_nodes(vec![SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 5.0, 5.0),
                FillStrokeStyle::fill(Color::BLACK),
            ))]),
        );
        scene.push_layer(
            Layer::new("top").with_nodes(vec![SceneNode::new(Element::circle(
                Point::new(0.0, 0.0),
                1.0,
                FillStrokeStyle::fill(Color::BLACK),
            ))]),
        );
        let out = render(&scene);
        let bg_idx = out.find("width=\"10.00\"").expect("默认层矩形");
        let bottom_idx = out.find(r#"<g id="bottom">"#).expect("bottom 图层");
        let top_idx = out.find(r#"<g id="top">"#).expect("top 图层");
        assert!(
            bg_idx < bottom_idx && bottom_idx < top_idx,
            "渲染顺序应为 默认层 < bottom < top"
        );
    }

    #[test]
    fn path_closed_vs_open() {
        use kurbo::BezPath;
        let mut scene = Scene::new(100.0, 100.0);
        // open path
        let mut open = BezPath::new();
        open.move_to((0.0, 0.0));
        open.line_to((10.0, 0.0));
        scene.push(Element::Path {
            path: open,
            style: FillStrokeStyle::stroke(Color::BLACK, 1.0),
            closed: false,
        });
        // closed path
        let mut closed = BezPath::new();
        closed.move_to((20.0, 0.0));
        closed.line_to((30.0, 0.0));
        closed.line_to((25.0, 10.0));
        scene.push(Element::Path {
            path: closed,
            style: FillStrokeStyle::stroke(Color::BLACK, 1.0),
            closed: true,
        });
        let out = render(&scene);
        // kurbo to_svg output format: M0,0 L10,0 (no spaces, no trailing-zero decimals).
        // Open-path d has no Z close; closed-path d ends with Z.
        assert!(
            out.contains(r#"d="M0,0 L10,0""#),
            "开放路径 d 应为 M0,0 L10,0: {}",
            out
        );
        assert!(
            out.contains(r#"d="M20,0 L30,0 L25,10 Z""#),
            "闭合路径 d 应以 Z 结尾: {}",
            out
        );
    }

    #[test]
    fn prelaid_text_ignores_layout_in_svg() {
        use crate::text::RichSpan;
        use crate::text::measure_text;
        let mut scene = Scene::new(100.0, 100.0);
        let style = TextStyle::new(Color::BLACK, 12.0, "sans-serif");
        let m = measure_text(
            std::slice::from_ref(&RichSpan::new("hello", style.clone())),
            None,
        );
        scene.push(Element::Text {
            spans: vec![RichSpan::new("hello", style.clone())],
            position: Point::new(1.0, 2.0),
            style,
            layout: Some(m.layout),
        });
        let out = render(&scene);
        // SVG outputs <text> from concatenated spans, independent of the pre-laid-out layout.
        assert!(out.contains(">hello</text>"));
        assert!(!out.contains("path"));
    }

    #[test]
    fn font_family_attr_is_css_normalized_and_xml_escaped() {
        use crate::text::TextStyle;
        let mut scene = Scene::new(100.0, 100.0);
        // Space-containing family name + generic family + special characters, verifying the
        // two-layer escaping:
        // CSS layer (font_family_css): quoted; XML layer (escape_attr): & → &amp;
        let style = TextStyle::new(
            Color::BLACK,
            12.0,
            "Helvetica Neue, Rock & Roll, sans-serif",
        );
        scene.push(Element::text("x", Point::new(1.0, 2.0), style));
        let out = render(&scene);
        // Expected attribute value: 'Helvetica Neue', 'Rock &amp; Roll', sans-serif
        // (space → single quotes; & XML-escaped; sans-serif generic family unquoted)
        assert!(out.contains(r#"font-family="'Helvetica Neue', 'Rock &amp; Roll', sans-serif""#));
        // Single-quoted family names should not be XML-escaped (single quotes are safe inside
        // double-quoted attributes)
        assert!(!out.contains("&apos;"));
    }

    #[test]
    fn text_decoration_spacing_stretch_emitted() {
        use crate::text::TextStyle;
        let mut scene = Scene::new(100.0, 100.0);
        let style = TextStyle::new(Color::BLACK, 12.0, "sans-serif")
            .with_underline(true)
            .with_strikethrough(true)
            .with_letter_spacing(2.0)
            .with_font_width(FontWidth::Condensed);
        scene.push(Element::text("x", Point::new(1.0, 2.0), style));
        let out = render(&scene);
        // Decoration / spacing / font width are output as SVG attributes.
        assert!(out.contains(r#"text-decoration="underline line-through""#));
        assert!(out.contains(r#"letter-spacing="2.00""#));
        assert!(out.contains(r#"font-stretch="75%""#));
    }

    #[test]
    fn clip_emits_clip_path_and_wraps_subtree() {
        use crate::scene::Clip;
        let mut scene = Scene::new(100.0, 100.0);
        // A rounded rectangle clipping a red rectangle
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 50.0, 50.0),
                FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
            ))
            .with_clip(Clip::circle(Point::new(25.0, 25.0), 10.0)),
        );
        let out = render(&scene);
        // Should contain <clipPath id="clip0"> with a <circle> inside
        assert!(out.contains(
            r#"<clipPath id="clip0"><circle cx="25.00" cy="25.00" r="10.00"/></clipPath>"#
        ));
        // Should be wrapped in <g clip-path="url(#clip0)">
        assert!(out.contains(r#"<g clip-path="url(#clip0)">"#));
    }

    #[test]
    fn base64_encode_standard_vectors() {
        // RFC 4648 test vectors.
        assert_eq!(base64_encode(b""), "");
        assert_eq!(base64_encode(b"f"), "Zg==");
        assert_eq!(base64_encode(b"fo"), "Zm8=");
        assert_eq!(base64_encode(b"foo"), "Zm9v");
        assert_eq!(base64_encode(b"foob"), "Zm9vYg==");
        assert_eq!(base64_encode(b"fooba"), "Zm9vYmE=");
        assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
    }

    /// Build a solid single-color RGBA8 pixmap image.
    fn test_image(w: u32, h: u32, fill: u8) -> crate::SceneImage {
        let pixels = vec![fill; (w * h * 4) as usize];
        crate::SceneImage::from_rgba8(w, h, pixels).unwrap()
    }

    #[test]
    fn image_emits_data_uri_and_contain_meet() {
        let mut scene = Scene::new(100.0, 100.0);
        scene.push(Element::image(
            test_image(4, 4, 255),
            Rect::new(0.0, 0.0, 10.0, 20.0),
        ));
        let out = render(&scene);
        // bitmap → PNG → data:image/png;base64,<real PNG>
        assert!(out.contains(r#"href="data:image/png;base64,"#));
        assert!(out.contains(r#"width="10.00" height="20.00""#));
        assert!(out.contains(r#"preserveAspectRatio="xMidYMid meet""#));
    }

    #[test]
    fn image_object_fit_none_uses_raw_pixel_size() {
        let mut scene = Scene::new(100.0, 100.0);
        scene.push(Element::image(
            test_image(30, 40, 255).with_object_fit(crate::ObjectFit::None),
            Rect::new(5.0, 6.0, 105.0, 106.0),
        ));
        let out = render(&scene);
        // None: preserveAspectRatio="none" and width/height use the original pixel size (30x40).
        assert!(out.contains(r#"x="5.00" y="6.00" width="30.00" height="40.00""#));
        assert!(out.contains(r#"preserveAspectRatio="none""#));
    }

    #[test]
    fn image_object_fit_fill_maps_to_none() {
        let mut scene = Scene::new(100.0, 100.0);
        scene.push(Element::image(
            test_image(10, 10, 255).with_object_fit(crate::ObjectFit::Fill),
            Rect::new(0.0, 0.0, 10.0, 10.0),
        ));
        let out = render(&scene);
        // Fill: use frame size + preserveAspectRatio="none".
        assert!(out.contains(r#"width="10.00" height="10.00""#));
        assert!(out.contains(r#"preserveAspectRatio="none""#));
    }

    #[test]
    fn image_respects_opacity() {
        let mut scene = Scene::new(100.0, 100.0);
        scene.push_node(
            SceneNode::from(Element::image(
                test_image(10, 10, 255),
                Rect::new(0.0, 0.0, 10.0, 10.0),
            ))
            .with_opacity(0.5),
        );
        let out = render(&scene);
        assert!(out.contains(r#"opacity="0.500""#));
    }

    #[test]
    fn text_baseline_shift_and_background_emitted() {
        use crate::text::TextStyle;
        let mut scene = Scene::new(200.0, 100.0);
        // Superscript: positive baseline_shift → negative baseline-shift (move up).
        let sup = TextStyle::new(Color::BLACK, 12.0, "sans-serif").with_baseline_shift(6.0);
        scene.push(Element::text("x²", Point::new(10.0, 50.0), sup));
        // Inline background: outputs a background <rect>.
        let code = TextStyle::new(Color::BLACK, 12.0, "sans-serif")
            .with_background_color(Some(Color::rgb(0xf0, 0xf0, 0xf0)));
        scene.push(Element::text("code", Point::new(30.0, 50.0), code));
        let out = render(&scene);
        assert!(out.contains("baseline-shift=\"-6.00px\""));
        assert!(out.contains("<rect "));
        assert!(out.contains("fill=\"#f0f0f0\""));
    }

    #[test]
    fn text_background_uses_layout_exact_size() {
        use crate::text::{RichSpan, TextStyle, measure_text};
        let style = TextStyle::new(Color::BLACK, 12.0, "sans-serif")
            .with_background_color(Some(Color::rgb(0xf0, 0xf0, 0xf0)));
        let m = measure_text(
            std::slice::from_ref(&RichSpan::new("code", style.clone())),
            None,
        );
        // Providing a pre-laid-out layout → the background <rect> should use the exact layout width.
        let mut scene = Scene::new(200.0, 100.0);
        scene.push(Element::Text {
            spans: vec![RichSpan::new("code", style.clone())],
            position: Point::new(30.0, 50.0),
            style,
            layout: Some(m.layout),
        });
        let out = render(&scene);
        let expect_w = format!("{:.2}", m.metrics.width);
        let expect_h = format!("{:.2}", m.metrics.height);
        assert!(
            out.contains(&format!("width=\"{}\" height=\"{}\"", expect_w, expect_h)),
            "背景矩形应使用 layout 精确尺寸,但输出含: {}",
            out
        );
    }

    #[test]
    fn text_no_background_when_none() {
        use crate::text::TextStyle;
        let mut scene = Scene::new(100.0, 100.0);
        scene.push(Element::text(
            "plain",
            Point::new(10.0, 50.0),
            TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
        ));
        let out = render(&scene);
        // Without background_color, only the canvas background <rect> exists (no text background rect).
        assert_eq!(out.matches("<rect ").count(), 1);
    }

    /// 缺陷回归:文本背景矩形必须用**真实测量**的尺寸,而非 `font_size` 估算。
    ///
    /// 此前 `Element::text()` 不排版(`layout: None`),SVG 端回落到估算
    /// (宽约 `len * font_size * 0.6`、高约 `font_size * 1.3`),实测对 "Hello World"@20px
    /// 给出 132×26,而真实排版是 109.74×27.24 —— **宽度误差约 20%**,背景框明显偏大,
    /// 且与 [`crate::fit::scene_bounds`](用真实测量)不一致。
    ///
    /// 现在 `Element::text()` 构造时即排版,两个后端共享同一份布局。
    #[test]
    fn text_background_uses_real_measurement() {
        use crate::text::TextStyle;

        let style = TextStyle::new(Color::BLACK, 20.0, "sans-serif")
            .with_background_color(Some(Color::rgb(0xff, 0xff, 0x00)));
        let el = Element::text("Hello World", Point::new(10.0, 40.0), style);
        // 无可用字体时排版为空,跳过(沙箱 / 精简镜像中可能没有字体)。
        let measured_w = match &el {
            Element::Text {
                layout: Some(l), ..
            } => l.width,
            _ => return,
        };

        let mut scene = Scene::new(300.0, 80.0);
        scene.push(el);
        let out = render(&scene);

        // 文本背景矩形(黄色)的宽度应等于排版宽度。
        let bg = out
            .lines()
            .find(|l| l.contains("#ffff00"))
            .expect("应输出文本背景矩形");
        let w: f64 = bg
            .split("width=\"")
            .nth(1)
            .and_then(|s| s.split('"').next())
            .and_then(|s| s.parse().ok())
            .expect("背景矩形应有 width");
        assert!(
            (w - measured_w).abs() < 0.5,
            "背景矩形宽度应等于排版宽度 {measured_w:.2},实际 {w:.2}"
        );
    }

    /// `Element::text()` 构造时即排版,两个后端与 [`crate::fit`] 共享同一份布局。
    #[test]
    fn element_text_prelayouts() {
        use crate::text::TextStyle;

        // 有内容 → 排版。
        let el = Element::text(
            "Hello",
            Point::new(0.0, 0.0),
            TextStyle::new(Color::BLACK, 16.0, "sans-serif"),
        );
        match &el {
            Element::Text { layout, .. } => {
                // 无字体环境下排版为空,此时不应 panic 而应降级为 None。
                if let Some(l) = layout {
                    assert!(!l.lines.is_empty());
                    assert!(l.width > 0.0);
                }
            }
            _ => panic!("expected Text"),
        }

        // 空文本 → 不排版(避免无谓分配)。
        let empty = Element::text(
            "",
            Point::new(0.0, 0.0),
            TextStyle::new(Color::BLACK, 16.0, "sans-serif"),
        );
        match &empty {
            Element::Text { layout, .. } => assert!(layout.is_none(), "空文本不应排版"),
            _ => panic!("expected Text"),
        }

        // rich_text 同理。
        let rich = Element::rich_text(
            vec![crate::text::RichSpan::new(
                "ab",
                TextStyle::new(Color::BLACK, 16.0, "sans-serif"),
            )],
            Point::new(0.0, 0.0),
            TextStyle::new(Color::BLACK, 16.0, "sans-serif"),
        );
        match &rich {
            Element::Text { layout, .. } => {
                if let Some(l) = layout {
                    assert!(!l.lines.is_empty());
                }
            }
            _ => panic!("expected Text"),
        }
        let empty_rich = Element::rich_text(
            vec![],
            Point::new(0.0, 0.0),
            TextStyle::new(Color::BLACK, 16.0, "sans-serif"),
        );
        match &empty_rich {
            Element::Text { layout, .. } => assert!(layout.is_none()),
            _ => panic!("expected Text"),
        }
    }

    /// Bug 回归:渲染器未显式设置尺寸 / 背景时,回落到 [`Scene`] 的元数据
    /// (此前 `SvgRenderer::new(0.0, 0.0)` 会输出 `width="0.00" height="0.00"`,
    /// 且 `Scene::background` 被完全忽略)。
    #[test]
    fn falls_back_to_scene_size_and_background() {
        let mut scene = Scene::new(300.0, 200.0).with_background(Color::rgb(0x00, 0x00, 0xff));
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 10.0, 10.0),
            FillStrokeStyle::fill(Color::RED),
        ));
        let mut svg = SvgRenderer::new(0.0, 0.0);
        scene.render(&mut svg);
        let out = svg.into_string();
        assert!(
            out.contains(r#"width="300.00" height="200.00" viewBox="0 0 300.00 200.00""#),
            "应回落到场景尺寸,实际输出: {out}"
        );
        assert!(
            out.contains(r##"fill="#0000ff""##),
            "应回落到场景背景色,实际输出: {out}"
        );
    }

    /// 渲染器显式设置的值优先于场景元数据(尺寸原样作为输出尺寸,scale 只影响 viewBox)。
    #[test]
    fn explicit_renderer_settings_win() {
        let scene = Scene::new(300.0, 200.0).with_scale(3.0);
        let mut svg = SvgRenderer::new(50.0, 40.0)
            .with_scale(2.0)
            .with_background(Color::GREEN);
        scene.render(&mut svg);
        let out = svg.into_string();
        assert!(out.contains(r#"width="50.00" height="40.00" viewBox="0 0 25.00 20.00""#));
        assert!(out.contains(r##"fill="#00ff00""##));
        // 显式 scale=2 应压过 scene 的 scale=3。
        assert!(
            !out.contains(r#"viewBox="0 0 16.67"#),
            "渲染器 scale 应优先: {out}"
        );
    }

    /// Bug 回归:整圆(|sweep| = 360°)在 SVG 中必须拆成两段 180° 弧。
    ///
    /// SVG 规范规定起终点重合的 `A` 段被整体忽略,单段写法会让 100% 扇形(整圆饼图)
    /// 在 SVG 端什么都不画,而栅格端画出整圆。
    #[test]
    fn full_circle_arc_is_split_in_two() {
        let d = arc_path_d(
            Point::new(50.0, 50.0),
            Vec2::new(30.0, 30.0),
            0.0,
            std::f64::consts::TAU,
            true,
        );
        assert_eq!(
            d.matches(" A ").count(),
            2,
            "整圆应拆成两段弧,实际 d = {d}"
        );
        assert!(d.starts_with("M 50.00 50.00 L "), "扇形应含中心点: {d}");
        assert!(d.ends_with(" Z"), "扇形应闭合: {d}");
        // 两段的起终点不能重合(否则又被忽略)。
        let open_pie = arc_path_d(
            Point::new(50.0, 50.0),
            Vec2::new(30.0, 30.0),
            0.0,
            std::f64::consts::TAU,
            false,
        );
        assert_eq!(open_pie.matches(" A ").count(), 2, "整圆弧: {open_pie}");
        // 非整圆仍是单段。
        let normal = arc_path_d(
            Point::new(50.0, 50.0),
            Vec2::new(30.0, 30.0),
            0.0,
            std::f64::consts::FRAC_PI_2,
            true,
        );
        assert_eq!(normal.matches(" A ").count(), 1, "普通扇形: {normal}");
    }

    /// 半透明渐变 stop:用 `stop-opacity` 表达 alpha(8 位 hex 在 SVG 1.1 / 部分
    /// SVG→PDF 工具链中不被识别)。
    #[test]
    fn gradient_stop_alpha_uses_stop_opacity() {
        let mut scene = Scene::new(100.0, 100.0);
        let grad = LinearGradient::new(
            Point::new(0.0, 0.0),
            Point::new(100.0, 0.0),
            vec![
                GradientStop {
                    offset: 0.0,
                    color: Color::rgba(0xff, 0x00, 0x00, 128),
                },
                GradientStop {
                    offset: 1.0,
                    color: Color::rgb(0x00, 0x00, 0xff),
                },
            ],
        );
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 100.0, 100.0),
            FillStrokeStyle {
                fill: Some(grad.into()),
                stroke: None,
            },
        ));
        let out = render(&scene);
        assert!(
            out.contains(r##"stop-color="#ff0000" stop-opacity="0.502""##),
            "半透明 stop 应输出 stop-opacity: {out}"
        );
        assert!(
            out.contains(r##"stop-color="#0000ff" />"##),
            "不透明 stop 不应带 stop-opacity: {out}"
        );
    }

    /// 缺陷回归:富文本的每个 span 必须输出自己的样式(此前把 spans 拼成纯文本,
    /// 颜色/字号/字重全部退化为块级单一样式,SVG 与 vello 不一致)。
    #[test]
    fn rich_text_spans_emit_tspan_with_own_style() {
        use crate::text::RichSpan;
        let mut scene = Scene::new(300.0, 60.0);
        scene.push(Element::rich_text(
            vec![
                RichSpan::new(
                    "red ",
                    TextStyle::new(Color::rgb(0xff, 0x00, 0x00), 20.0, "sans-serif")
                        .with_weight(FontWeight::Bold),
                ),
                RichSpan::new(
                    "blue",
                    TextStyle::new(Color::rgb(0x00, 0x00, 0xff), 12.0, "sans-serif"),
                ),
            ],
            Point::new(10.0, 30.0),
            TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
        ));
        let out = render(&scene);
        assert!(out.contains("<tspan"), "富文本应输出 tspan: {out}");
        assert!(
            out.contains(r##"fill="#ff0000""##)
                && out.contains(r##"font-size="20.00""##)
                && out.contains(r##"font-weight="700""##),
            "红色加粗 span 的样式应保留: {out}"
        );
        assert!(
            out.contains(r##"fill="#0000ff""##),
            "蓝色 span 的样式应保留: {out}"
        );
        assert!(out.contains(">red </tspan>"), "span 文本应完整: {out}");
        assert!(out.contains(">blue</tspan>"), "span 文本应完整: {out}");

        // 单 span、无换行的热路径保持纯文本输出(无 tspan)。
        let mut plain = Scene::new(100.0, 30.0);
        plain.push(Element::text(
            "plain",
            Point::new(1.0, 2.0),
            TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
        ));
        let out_plain = render(&plain);
        assert!(
            !out_plain.contains("<tspan"),
            "纯文本不应输出 tspan: {out_plain}"
        );
    }

    /// 缺陷回归:文本内含 `\n` 时必须逐行输出 tspan(SVG `<text>` 本身不换行,
    /// 此前整串输出会退化为一行,与 vello 的多行布局不一致)。
    #[test]
    fn multiline_text_emits_line_tspans() {
        let mut scene = Scene::new(100.0, 100.0);
        scene.push(Element::text(
            "line1\nline2",
            Point::new(5.0, 10.0),
            TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
        ));
        let out = render(&scene);
        assert!(out.contains(">line1</tspan>"), "第一行内容缺失: {out}");
        assert!(out.contains(">line2</tspan>"), "第二行内容缺失: {out}");
        // 每行一个行级 tspan,且首行 dy=0、后续行按行距下移。
        let line_tspans: Vec<&str> = out.matches(r#"<tspan x="5.00" dy="#).collect();
        assert!(line_tspans.len() >= 2, "应有两个行级 tspan: {out}");
    }

    /// 缺陷回归:半透明 fill/stroke 必须拆成 `#rrggbb` + `*-opacity`,不能输出
    /// SVG 1.1 / SVG→PDF 不支持的 8 位 hex。
    #[test]
    fn translucent_color_uses_fill_and_stroke_opacity() {
        let mut scene = Scene::new(40.0, 40.0);
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 40.0, 40.0),
            FillStrokeStyle {
                fill: Some(Color::rgba(0xff, 0x00, 0x00, 128).into()),
                stroke: Some(Stroke::new(Color::rgba(0x00, 0x00, 0xff, 128), 2.0)),
            },
        ));
        let out = render(&scene);
        assert!(
            out.contains(r##"fill="#ff0000" fill-opacity="0.502""##),
            "半透明 fill 应带 fill-opacity: {out}"
        );
        assert!(
            out.contains(r##"stroke="#0000ff" stroke-opacity="0.502""##),
            "半透明 stroke 应带 stroke-opacity: {out}"
        );
        assert!(
            !out.contains("#ff000080") && !out.contains("#0000ff80"),
            "不应输出 8 位 hex: {out}"
        );
    }

    // ——— 手绘填充(Fill::Sketch → <pattern>)———

    fn sketch_rect(color: crate::geometry::Color, style: SketchFillStyle) -> Scene {
        let mut scene = Scene::new(200.0, 200.0);
        scene.push(Element::rect(
            Rect::new(10.0, 10.0, 100.0, 80.0),
            FillStrokeStyle {
                fill: Some(Fill::Sketch(SketchFill::new(color).with_style(style))),
                stroke: None,
            },
        ));
        scene
    }

    #[test]
    fn sketch_fill_emits_one_pattern_definition() {
        let out = render(&sketch_rect(
            Color::rgb(0x33, 0x66, 0x99),
            SketchFillStyle::Hachure,
        ));
        assert!(out.contains(r#"<pattern id="sk0""#), "{out}");
        assert!(out.contains(r#"patternUnits="userSpaceOnUse""#), "{out}");
        // 角度交给 patternTransform,tile 内只画竖线 → 任意角度都无缝。
        assert!(
            out.contains(r#"patternTransform="rotate(-41.00)""#),
            "{out}"
        );
        assert!(out.contains(r#"fill="url(#sk0)""#), "{out}");
        assert_eq!(out.matches("<pattern").count(), 1, "只应定义一次: {out}");
    }

    /// pattern 池:100 个同色同参数的矩形只产生一个 <pattern>;
    /// 这正是"元素数爆炸"防护在 SVG 侧的表现(体积与元素数无关)。
    #[test]
    fn identical_sketch_fills_share_one_pattern() {
        let mut scene = Scene::new(400.0, 400.0);
        for i in 0..100 {
            let x = (i % 10) as f64 * 20.0;
            let y = (i / 10) as f64 * 20.0;
            scene.push(Element::rect(
                Rect::new(x, y, x + 16.0, y + 16.0),
                FillStrokeStyle {
                    fill: Some(Fill::Sketch(SketchFill::new(Color::rgb(0xcc, 0x33, 0x33)))),
                    stroke: None,
                },
            ));
        }
        let out = render(&scene);
        assert_eq!(out.matches("<pattern").count(), 1, "pattern 数应 ≤1: {out}");
        assert_eq!(out.matches(r#"fill="url(#sk0)""#).count(), 100);
    }

    /// 4 种样式 × 2 种颜色 → 最多 4 个 pattern(每种组合一个)。
    #[test]
    fn pattern_pool_is_keyed_by_all_parameters() {
        let mut scene = Scene::new(300.0, 100.0);
        for (i, style) in [
            SketchFillStyle::Hachure,
            SketchFillStyle::CrossHatch,
            SketchFillStyle::Zigzag,
            SketchFillStyle::Dots,
        ]
        .into_iter()
        .enumerate()
        {
            scene.push(Element::rect(
                Rect::new(i as f64 * 70.0, 10.0, i as f64 * 70.0 + 60.0, 80.0),
                FillStrokeStyle {
                    fill: Some(Fill::Sketch(
                        SketchFill::new(Color::rgb(0x11, 0x22, 0x33)).with_style(style),
                    )),
                    stroke: None,
                },
            ));
        }
        let out = render(&scene);
        assert_eq!(out.matches("<pattern").count(), 4, "四种样式各一个: {out}");
        assert!(out.contains("<circle"), "Dots 用圆点: {out}");
        assert!(out.contains("<polyline"), "Zigzag 用折线: {out}");
    }

    /// 不同颜色必须各自成 pattern(去重不能吃掉颜色)。
    #[test]
    fn different_colors_get_different_patterns() {
        let mut scene = Scene::new(300.0, 100.0);
        for (i, c) in [
            Color::rgb(0xff, 0x00, 0x00),
            Color::rgb(0x00, 0xff, 0x00),
            Color::rgb(0x00, 0x00, 0xff),
        ]
        .into_iter()
        .enumerate()
        {
            scene.push(Element::rect(
                Rect::new(i as f64 * 90.0, 10.0, i as f64 * 90.0 + 80.0, 80.0),
                FillStrokeStyle {
                    fill: Some(Fill::Sketch(SketchFill::new(c))),
                    stroke: None,
                },
            ));
        }
        let out = render(&scene);
        assert_eq!(out.matches("<pattern").count(), 3, "{out}");
    }

    /// 半透明排线颜色必须拆成 stroke-opacity(与 fill/stroke 的惯例一致,
    /// 不能被 SVG→PDF 工具链拒绝)。
    #[test]
    fn translucent_sketch_color_uses_stroke_opacity() {
        let out = render(&sketch_rect(
            Color::rgba(0x33, 0x66, 0x99, 128),
            SketchFillStyle::Hachure,
        ));
        assert!(out.contains(r#"stroke-opacity="0.502""#), "{out}");
        assert!(!out.contains("#33669980"), "不应输出 8 位 hex: {out}");
    }

    /// tile 内容必须内缩半个线宽:贴边画的线会被 pattern 边界裁掉一半,
    /// 相邻 tile 又补不回来 → 排线会变成半宽虚线。
    #[test]
    fn pattern_tile_content_is_inset_from_the_edges() {
        let out = render(&sketch_rect(Color::BLACK, SketchFillStyle::Hachure));
        let gap = 4.0;
        assert!(
            out.contains(&format!(r#"x1="{:.2}""#, gap * 0.5)),
            "竖线应在 tile 中间: {out}"
        );
        assert!(!out.contains(r#"x1="0.00""#), "线不应贴在 tile 边缘: {out}");
    }

    /// 未开启手绘时,SVG 输出里不应出现任何 pattern(默认零影响)。
    #[test]
    fn no_pattern_without_a_sketch_fill() {
        let mut scene = Scene::new(100.0, 100.0);
        scene.push(Element::rect(
            Rect::new(10.0, 10.0, 90.0, 90.0),
            FillStrokeStyle::fill(Color::rgb(0x33, 0x66, 0x99)),
        ));
        let out = render(&scene);
        assert!(!out.contains("<pattern"), "{out}");
        assert!(!out.contains("<defs>"), "{out}");
    }

    fn render_with(scene: &Scene, f: impl FnOnce(SvgRenderer) -> SvgRenderer) -> String {
        let mut svg = f(SvgRenderer::new(scene.width, scene.height).with_background(Color::WHITE));
        scene.render(&mut svg);
        svg.into_string()
    }

    fn sized_scene() -> Scene {
        let mut scene = Scene::new(120.0, 60.0);
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 10.0, 10.0),
            FillStrokeStyle::fill(Color::RED),
        ));
        scene
    }

    /// 默认(也是历史行为):视口写死为输出尺寸。
    #[test]
    fn fixed_sizing_writes_width_and_height() {
        let out = render_with(&sized_scene(), |r| r);
        assert!(
            out.starts_with(
                r#"<svg xmlns="http://www.w3.org/2000/svg" width="120.00" height="60.00" viewBox="0 0 120.00 60.00">"#
            ),
            "{out}"
        );
    }

    /// 响应式:只写 viewBox,视口交给宿主 CSS(SVG 2 的 auto ≈ 100%)。
    #[test]
    fn intrinsic_sizing_omits_width_and_height() {
        let out = render_with(&sized_scene(), |r| r.with_sizing(SvgSizing::Intrinsic));
        assert!(
            out.starts_with(
                r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120.00 60.00">"#
            ),
            "{out}"
        );
        assert!(!out.contains(r#"<svg width="#), "根节点不应带 width: {out}");
    }

    /// `style` 追加到根节点并做属性转义(下游用它写 max-width / background-color)。
    #[test]
    fn root_style_is_emitted_and_escaped() {
        let out = render_with(&sized_scene(), |r| {
            r.with_sizing(SvgSizing::Intrinsic)
                .with_style(r#"max-width: 120.000px; background-color: #ffffff;"#)
        });
        assert!(
            out.starts_with(
                r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120.00 60.00" style="max-width: 120.000px; background-color: #ffffff;">"#
            ),
            "{out}"
        );

        // 引号必须转义,否则 style 属性会提前闭合。
        let out = render_with(&sized_scene(), |r| r.with_style(r#"content: "x""#));
        assert!(out.contains(r#"style="content: &quot;x&quot;""#), "{out}");
    }

    /// scale 只缩放 viewBox:Intrinsic 下 viewBox 仍是 输出尺寸/scale。
    #[test]
    fn intrinsic_sizing_keeps_scale_in_viewbox() {
        let out = render_with(&sized_scene(), |r| {
            r.with_scale(2.0).with_sizing(SvgSizing::Intrinsic)
        });
        assert!(
            out.starts_with(
                r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60.00 30.00">"#
            ),
            "{out}"
        );
    }
}