devpage-design 0.2.2

The design engine: parses, resolves, lays out and paints devpage designs
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
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
//! Syntax tree → scene: imports and props substituted, every attribute
//! checked, typed and defaulted.

use std::collections::{BTreeMap, HashMap};
use std::rc::Rc;
use std::sync::Arc;

use vello_cpu::peniko::{Blob, ImageAlphaType, ImageData, ImageFormat};

use crate::Problem;
use crate::fonts::{self, Family, FontFile, FontFiles, FontId};
use crate::parse::{self, Child, Element, Pos, TextPart, Value};

/// One color's value: straight-alpha RGBA.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rgba {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

/// Which of a design's two themes it is drawn in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Theme {
    #[default]
    Light,
    Dark,
}

impl Theme {
    /// `"light"` or `"dark"` as a theme, as a PNG's `?theme=` names one.
    pub fn named(name: &str) -> Option<Theme> {
        match name {
            "light" => Some(Theme::Light),
            "dark" => Some(Theme::Dark),
            _ => None,
        }
    }
}

/// A color in a scene: its value in each theme. A color written as `#…` has
/// the same value in both; `theme.name` has the themes' two.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Color {
    pub light: Rgba,
    pub dark: Rgba,
}

impl Color {
    /// The same value in both themes.
    pub const fn fixed(c: Rgba) -> Color {
        Color { light: c, dark: c }
    }

    /// The value in `theme`.
    pub fn get(self, theme: Theme) -> Rgba {
        match theme {
            Theme::Light => self.light,
            Theme::Dark => self.dark,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Size {
    Px(f32),
    Hug,
    Fill,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Layout {
    None,
    Row,
    Column,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Align {
    Start,
    Center,
    End,
    SpaceBetween,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Kind {
    Frame,
    Text,
    Rect,
    Ellipse,
    Vector,
    Image,
}

/// How a box is filled: one color, or a CSS-style linear gradient.
#[derive(Debug, Clone, PartialEq)]
pub enum Fill {
    Solid(Color),
    /// `angle` in degrees, CSS's: 0 points up, 90 right, 180 down. Each stop
    /// is a color at an offset from 0 to 1 along the gradient line.
    Linear {
        angle: f32,
        stops: Vec<(Color, f32)>,
    },
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TextAlign {
    Left,
    Center,
    Right,
}

/// A `Vector`'s path and the box of path coordinates it is drawn from.
#[derive(Debug, Clone, PartialEq)]
pub struct Vector {
    pub d: String,
    /// `[minX, minY, width, height]`.
    pub view_box: [f32; 4],
}

/// An image file's identity: the SHA-256 of its bytes. Two `Image`s showing
/// the same bytes — the same file used twice, or two copies of it — share one
/// [`ImageFile`], decoded once and sent once.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ImageId(pub [u8; 32]);

impl ImageId {
    pub fn of(bytes: &[u8]) -> ImageId {
        use sha2::Digest;
        ImageId(sha2::Sha256::digest(bytes).into())
    }
}

impl std::fmt::Debug for ImageId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for b in &self.0[..6] {
            write!(f, "{b:02x}")?;
        }
        Ok(())
    }
}

/// The most pixels a side an image is drawn from. The GPU keeps every image a
/// drawing paints in one atlas of [`crate::atlas::SIDE`] pixels a side, so a
/// larger file is resampled to fit this, keeping its aspect, when it is
/// decoded — and both backends draw those same pixels.
pub const MAX_IMAGE_SIDE: u32 = 4096;

/// A decoded image file: its bytes, its own size, and the pixels it is drawn
/// from — the file's own, or resampled to at most [`MAX_IMAGE_SIDE`] a side.
#[derive(Debug)]
pub struct ImageFile {
    pub id: ImageId,
    pub bytes: Vec<u8>,
    /// The file's size in pixels: what an `Image` hugs by.
    pub width: u32,
    pub height: u32,
    /// Straight-alpha RGBA, `pixels_width` × `pixels_height`.
    pub pixels: Arc<Vec<u8>>,
    pub pixels_width: u32,
    pub pixels_height: u32,
}

impl ImageFile {
    /// Decodes `bytes`, a PNG or JPEG file, or says why it can't.
    pub fn new(bytes: Vec<u8>) -> Result<ImageFile, String> {
        ImageFile::with_id(ImageId::of(&bytes), bytes)
    }

    /// Decodes `bytes`, already known to be the file `id`.
    pub fn with_id(id: ImageId, bytes: Vec<u8>) -> Result<ImageFile, String> {
        let decoded = decode(&bytes)?;
        let (width, height) = (decoded.width, decoded.height);
        let (pixels, pixels_width, pixels_height) =
            fit(decoded.data.data(), width, height, MAX_IMAGE_SIDE);
        Ok(ImageFile {
            id,
            bytes,
            width,
            height,
            pixels: Arc::new(pixels),
            pixels_width,
            pixels_height,
        })
    }

    /// The pixels as an image for one drawing to paint, under a blob of its
    /// own that shares the pixels: see `render::Renderer::drawing`.
    pub fn image_data(&self) -> ImageData {
        ImageData {
            data: Blob::new(self.pixels.clone()),
            format: ImageFormat::Rgba8,
            alpha_type: ImageAlphaType::Alpha,
            width: self.pixels_width,
            height: self.pixels_height,
        }
    }
}

/// `rgba`, `width` × `height`, resampled to at most `max` pixels a side with
/// its aspect kept, or as it is when it already fits. Each new pixel is the
/// area-weighted average of the pixels under it, in premultiplied alpha so a
/// transparent pixel lends no color.
pub fn fit(rgba: &[u8], width: u32, height: u32, max: u32) -> (Vec<u8>, u32, u32) {
    if width <= max && height <= max {
        return (rgba.to_vec(), width, height);
    }
    let scale = max as f64 / width.max(height) as f64;
    let w = ((width as f64 * scale).round() as u32).clamp(1, max);
    let h = ((height as f64 * scale).round() as u32).clamp(1, max);
    // For each output index along one axis, the input indices it covers and
    // how much of each.
    let weights = |from: u32, to: u32| -> Vec<Vec<(usize, f32)>> {
        let ratio = from as f64 / to as f64;
        (0..to)
            .map(|o| {
                let (a, b) = (o as f64 * ratio, (o + 1) as f64 * ratio);
                (a.floor() as usize..(b.ceil() as usize).min(from as usize))
                    .map(|i| {
                        let cover = (b.min(i as f64 + 1.0) - a.max(i as f64)) / ratio;
                        (i, cover as f32)
                    })
                    .filter(|&(_, c)| c > 0.0)
                    .collect()
            })
            .collect()
    };
    let (across, down) = (weights(width, w), weights(height, h));
    // Across each row first, premultiplied, then down each column.
    let mut rows = vec![0f32; 4 * w as usize * height as usize];
    for y in 0..height as usize {
        let line = &rgba[4 * y * width as usize..][..4 * width as usize];
        for (x, ws) in across.iter().enumerate() {
            let mut sum = [0f32; 4];
            for &(i, c) in ws {
                let p = &line[4 * i..][..4];
                let a = p[3] as f32 * c;
                sum[0] += p[0] as f32 * a;
                sum[1] += p[1] as f32 * a;
                sum[2] += p[2] as f32 * a;
                sum[3] += a;
            }
            rows[4 * (y * w as usize + x)..][..4].copy_from_slice(&sum);
        }
    }
    let mut out = vec![0u8; 4 * w as usize * h as usize];
    for (y, ws) in down.iter().enumerate() {
        for x in 0..w as usize {
            let mut sum = [0f32; 4];
            for &(i, c) in ws {
                let p = &rows[4 * (i * w as usize + x)..][..4];
                for k in 0..4 {
                    sum[k] += p[k] * c;
                }
            }
            let px = &mut out[4 * (y * w as usize + x)..][..4];
            if sum[3] > 0.0 {
                for k in 0..3 {
                    px[k] = (sum[k] / sum[3]).round().clamp(0.0, 255.0) as u8;
                }
                px[3] = sum[3].round().clamp(0.0, 255.0) as u8;
            }
        }
    }
    (out, w, h)
}

/// Where an attribute was written, for a problem found only once the design
/// is laid out and painted. It is never part of what a node draws: two nodes
/// that differ only in it are equal, and it doesn't travel on the wire.
#[derive(Debug, Clone)]
pub struct Origin {
    pub file: String,
    pub pos: Pos,
}

impl Default for Origin {
    fn default() -> Origin {
        Origin {
            file: String::new(),
            pos: Pos { line: 1, col: 1 },
        }
    }
}

impl PartialEq for Origin {
    fn eq(&self, _: &Origin) -> bool {
        true
    }
}

/// An `Image`'s file: its address in the served folder and which
/// [`ImageFile`] in the scene it shows.
#[derive(Debug, Clone, PartialEq)]
pub struct Image {
    pub src: String,
    pub id: ImageId,
    /// Where `src` was written.
    pub at: Origin,
}

/// A PNG or JPEG file's pixels, as straight-alpha RGBA, or why it has none.
pub fn decode(data: &[u8]) -> Result<ImageData, String> {
    let (pixels, width, height) = if data.starts_with(b"\x89PNG\r\n\x1a\n") {
        let broken = |e: &dyn std::fmt::Display| format!("is a PNG that doesn't decode: {e}");
        let mut decoder = png::Decoder::new(std::io::Cursor::new(data));
        decoder.set_transformations(png::Transformations::normalize_to_color8());
        let mut reader = decoder.read_info().map_err(|e| broken(&e))?;
        let size = reader
            .output_buffer_size()
            .ok_or_else(|| broken(&"too big to hold"))?;
        let mut buf = vec![0; size];
        let info = reader.next_frame(&mut buf).map_err(|e| broken(&e))?;
        buf.truncate(info.buffer_size());
        let rgba = match info.color_type {
            png::ColorType::Rgba => buf,
            png::ColorType::Rgb => buf
                .chunks(3)
                .flat_map(|p| [p[0], p[1], p[2], 255])
                .collect(),
            png::ColorType::GrayscaleAlpha => buf
                .chunks(2)
                .flat_map(|p| [p[0], p[0], p[0], p[1]])
                .collect(),
            png::ColorType::Grayscale => buf.iter().flat_map(|&g| [g, g, g, 255]).collect(),
            // Expanded to RGB by `normalize_to_color8`.
            png::ColorType::Indexed => return Err(broken(&"an unexpanded palette")),
        };
        (rgba, info.width, info.height)
    } else if data.starts_with(&[0xff, 0xd8, 0xff]) {
        use zune_jpeg::JpegDecoder;
        use zune_jpeg::zune_core::colorspace::ColorSpace;
        use zune_jpeg::zune_core::options::DecoderOptions;
        let broken = |e: &dyn std::fmt::Display| format!("is a JPEG that doesn't decode: {e}");
        let options = DecoderOptions::default()
            .set_strict_mode(true)
            .jpeg_set_out_colorspace(ColorSpace::RGBA);
        let mut decoder = JpegDecoder::new_with_options(std::io::Cursor::new(data), options);
        let pixels = decoder.decode().map_err(|e| broken(&e))?;
        let info = decoder.info().ok_or_else(|| broken(&"no header"))?;
        (pixels, info.width as u32, info.height as u32)
    } else {
        return Err("is not a PNG or JPEG file".into());
    };
    if width == 0 || height == 0 || pixels.len() != width as usize * height as usize * 4 {
        return Err(format!(
            "is an image of {width}×{height} pixels that doesn't decode whole"
        ));
    }
    Ok(ImageData {
        data: Blob::new(Arc::new(pixels)),
        format: ImageFormat::Rgba8,
        alpha_type: ImageAlphaType::Alpha,
        width,
        height,
    })
}

#[derive(Debug, Clone, PartialEq)]
pub struct Shadow {
    pub x: f32,
    pub y: f32,
    pub blur: f32,
    pub spread: f32,
    pub color: Color,
    /// Where `shadow` was written.
    pub at: Origin,
}

#[derive(Debug, Clone, PartialEq)]
pub struct TextStyle {
    /// The font file the text is set in, the face its weight picked; `None`
    /// for Inter.
    pub font: Option<FontId>,
    pub content: String,
    pub size: f32,
    pub weight: u16,
    pub color: Color,
    pub line_height: f32,
    pub align: TextAlign,
}

/// One node of a scene.
#[derive(Debug, Clone, PartialEq)]
pub struct Node {
    pub kind: Kind,
    pub name: String,
    pub x: f32,
    pub y: f32,
    pub width: Size,
    pub height: Size,
    pub opacity: f32,
    pub on_click: Option<String>,
    pub fill: Option<Fill>,
    pub stroke: Option<Color>,
    pub stroke_width: f32,
    pub radius: [f32; 4],
    pub shadow: Option<Shadow>,
    pub clip: bool,
    pub layout: Layout,
    pub gap: f32,
    pub padding: [f32; 4],
    pub align: Align,
    pub justify: Align,
    pub text: Option<TextStyle>,
    pub vector: Option<Vector>,
    pub image: Option<Image>,
    pub children: Vec<Node>,
}

impl Node {
    fn new(kind: Kind, name: &str) -> Node {
        Node {
            kind,
            name: name.to_string(),
            x: 0.0,
            y: 0.0,
            width: Size::Hug,
            height: Size::Hug,
            opacity: 1.0,
            on_click: None,
            fill: None,
            stroke: None,
            stroke_width: 1.0,
            radius: [0.0; 4],
            shadow: None,
            clip: false,
            layout: Layout::None,
            gap: 0.0,
            padding: [0.0; 4],
            align: Align::Start,
            justify: Align::Start,
            text: None,
            vector: None,
            image: None,
            children: Vec::new(),
        }
    }
}

/// Reads a design's files by their path from the top of the served folder.
pub trait Files {
    /// A file's bytes: a design's text, an `Image`'s file or a font file.
    fn bytes(&self, path: &str) -> Option<Vec<u8>>;
    /// The names of the files directly in the folder at `path`, sorted;
    /// `None` when there is no such folder. A font folder is read this way.
    fn list(&self, path: &str) -> Option<Vec<String>>;
    /// A design file's text.
    fn read(&self, path: &str) -> Option<String> {
        String::from_utf8(self.bytes(path)?).ok()
    }
    /// The image file at `path`, decoded, or why it doesn't decode; `None`
    /// when there is no such file. A store that keeps files between resolves
    /// keeps their decoded images too, so a save doesn't decode them again.
    fn image(&self, path: &str) -> Option<Result<Arc<ImageFile>, String>> {
        self.bytes(path)
            .map(|bytes| ImageFile::new(bytes).map(Arc::new))
    }
    /// The font file at `path`, checked, or why it isn't one; `None` when
    /// there is no such file. A store that keeps files between resolves
    /// keeps them checked too.
    fn font(&self, path: &str) -> Option<Result<Arc<FontFile>, String>> {
        self.bytes(path)
            .map(|bytes| FontFile::new(bytes).map(Arc::new))
    }
}

/// The names of the files directly in `folder`, from every path a store
/// holds — `None` when it holds none there.
pub fn listed<'a>(paths: impl Iterator<Item = &'a String>, folder: &str) -> Option<Vec<String>> {
    let prefix = format!("{folder}/");
    let mut names: Vec<String> = paths
        .filter_map(|p| p.strip_prefix(&prefix))
        .filter(|rest| !rest.contains('/'))
        .map(str::to_string)
        .collect();
    names.sort();
    (!names.is_empty()).then_some(names)
}

impl Files for HashMap<String, String> {
    fn bytes(&self, path: &str) -> Option<Vec<u8>> {
        self.get(path).map(|s| s.clone().into_bytes())
    }
    fn list(&self, path: &str) -> Option<Vec<String>> {
        listed(self.keys(), path)
    }
}

/// A resolved design: its tree, each distinct image file its `Image`s show
/// and font file its texts are set in, the files it was made from, and
/// whether it is **themed** — whether any `theme.` reference reached its
/// nodes.
#[derive(Debug, Clone, PartialEq)]
pub struct Scene {
    pub root: Node,
    pub images: ImageFiles,
    pub fonts: FontFiles,
    pub files: Vec<String>,
    pub themed: bool,
}

/// A scene's image files by id, each decoded once however many `Image`s
/// show it.
pub type ImageFiles = std::collections::BTreeMap<ImageId, Arc<ImageFile>>;

/// Image files compare by their identity, which is their bytes.
impl PartialEq for ImageFile {
    fn eq(&self, other: &ImageFile) -> bool {
        self.id == other.id
    }
}

/// Resolves the design at `path`, reporting every problem found.
pub fn resolve(files: &dyn Files, path: &str) -> Result<Scene, Vec<Problem>> {
    let mut r = Resolver {
        files,
        problems: Vec::new(),
        read: Vec::new(),
        stack: Vec::new(),
        missing: Vec::new(),
        depth: 0,
        images: ImageFiles::new(),
        by_path: HashMap::new(),
        fonts: FontFiles::new(),
        families: HashMap::new(),
        themes: HashMap::new(),
        themed: false,
    };
    let root = r.design(path, &[], None, "", None);
    if r.problems.is_empty() {
        Ok(Scene {
            root: root.expect("no problems means a root"),
            images: r.images,
            fonts: r.fonts,
            files: r.read,
            themed: r.themed,
        })
    } else {
        Err(r.problems)
    }
}

struct Resolver<'a> {
    files: &'a dyn Files,
    problems: Vec<Problem>,
    read: Vec<String>,
    stack: Vec<String>,
    /// Imports already reported as `no such file`, so a use of one isn't
    /// reported a second time.
    missing: Vec<String>,
    /// How many elements enclose the current one, across instances.
    depth: usize,
    /// Every image file the design shows, by id.
    images: ImageFiles,
    /// Each image file read so far, by its path.
    by_path: HashMap<String, Result<ImageId, String>>,
    /// Every font file the design's texts are set in, by id.
    fonts: FontFiles,
    /// Each font a `themes.yml` named and a text used so far, file or
    /// folder, by its path, and whether its problem was reported yet: once
    /// per resolve, however many texts use it.
    families: HashMap<String, (Found, bool)>,
    /// The themes each folder's designs use, merged from every `themes.yml`
    /// from that folder up, by folder: read once per resolve.
    themes: HashMap<String, Rc<Themes>>,
    /// Whether a `theme.` reference reached a node.
    themed: bool,
}

/// The themes a folder's designs use: every `themes.yml` with `kind: themes`
/// from the top of the served folder down to it, merged — a lower file's
/// names over a higher one's, theme by theme.
#[derive(Debug, Clone, Default)]
struct Themes {
    /// Whether any such file was found.
    found: bool,
    light: BTreeMap<String, Rgba>,
    dark: BTreeMap<String, Rgba>,
    /// The fonts the files name, by name, a lower file's over a higher one's.
    fonts: BTreeMap<String, ThemesFont>,
}

/// A font a `themes.yml`'s `fonts` names: its path as written, its address —
/// `None` when it leaves the served folder — and where it is written.
#[derive(Debug, Clone)]
struct ThemesFont {
    written: String,
    at: Option<String>,
    origin: Origin,
}

/// One `themes.yml`'s two themes and the fonts it names, as far as they are
/// valid.
struct ThemesFile {
    light: BTreeMap<String, Rgba>,
    dark: BTreeMap<String, Rgba>,
    fonts: BTreeMap<String, ThemesFont>,
}

/// The file a folder's themes are in.
pub const THEMES_FILE: &str = "themes.yml";

/// How deep a resolved design's tree may nest, counting through instances:
/// the parser's own limit for one file, and so far beyond any real design.
const MAX_DEPTH: usize = parse::MAX_DEPTH;

/// A prop's value and the file that wrote it, which a path in it is
/// relative to.
#[derive(Debug, Clone)]
struct Given {
    value: Value,
    by: String,
}

type Props = HashMap<String, Given>;

/// A font a `font` names: its family, or why it can't be used; `None` when
/// there is nothing there.
type Found = Option<Result<Rc<Family>, String>>;

impl Resolver<'_> {
    fn problem(&mut self, file: &str, pos: Pos, message: String) {
        self.problems.push(Problem {
            file: file.to_string(),
            pos,
            message,
        });
    }

    /// Binds every theme color written in `el` and the elements in it — in
    /// `path`'s file — to that file's themes.
    fn bind_element(&mut self, path: &str, el: &mut Element) {
        for attr in &mut el.attrs {
            self.bind(path, &mut attr.value);
        }
        for child in &mut el.children {
            if let Child::Element(e) = child {
                self.bind_element(path, e);
            }
        }
    }

    /// Binds a value written in `path` to `path`'s themes: `theme.name` to
    /// its two colors, and a gradient naming theme colors to one gradient
    /// per theme.
    fn bind(&mut self, path: &str, value: &mut Value) {
        match value {
            Value::Theme(name, pos) => {
                // A problem already when there is none; any color keeps
                // the rest of the design checked.
                let (light, dark) = self
                    .theme_color(path, name, *pos)
                    .map_or(("#0000".into(), "#0000".into()), |(l, d)| (hex(l), hex(d)));
                *value = Value::Themed {
                    light,
                    dark,
                    written: format!("theme.{name}"),
                };
            }
            Value::Str(s, pos) if s.starts_with("linear-gradient(") && s.contains("theme.") => {
                let (mut light, mut dark) = (String::new(), String::new());
                let mut rest = s.as_str();
                let mut col = pos.col + 1;
                while let Some(at) = rest.find("theme.") {
                    let before = &rest[..at];
                    light.push_str(before);
                    dark.push_str(before);
                    col += before.chars().count() as u32;
                    let after = &rest[at + "theme.".len()..];
                    let len = after
                        .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '-'))
                        .unwrap_or(after.len());
                    let name = &after[..len];
                    let at_ref = Pos {
                        line: pos.line,
                        col,
                    };
                    match self.theme_color(path, name, at_ref) {
                        Some((l, d)) => {
                            light.push_str(&hex(l));
                            dark.push_str(&hex(d));
                        }
                        // A problem already; any color keeps the rest checked.
                        None => {
                            light.push_str("#0000");
                            dark.push_str("#0000");
                        }
                    }
                    col += ("theme.".len() + name.chars().count()) as u32;
                    rest = &after[len..];
                }
                light.push_str(rest);
                dark.push_str(rest);
                *value = Value::Themed {
                    light,
                    dark,
                    written: format!("\"{s}\""),
                };
            }
            Value::Array(items) => {
                for item in items {
                    self.bind(path, item);
                }
            }
            Value::Object(fields) => {
                for (_, v) in fields {
                    self.bind(path, v);
                }
            }
            _ => {}
        }
    }

    /// The two colors of `theme.name`, written at `pos` in `path`, from the
    /// themes of `path`'s folder — or `None`, with the problem reported.
    fn theme_color(&mut self, path: &str, name: &str, pos: Pos) -> Option<(Rgba, Rgba)> {
        let folder = path.rsplit_once('/').map_or("", |(folder, _)| folder);
        let themes = self.themes(folder);
        let problem = if !themes.found {
            format!(
                "theme.{name}: no {THEMES_FILE} with kind: themes in this design's folder or above it"
            )
        } else {
            match (themes.light.get(name), themes.dark.get(name)) {
                (Some(l), Some(d)) => return Some((*l, *d)),
                (None, None) => {
                    let mut names: Vec<&String> =
                        themes.light.keys().chain(themes.dark.keys()).collect();
                    names.sort();
                    names.dedup();
                    let names: Vec<&str> = names.iter().map(|n| n.as_str()).collect();
                    if names.is_empty() {
                        format!("theme.{name}: the themes have no colors")
                    } else {
                        format!(
                            "theme.{name}: the themes have no {name}; they have {}",
                            names.join(", ")
                        )
                    }
                }
                (Some(_), None) => format!(
                    "theme.{name}: only the light theme has {name}; a name needs a color in both"
                ),
                (None, Some(_)) => format!(
                    "theme.{name}: only the dark theme has {name}; a name needs a color in both"
                ),
            }
        };
        self.problem(path, pos, problem);
        None
    }

    /// The themes the designs in `folder` use: its own `themes.yml` over
    /// those of the folders above it, each read once per resolve — a missing
    /// one too, so that creating it counts as a change.
    fn themes(&mut self, folder: &str) -> Rc<Themes> {
        if let Some(themes) = self.themes.get(folder) {
            return themes.clone();
        }
        let above = match folder.rsplit_once('/') {
            Some((parent, _)) => self.themes(parent),
            None if folder.is_empty() => Rc::new(Themes::default()),
            None => self.themes(""),
        };
        let file = if folder.is_empty() {
            THEMES_FILE.to_string()
        } else {
            format!("{folder}/{THEMES_FILE}")
        };
        let themes = match self.themes_file(&file) {
            None => above,
            Some(own) => {
                let mut merged = (*above).clone();
                merged.found = true;
                merged.light.extend(own.light);
                merged.dark.extend(own.dark);
                merged.fonts.extend(own.fonts);
                Rc::new(merged)
            }
        };
        self.themes.insert(folder.to_string(), themes.clone());
        themes
    }

    /// The themes in the file at `path`, as far as they are valid, with its
    /// problems reported; `None` when there is no such file or it isn't a
    /// themes file — its `kind` isn't `themes`.
    fn themes_file(&mut self, path: &str) -> Option<ThemesFile> {
        let text = self.files.read(path)?;
        if !self.read.iter().any(|p| p == path) {
            self.read.push(path.to_string());
        }
        let mut file = ThemesFile {
            light: BTreeMap::new(),
            dark: BTreeMap::new(),
            fonts: BTreeMap::new(),
        };
        let yaml: serde_yaml::Value = match serde_yaml::from_str(&text) {
            Ok(yaml) => yaml,
            Err(e) => {
                // Only a file that says it is a themes file is ours to report.
                if !text.lines().any(|l| l.trim() == "kind: themes") {
                    return None;
                }
                let pos = e.location().map_or(Pos { line: 1, col: 1 }, |l| Pos {
                    line: l.line() as u32,
                    col: l.column() as u32,
                });
                self.problem(path, pos, format!("this themes file isn't valid YAML: {e}"));
                return Some(file);
            }
        };
        let serde_yaml::Value::Mapping(top) = yaml else {
            return None;
        };
        if top.get("kind").and_then(|k| k.as_str()) != Some("themes") {
            return None;
        }
        let start = Pos { line: 1, col: 1 };
        for (key, value) in &top {
            let key = key.as_str().unwrap_or_default();
            let theme = match key {
                "kind" => continue,
                "light" => &mut file.light,
                "dark" => &mut file.dark,
                "fonts" => {
                    self.themes_fonts(path, &text, value, &mut file.fonts);
                    continue;
                }
                other => {
                    let pos = key_pos(&text, None, other).unwrap_or(start);
                    self.problem(
                        path,
                        pos,
                        format!("{other}: a themes file has kind, fonts, light and dark only"),
                    );
                    continue;
                }
            };
            let at = key_pos(&text, None, key).unwrap_or(start);
            let serde_yaml::Value::Mapping(colors) = value else {
                self.problem(
                    path,
                    at,
                    format!("{key}: expected a map of names to colors, like surface: \"#ffffff\""),
                );
                continue;
            };
            for (name, color) in colors {
                let Some(name) = name.as_str() else {
                    self.problem(path, at, format!("{key}: a color's name is text"));
                    continue;
                };
                let pos = key_pos(&text, Some(key), name).unwrap_or(at);
                if name.is_empty()
                    || name.starts_with(|c: char| c.is_ascii_digit() || c == '-')
                    || !name
                        .chars()
                        .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
                {
                    self.problem(
                        path,
                        pos,
                        format!(
                            "{key}.{name}: a name holds letters, digits, _ and -, and starts with a letter"
                        ),
                    );
                    continue;
                }
                let value = match color {
                    serde_yaml::Value::String(s) => rgba(s),
                    serde_yaml::Value::Null => Err(
                        "no color: write it in quotes, \"#rrggbb\", as YAML reads # as a comment"
                            .to_string(),
                    ),
                    _ => Err("expected a color like \"#rrggbb\"".to_string()),
                };
                match value {
                    Ok(c) => {
                        theme.insert(name.to_string(), c);
                    }
                    Err(e) => self.problem(path, pos, format!("{key}.{name}: {e}")),
                }
            }
        }
        for needed in ["light", "dark"] {
            if !top.contains_key(needed) {
                self.problem(
                    path,
                    start,
                    format!("a themes file has a light and a dark theme; this one has no {needed}"),
                );
            }
        }
        Some(file)
    }

    /// The fonts a `themes.yml` at `path` names in `value`, its `fonts`, each
    /// a name and a path from that file; a bad entry is a problem at its
    /// line.
    fn themes_fonts(
        &mut self,
        path: &str,
        text: &str,
        value: &serde_yaml::Value,
        into: &mut BTreeMap<String, ThemesFont>,
    ) {
        let start = Pos { line: 1, col: 1 };
        let at = key_pos(text, None, "fonts").unwrap_or(start);
        let serde_yaml::Value::Mapping(entries) = value else {
            self.problem(
                path,
                at,
                "fonts: expected a map of names to font files or folders, like figtree: ./fonts/Figtree".into(),
            );
            return;
        };
        for (name, written) in entries {
            let Some(name) = name.as_str() else {
                self.problem(path, at, "fonts: a font's name is text".into());
                continue;
            };
            let pos = key_pos(text, Some("fonts"), name).unwrap_or(at);
            if name.is_empty()
                || !name
                    .chars()
                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
            {
                self.problem(
                    path,
                    pos,
                    format!(
                        "fonts.{name}: a font's name holds lowercase letters, digits and - only"
                    ),
                );
                continue;
            }
            let Some(written) = written.as_str() else {
                self.problem(
                    path,
                    pos,
                    format!("fonts.{name}: expected a path to a font file or a folder of one family's, like ./fonts/Figtree"),
                );
                continue;
            };
            into.insert(
                name.to_string(),
                ThemesFont {
                    written: written.to_string(),
                    at: join(path, written),
                    origin: Origin {
                        file: path.to_string(),
                        pos,
                    },
                },
            );
        }
    }

    /// The root node of the design at `path`, with `args` given to its props.
    fn design(
        &mut self,
        path: &str,
        args: &[(parse::Attr, String)],
        from: Option<(&str, Pos)>,
        used_as: &str,
        parent: Option<Layout>,
    ) -> Option<Node> {
        if self.stack.iter().any(|p| p == path) {
            let (file, pos) = from.unwrap_or((path, Pos { line: 1, col: 1 }));
            self.problem(file, pos, format!("{path} uses itself"));
            return None;
        }
        let Some(source) = self.files.read(path) else {
            if from.is_some() && self.missing.iter().any(|p| p == path) {
                return None;
            }
            let (file, pos) = from.unwrap_or((path, Pos { line: 1, col: 1 }));
            self.problem(file, pos, format!("{path} — no such file"));
            return None;
        };
        if !self.read.iter().any(|p| p == path) {
            self.read.push(path.to_string());
        }
        let mut file = match parse::parse(&source) {
            Ok(file) => file,
            Err(mut problem) => {
                problem.file = path.to_string();
                self.problems.push(problem);
                return None;
            }
        };
        // Bound now, before any value leaves this file as a prop: a theme
        // color is this file's, wherever it is used.
        self.bind_element(path, &mut file.root);
        let mut imports = HashMap::new();
        for import in &file.imports {
            if import.name == parse::THEME {
                self.problem(
                    path,
                    import.pos,
                    format!(
                        "import {0} — {0} is the name of the design's themes",
                        import.name
                    ),
                );
                continue;
            }
            if ELEMENTS.contains(&import.name.as_str()) {
                self.problem(
                    path,
                    import.pos,
                    format!("import {0} — {0} is a built-in element", import.name),
                );
                continue;
            }
            if imports.contains_key(&import.name) {
                self.problem(
                    path,
                    import.pos,
                    format!("import {0} — {0} is already imported", import.name),
                );
                continue;
            }
            if !import.path.ends_with(".design") {
                self.problem(
                    path,
                    import.pos,
                    format!("import {} — a design is a .design file", import.path),
                );
                continue;
            }
            match join(path, &import.path) {
                Some(target) => {
                    // Every import must exist, used or not.
                    if self.files.read(&target).is_none() {
                        self.problem(
                            path,
                            import.pos,
                            format!("import {} — no such file", import.path),
                        );
                        self.missing.push(target.clone());
                    }
                    imports.insert(import.name.clone(), target);
                }
                None => self.problem(
                    path,
                    import.pos,
                    format!("import {} — outside the served folder", import.path),
                ),
            }
        }
        if file.root.name != "Frame" {
            self.problem(
                path,
                file.root.pos,
                format!("the root element must be a Frame, not {}", file.root.name),
            );
            return None;
        }
        // Props: the root's declared defaults, overridden by the instance's.
        let mut props = Props::new();
        if let Some(attr) = file.root.attrs.iter().find(|a| a.name == "props") {
            match &attr.value {
                Value::Object(fields) => {
                    for (k, v) in fields {
                        if k == parse::THEME {
                            self.problem(
                                path,
                                attr.pos,
                                format!(
                                    "props: {k} is the name of the design's themes, not a prop"
                                ),
                            );
                            continue;
                        }
                        props.insert(
                            k.clone(),
                            Given {
                                value: v.clone(),
                                by: path.to_string(),
                            },
                        );
                    }
                }
                _ => self.problem(
                    path,
                    attr.pos,
                    "props: expected an object of defaults".into(),
                ),
            }
        }
        let (caller, caller_pos) = from.unwrap_or((path, file.root.pos));
        let caller = caller.to_string();
        let mut overrides = Vec::new();
        for (arg, by) in args {
            if matches!(
                arg.name.as_str(),
                "x" | "y" | "width" | "height" | "name" | "opacity" | "onClick"
            ) {
                overrides.push((arg.clone(), by.clone()));
            } else if props.contains_key(&arg.name) {
                props.insert(
                    arg.name.clone(),
                    Given {
                        value: arg.value.clone(),
                        by: by.clone(),
                    },
                );
            } else {
                self.problem(
                    &caller,
                    arg.pos,
                    format!("{used_as} has no prop \"{}\"", arg.name),
                );
            }
        }
        let _ = caller_pos;
        self.stack.push(path.to_string());
        let mut root = self.element(path, &file.root, &props, &imports, true, parent);
        self.stack.pop();
        if let Some(root) = root.as_mut() {
            for (attr, by) in &overrides {
                // The caller's own props are already substituted into these.
                self.common(&caller, by, root, attr, attr.value.clone());
                self.fill_needs_layout(&caller, attr, &attr.value, parent);
                self.place_needs_no_layout(&caller, attr, parent);
            }
        }
        root
    }

    fn element(
        &mut self,
        path: &str,
        el: &Element,
        props: &Props,
        imports: &HashMap<String, String>,
        root: bool,
        parent: Option<Layout>,
    ) -> Option<Node> {
        if self.depth >= MAX_DEPTH {
            self.problem(path, el.pos, format!("nested more than {MAX_DEPTH} deep"));
            return None;
        }
        self.depth += 1;
        let node = self.element_inner(path, el, props, imports, root, parent);
        self.depth -= 1;
        node
    }

    fn element_inner(
        &mut self,
        path: &str,
        el: &Element,
        props: &Props,
        imports: &HashMap<String, String>,
        root: bool,
        parent: Option<Layout>,
    ) -> Option<Node> {
        // An attribute given twice is a problem, on an element or an instance
        // alike; the first one counts.
        let mut seen: Vec<&str> = Vec::new();
        let mut attrs = Vec::new();
        for attr in &el.attrs {
            if seen.contains(&attr.name.as_str()) {
                self.problem(path, attr.pos, format!("{} is given twice", attr.name));
            } else {
                seen.push(&attr.name);
                attrs.push(attr);
            }
        }
        if let Some(target) = imports.get(&el.name) {
            if !el.children.is_empty() {
                self.problem(path, el.pos, format!("{} takes no children", el.name));
            }
            let args: Vec<(parse::Attr, String)> = attrs
                .iter()
                .map(|a| {
                    let (value, by) = substitute(&a.value, props, path);
                    let arg = parse::Attr {
                        name: a.name.clone(),
                        value,
                        pos: a.pos,
                    };
                    (arg, by)
                })
                .collect();
            let target = target.clone();
            return self.design(&target, &args, Some((path, el.pos)), &el.name, parent);
        }
        let kind = match el.name.as_str() {
            // Keep in step with ELEMENTS.
            "Frame" => Kind::Frame,
            "Text" => Kind::Text,
            "Rect" => Kind::Rect,
            "Ellipse" => Kind::Ellipse,
            "Vector" => Kind::Vector,
            "Image" => Kind::Image,
            other => {
                self.problem(path, el.pos, format!("unknown element {other}"));
                return None;
            }
        };
        let mut node = Node::new(kind, &el.name);
        // A text's `font`, as given and by the file that wrote it, chosen a
        // face from once its weight is known.
        let mut font = None;
        for &attr in &attrs {
            if attr.name == "props" {
                if !root {
                    self.problem(
                        path,
                        attr.pos,
                        "props: only a design's root declares props".into(),
                    );
                }
                continue;
            }
            // Shown on its own a design has no parent to place it in, and used
            // as an instance it goes where the instance's own x and y say.
            if root && matches!(attr.name.as_str(), "x" | "y") {
                self.problem(
                    path,
                    attr.pos,
                    format!(
                        "{}: a design's root has no place of its own; place an instance with x and y where it is used",
                        attr.name
                    ),
                );
                continue;
            }
            let (value, by) = match &attr.value {
                Value::Prop(p) => match props.get(p) {
                    Some(given) => (given.value.clone(), given.by.clone()),
                    None => {
                        self.problem(path, attr.pos, format!("{}: no prop \"{p}\"", attr.name));
                        continue;
                    }
                },
                v => (v.clone(), path.to_string()),
            };
            self.themed |= has_theme(&value);
            self.fill_needs_layout(path, attr, &value, parent);
            self.place_needs_no_layout(path, attr, parent);
            if kind == Kind::Text && attr.name == "font" {
                font = Some((attr, value, by));
                continue;
            }
            self.attribute(path, &by, &mut node, attr, value);
        }
        match kind {
            Kind::Vector if !el.attrs.iter().any(|a| a.name == "d") => self.problem(
                path,
                el.pos,
                format!("{} needs a path, d=\"M…\"", node.name),
            ),
            Kind::Image if node.image.is_none() && !el.attrs.iter().any(|a| a.name == "src") => {
                self.problem(
                    path,
                    el.pos,
                    format!("{} needs a file, src=\"…\"", node.name),
                )
            }
            _ => {}
        }
        if kind == Kind::Text {
            let mut content = String::new();
            for child in &el.children {
                match child {
                    Child::Text(parts, pos) => {
                        for part in parts {
                            match part {
                                TextPart::Literal(s) => content.push_str(s),
                                TextPart::Prop(p) => match props.get(p).map(|g| &g.value) {
                                    Some(Value::Str(s, _)) => content.push_str(s),
                                    Some(Value::Num(n)) => content.push_str(&n.to_string()),
                                    _ => self.problem(path, *pos, format!("no text prop \"{p}\"")),
                                },
                                TextPart::Theme(name, at) => self.problem(
                                    path,
                                    *at,
                                    format!(
                                        "theme.{name} is a color, not text: give it to color={{theme.{name}}}"
                                    ),
                                ),
                            }
                        }
                    }
                    Child::Element(e) => self.problem(path, e.pos, "Text holds text only".into()),
                }
            }
            let text = node.text.get_or_insert_with(default_text);
            text.content = content;
            let weight = text.weight;
            let weight_at = attrs.iter().find(|a| a.name == "weight").map(|a| a.pos);
            text.font = self.text_font(path, el.pos, font, weight, weight_at);
        } else {
            for child in &el.children {
                match child {
                    Child::Element(e) => {
                        if kind != Kind::Frame {
                            self.problem(path, e.pos, format!("{} takes no children", el.name));
                        } else if let Some(n) =
                            self.element(path, e, props, imports, false, Some(node.layout))
                        {
                            node.children.push(n);
                        }
                    }
                    Child::Text(_, pos) => self.problem(
                        path,
                        *pos,
                        format!("text belongs in a Text, not a {}", el.name),
                    ),
                }
            }
        }
        Some(node)
    }

    /// `"fill"` takes the free space of a parent's auto layout, so a child of a
    /// frame with no layout can't have it.
    fn fill_needs_layout(
        &mut self,
        path: &str,
        attr: &parse::Attr,
        value: &Value,
        parent: Option<Layout>,
    ) {
        if parent == Some(Layout::None)
            && matches!(attr.name.as_str(), "width" | "height")
            && matches!(value, Value::Str(s, _) if s == "fill")
        {
            self.problem(
                path,
                attr.pos,
                format!(
                    "{}: \"fill\" needs a parent with layout=\"row\" or \"column\"",
                    attr.name
                ),
            );
        }
    }

    /// `x` and `y` place a child inside a frame with no layout; auto layout
    /// places its children itself, so there they would mean nothing.
    fn place_needs_no_layout(&mut self, path: &str, attr: &parse::Attr, parent: Option<Layout>) {
        if matches!(parent, Some(Layout::Row | Layout::Column))
            && matches!(attr.name.as_str(), "x" | "y")
        {
            self.problem(
                path,
                attr.pos,
                format!(
                    "{}: places a child only in a frame with layout=\"none\"",
                    attr.name
                ),
            );
        }
    }

    // Each arm sets a field and says whether the value fit: `Ok(field = v)`.
    #[allow(clippy::unit_arg)]
    fn attribute(
        &mut self,
        path: &str,
        by: &str,
        node: &mut Node,
        attr: &parse::Attr,
        value: Value,
    ) {
        let kind = node.kind;
        // A path is relative to the file that wrote it, and its problem is
        // where it was written.
        let (at_file, at_pos) = written_at(path, by, attr, &value);
        let ok = match (attr.name.as_str(), kind) {
            ("x" | "y" | "width" | "height" | "name" | "opacity" | "onClick", _) => {
                self.common(path, by, node, attr, value);
                return;
            }
            ("fill", k) if k != Kind::Text => fill(&value).map(|f| node.fill = Some(f)),
            ("stroke", k) if k != Kind::Text => color(&value).map(|c| node.stroke = Some(c)),
            ("strokeWidth", k) if k != Kind::Text => px(&value).map(|n| node.stroke_width = n),
            ("radius", k) if k != Kind::Text => match &value {
                Value::Num(_) => px(&value).map(|n| node.radius = [n; 4]),
                Value::Array(a) if a.len() == 4 => {
                    pxs(a).map(|v| node.radius = [v[0], v[1], v[2], v[3]])
                }
                _ => Err("expected pixels or an array of 4".into()),
            },
            ("shadow", k) if k != Kind::Text => shadow(&value).map(|mut s| {
                s.at = Origin {
                    file: path.to_string(),
                    pos: attr.pos,
                };
                node.shadow = Some(s)
            }),
            // Only a frame has children to clip.
            ("clip", Kind::Frame) => match value {
                Value::Bool(b) => Ok(node.clip = b),
                _ => Err("expected true or false".into()),
            },
            ("layout", Kind::Frame) => match str_of(&value).as_deref() {
                Some("row") => Ok(node.layout = Layout::Row),
                Some("column") => Ok(node.layout = Layout::Column),
                Some("none") => Ok(node.layout = Layout::None),
                _ => Err("expected \"row\", \"column\" or \"none\"".into()),
            },
            ("gap", Kind::Frame) => px(&value).map(|n| node.gap = n),
            ("padding", Kind::Frame) => match &value {
                Value::Num(_) => px(&value).map(|n| node.padding = [n; 4]),
                Value::Array(a) if a.len() == 2 => {
                    pxs(a).map(|v| node.padding = [v[0], v[1], v[0], v[1]])
                }
                Value::Array(a) if a.len() == 4 => {
                    pxs(a).map(|v| node.padding = [v[0], v[1], v[2], v[3]])
                }
                other => Err(format!(
                    "expected pixels or an array of 2 or 4, found {}",
                    show(other)
                )),
            },
            ("align", Kind::Frame) => align(&value, false).map(|a| node.align = a),
            ("justify", Kind::Frame) => align(&value, true).map(|a| node.justify = a),
            ("size", Kind::Text) => {
                px(&value).map(|n| node.text.get_or_insert_with(default_text).size = n)
            }
            ("weight", Kind::Text) => match num(&value) {
                Ok(w) if fonts::WEIGHTS.iter().any(|&k| k as f32 == w) => {
                    Ok(node.text.get_or_insert_with(default_text).weight = w as u16)
                }
                _ => Err("expected 100 to 900 in steps of 100".into()),
            },
            ("color", Kind::Text) => {
                color(&value).map(|c| node.text.get_or_insert_with(default_text).color = c)
            }
            ("lineHeight", Kind::Text) => {
                px(&value).map(|n| node.text.get_or_insert_with(default_text).line_height = n)
            }
            ("textAlign", Kind::Text) => match str_of(&value).as_deref() {
                Some("left") => {
                    Ok(node.text.get_or_insert_with(default_text).align = TextAlign::Left)
                }
                Some("center") => {
                    Ok(node.text.get_or_insert_with(default_text).align = TextAlign::Center)
                }
                Some("right") => {
                    Ok(node.text.get_or_insert_with(default_text).align = TextAlign::Right)
                }
                _ => Err("expected \"left\", \"center\" or \"right\"".into()),
            },
            ("d", Kind::Vector) => match str_of(&value) {
                Some(d) => match path_numbers(&d).map_err(|e| e.to_string()).and_then(|()| {
                    vello_cpu::kurbo::BezPath::from_svg(&d)
                        .map_err(|e| format!("not SVG path data: {e}"))
                }) {
                    Ok(_) => {
                        let view_box = node.vector.as_ref().map(|v| v.view_box);
                        let view_box = view_box.unwrap_or_else(|| bounds(&d));
                        Ok(node.vector = Some(Vector { d, view_box }))
                    }
                    Err(e) => Err(e),
                },
                None => Err("expected SVG path data".into()),
            },
            ("viewBox", Kind::Vector) => match str_of(&value).as_deref().map(view_box) {
                Some(Ok(b)) => {
                    let v = node.vector.get_or_insert_with(|| Vector {
                        d: String::new(),
                        view_box: b,
                    });
                    Ok(v.view_box = b)
                }
                Some(Err(e)) => Err(e),
                None => Err("expected \"minX minY width height\"".into()),
            },
            ("src", Kind::Image) => match str_of(&value) {
                Some(src) => match join(by, &src) {
                    None => {
                        let e = format!("src: {src} — outside the served folder");
                        self.problem(&at_file, at_pos, e);
                        return;
                    }
                    Some(at) => match self.image_file(&at) {
                        None => {
                            self.problem(&at_file, at_pos, format!("src: {src} — no such file"));
                            return;
                        }
                        Some(Err(e)) => {
                            self.problem(&at_file, at_pos, format!("src: {src} {e}"));
                            return;
                        }
                        Some(Ok(id)) => {
                            node.image = Some(Image {
                                src: at,
                                id,
                                at: Origin {
                                    file: path.to_string(),
                                    pos: attr.pos,
                                },
                            });
                            Ok(())
                        }
                    },
                },
                None => Err("expected a path".into()),
            },
            (name, _) => {
                self.problem(
                    path,
                    attr.pos,
                    format!("{} takes no attribute {name}", node.name),
                );
                return;
            }
        };
        if let Err(e) = ok {
            self.problem(path, attr.pos, format!("{}: {e}", attr.name));
        }
    }

    /// The image file at `at`, by its content — read and decoded once per
    /// resolve however many `Image`s show it — or why it doesn't decode;
    /// `None` when there is no such file.
    fn image_file(&mut self, at: &str) -> Option<Result<ImageId, String>> {
        if let Some(known) = self.by_path.get(at) {
            return Some(known.clone());
        }
        let file = self.files.image(at)?;
        if !self.read.iter().any(|p| p == at) {
            self.read.push(at.to_string());
        }
        let id = file.map(|file| {
            let id = file.id;
            self.images.entry(id).or_insert(file);
            id
        });
        self.by_path.insert(at.to_string(), id.clone());
        Some(id)
    }

    /// The font file a `Text` written at `pos` in `path` is set in, for its
    /// `weight` — `None` for Inter, when it has no `font`. Its `font`, given
    /// as `value` by the file `by`, is a name the themes of `by`'s folder
    /// give a font. An unknown name is a problem where it is written; a font
    /// that can't be used, at its entry in the `themes.yml`, once; a weight
    /// the font lacks, at the `weight` — or the `Text`.
    fn text_font(
        &mut self,
        path: &str,
        pos: Pos,
        font: Option<(&parse::Attr, Value, String)>,
        weight: u16,
        weight_at: Option<Pos>,
    ) -> Option<FontId> {
        let Some((attr, value, by)) = font else {
            if !fonts::INTER_WEIGHTS.contains(&weight) {
                self.no_weight(
                    path,
                    pos,
                    weight_at,
                    weight,
                    fonts::INTER,
                    &fonts::INTER_WEIGHTS,
                );
            }
            return None;
        };
        let (file, at_pos) = written_at(path, &by, attr, &value);
        let Some(name) = str_of(&value) else {
            self.problem(
                &file,
                at_pos,
                "font: expected the name of a font the themes name, like \"figtree\"".into(),
            );
            return None;
        };
        let folder = by.rsplit_once('/').map_or("", |(folder, _)| folder);
        let named = self.themes(folder).fonts.clone();
        let Some(entry) = named.get(&name) else {
            let problem = if named.is_empty() {
                format!(
                    "font: no font named {name}; no {THEMES_FILE} in this design's folder or above it names fonts"
                )
            } else {
                let names: Vec<&str> = named.keys().map(String::as_str).collect();
                format!(
                    "font: no font named {name}; the themes name {}",
                    names.join(", ")
                )
            };
            self.problem(&file, at_pos, problem);
            return None;
        };
        let origin = entry.origin.clone();
        let Some(at) = entry.at.clone() else {
            let key = format!("{}\0{}", origin.file, name);
            if let std::collections::hash_map::Entry::Vacant(first) = self.families.entry(key) {
                first.insert((None, true));
                self.problem(
                    &origin.file,
                    origin.pos,
                    format!(
                        "fonts.{name}: {} — outside the served folder",
                        entry.written
                    ),
                );
            }
            return None;
        };
        let (family, reported) = self.family(&at);
        let family = match family {
            Some(Ok(family)) => family,
            missing_or_bad => {
                if !reported {
                    let problem = match missing_or_bad {
                        Some(Err(e)) => format!("fonts.{name}: {} {e}", entry.written),
                        _ => format!("fonts.{name}: {} — no such file or folder", entry.written),
                    };
                    self.problem(&origin.file, origin.pos, problem);
                    if let Some(known) = self.families.get_mut(&at) {
                        known.1 = true;
                    }
                }
                return None;
            }
        };
        match family.face(weight) {
            Some(face) => {
                self.fonts.entry(face.id).or_insert_with(|| face.clone());
                Some(face.id)
            }
            None => {
                let has = family.weights();
                self.no_weight(path, pos, weight_at, weight, &family.name, &has);
                None
            }
        }
    }

    /// The problem of a weight the font doesn't have: at the `Text`'s
    /// `weight`, or at the `Text` when it leaves the weight at 400.
    fn no_weight(
        &mut self,
        path: &str,
        pos: Pos,
        weight_at: Option<Pos>,
        weight: u16,
        family: &str,
        has: &[u16],
    ) {
        let message = if has.is_empty() {
            format!(
                "weight: {family} has no {weight}; it has no weight from 100 to 900 in steps of 100"
            )
        } else {
            format!(
                "weight: {family} has no {weight}; it has {}",
                fonts::list(has)
            )
        };
        self.problem(path, weight_at.unwrap_or(pos), message);
    }

    /// The font at `at` — one file, or a folder of one family's files — read
    /// and checked once per resolve, or why it can't be used; `None` when
    /// there is nothing there. Also whether its problem was reported yet.
    fn family(&mut self, at: &str) -> (Found, bool) {
        if let Some(known) = self.families.get(at) {
            return known.clone();
        }
        let family = match self.font_file(at) {
            Some(Ok(file)) => Some(Ok(Rc::new(Family {
                name: file.family.clone(),
                faces: vec![file],
            }))),
            Some(Err(e)) => Some(Err(e)),
            None => self.files.list(at).map(|names| {
                let mut faces = Vec::new();
                for name in names.into_iter().filter(|n| fonts::is_font_name(n)) {
                    match self.font_file(&format!("{at}/{name}")) {
                        Some(Ok(file)) => faces.push((name, file)),
                        Some(Err(e)) => return Err(format!("holds {name}, which {e}")),
                        // Gone since the folder was listed.
                        None => {}
                    }
                }
                Family::of_folder(faces).map(Rc::new)
            }),
        };
        self.families
            .insert(at.to_string(), (family.clone(), false));
        (family, false)
    }

    /// The font file at `at`, checked, or why it isn't one; `None` when there
    /// is no such file.
    fn font_file(&mut self, at: &str) -> Option<Result<Arc<FontFile>, String>> {
        let file = self.files.font(at)?;
        if !self.read.iter().any(|p| p == at) {
            self.read.push(at.to_string());
        }
        Some(file)
    }

    /// An interaction with its path, if it has one, made relative to the top of
    /// the served folder instead of to `path`, the file it is written in.
    fn interaction(&mut self, path: &str, action: &str) -> Result<String, String> {
        let Some((verb, target)) = action.split_once(' ') else {
            return Ok(action.to_string());
        };
        let target = target.trim();
        if !target.ends_with(".design") {
            return Err(format!("{action} — a design is a .design file"));
        }
        match join(path, target) {
            None => Err(format!("{action} — outside the served folder")),
            Some(at) if self.files.bytes(&at).is_none() => Err(format!("{action} — no such file")),
            Some(at) => Ok(format!("{verb} {at}")),
        }
    }

    fn common(&mut self, path: &str, by: &str, node: &mut Node, attr: &parse::Attr, value: Value) {
        let (at_file, at_pos) = written_at(path, by, attr, &value);
        let ok = match attr.name.as_str() {
            "x" => num(&value).map(|n| node.x = n),
            "y" => num(&value).map(|n| node.y = n),
            "width" => size(&value).map(|s| node.width = s),
            "height" => size(&value).map(|s| node.height = s),
            "name" => str_of(&value)
                .map(|s| node.name = s)
                .ok_or_else(|| "expected a string".into()),
            "opacity" => match value {
                Value::Num(n) if (0.0..=1.0).contains(&n) => {
                    node.opacity = n as f32;
                    Ok(())
                }
                other => Err(format!(
                    "expected a number from 0 to 1, found {}",
                    show(&other)
                )),
            },
            "onClick" => match str_of(&value).filter(|s| interaction_ok(s)) {
                Some(action) => match self.interaction(by, &action) {
                    Ok(a) => {
                        node.on_click = Some(a);
                        Ok(())
                    }
                    Err(e) => {
                        self.problem(&at_file, at_pos, format!("onClick: {e}"));
                        return;
                    }
                },
                None => Err(
                    "expected \"navigate <path>\", \"back\", \"overlay <path>\" or \"close\""
                        .into(),
                ),
            },
            _ => unreachable!(),
        };
        if let Err(e) = ok {
            self.problem(path, attr.pos, format!("{}: {e}", attr.name));
        }
    }
}

fn default_text() -> TextStyle {
    TextStyle {
        font: None,
        content: String::new(),
        size: 14.0,
        weight: 400,
        color: Color::fixed(Rgba {
            r: 0x0f,
            g: 0x17,
            b: 0x2a,
            a: 255,
        }),
        line_height: 1.4,
        align: TextAlign::Left,
    }
}

fn view_box(s: &str) -> Result<[f32; 4], String> {
    let v: Vec<f32> = s
        .split([' ', ','])
        .filter(|p| !p.is_empty())
        .map(|p| parse::number(p).map(|n| n as f32))
        .collect::<Result<_, _>>()?;
    match v[..] {
        [x, y, w, h] if w > 0.0 && h > 0.0 => Ok([x, y, w, h]),
        _ => Err("expected \"minX minY width height\"".into()),
    }
}

/// Every number in SVG path data `d` held to the same limits as a design's
/// other numbers. A number here is SVG's — it may have an exponent — and an
/// arc's two flags are single digits that may be written run together.
fn path_numbers(d: &str) -> Result<(), String> {
    let b = d.as_bytes();
    let mut i = 0;
    let mut command = b' ';
    // Which parameter of the current command comes next.
    let mut param = 0;
    while i < b.len() {
        let c = b[i];
        if c.is_ascii_alphabetic() && c != b'e' && c != b'E' {
            command = c;
            param = 0;
            i += 1;
            continue;
        }
        if c.is_ascii_whitespace() || c == b',' {
            i += 1;
            continue;
        }
        if matches!(command, b'A' | b'a') && matches!(param % 7, 3 | 4) && matches!(c, b'0' | b'1')
        {
            param += 1;
            i += 1;
            continue;
        }
        let start = i;
        if matches!(b[i], b'+' | b'-') {
            i += 1;
        }
        let mut dot = false;
        while i < b.len() && (b[i].is_ascii_digit() || (b[i] == b'.' && !dot)) {
            dot |= b[i] == b'.';
            i += 1;
        }
        if i < b.len() && matches!(b[i], b'e' | b'E') {
            let mut j = i + 1;
            if j < b.len() && matches!(b[j], b'+' | b'-') {
                j += 1;
            }
            if j < b.len() && b[j].is_ascii_digit() {
                i = j;
                while i < b.len() && b[i].is_ascii_digit() {
                    i += 1;
                }
            }
        }
        if i == start {
            // Not a number: the path parser says what is wrong.
            return Ok(());
        }
        let s = &d[start..i];
        if let Ok(n) = s.parse::<f64>() {
            parse::in_range(s, n)?;
        }
        param += 1;
    }
    Ok(())
}

/// A path's own bounds, the view box of a `Vector` that names none.
fn bounds(d: &str) -> [f32; 4] {
    use vello_cpu::kurbo::Shape;
    let b = vello_cpu::kurbo::BezPath::from_svg(d)
        .map(|p| p.bounding_box())
        .unwrap_or_default();
    [
        b.x0 as f32,
        b.y0 as f32,
        (b.width() as f32).max(1.0),
        (b.height() as f32).max(1.0),
    ]
}

fn interaction_ok(s: &str) -> bool {
    s == "back"
        || s == "close"
        || s.strip_prefix("navigate ")
            .or(s.strip_prefix("overlay "))
            .is_some_and(|p| !p.trim().is_empty())
}

/// A path relative to a design's file, from the top of the served folder, or
/// `None` when it climbs out of the served folder.
pub fn join(from: &str, relative: &str) -> Option<String> {
    let mut parts: Vec<&str> = from.split('/').filter(|p| !p.is_empty()).collect();
    parts.pop();
    for part in relative.split('/') {
        match part {
            "." | "" => {}
            ".." => {
                parts.pop()?;
            }
            p => parts.push(p),
        }
    }
    Some(parts.join("/"))
}

/// `value`, written in `path`, with a prop put in its place, and the file
/// that wrote what it ends up as.
fn substitute(value: &Value, props: &Props, path: &str) -> (Value, String) {
    match value {
        Value::Prop(p) => match props.get(p) {
            Some(given) => (given.value.clone(), given.by.clone()),
            None => (value.clone(), path.to_string()),
        },
        v => (v.clone(), path.to_string()),
    }
}

/// Where a path in `attr`'s `value` was written: at the attribute, in
/// `path`, or — when the value came as a prop from another file, `by` — at
/// the string there.
fn written_at(path: &str, by: &str, attr: &parse::Attr, value: &Value) -> (String, Pos) {
    match value {
        Value::Str(_, pos) if by != path => (by.to_string(), *pos),
        _ => (path.to_string(), attr.pos),
    }
}

fn show(v: &Value) -> String {
    match v {
        Value::Str(s, _) => format!("\"{s}\""),
        Value::Num(n) => n.to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Array(_) => "an array".into(),
        Value::Object(_) => "an object".into(),
        Value::Prop(p) => p.clone(),
        Value::Theme(name, _) => format!("theme.{name}"),
        Value::Themed { written, .. } => written.clone(),
    }
}

fn str_of(v: &Value) -> Option<String> {
    match v {
        Value::Str(s, _) => Some(s.clone()),
        _ => None,
    }
}

/// Where `key` is written in a themes file's text: at the top level, or —
/// with `under` — inside that top-level key's block. YAML's values carry no
/// place, so a key is found by its text: on a line of its own, plain or in
/// quotes.
fn key_pos(text: &str, under: Option<&str>, key: &str) -> Option<Pos> {
    let names = |line: &str, key: &str| {
        let line = line.trim_start();
        [
            format!("{key}:"),
            format!("\"{key}\":"),
            format!("'{key}':"),
        ]
        .iter()
        .any(|k| line.starts_with(k.as_str()))
    };
    let top = |line: &str| !line.starts_with([' ', '\t']) && !line.trim().is_empty();
    let mut inside = under.is_none();
    for (n, line) in text.lines().enumerate() {
        if line.trim_start().starts_with('#') {
            continue;
        }
        let pos = Pos {
            line: n as u32 + 1,
            col: (line.len() - line.trim_start().len()) as u32 + 1,
        };
        match under {
            None if top(line) && names(line, key) => return Some(pos),
            None => {}
            Some(block) if top(line) => inside = names(line, block),
            Some(_) if inside && names(line, key) => return Some(pos),
            Some(_) => {}
        }
    }
    None
}

/// The built-in elements; an import can't take one of their names.
const ELEMENTS: [&str; 6] = ["Frame", "Text", "Rect", "Ellipse", "Vector", "Image"];

fn num(v: &Value) -> Result<f32, String> {
    match v {
        Value::Num(n) => Ok(*n as f32),
        other => Err(format!("expected a number, found {}", show(other))),
    }
}

/// A length or a multiple that can't be negative: pixels, a size, a line height.
fn px(v: &Value) -> Result<f32, String> {
    match v {
        Value::Num(n) if *n >= 0.0 => Ok(*n as f32),
        Value::Num(n) => Err(format!("expected a number of 0 or more, found {n}")),
        other => Err(format!("expected a number, found {}", show(other))),
    }
}

fn pxs(a: &[Value]) -> Result<Vec<f32>, String> {
    a.iter().map(px).collect()
}

fn size(v: &Value) -> Result<Size, String> {
    match v {
        Value::Num(n) if *n >= 0.0 => Ok(Size::Px(*n as f32)),
        Value::Num(n) => Err(format!("expected pixels of 0 or more, found {n}")),
        Value::Str(s, _) if s == "hug" => Ok(Size::Hug),
        Value::Str(s, _) if s == "fill" => Ok(Size::Fill),
        other => Err(format!(
            "expected pixels, \"hug\" or \"fill\", found {}",
            show(other)
        )),
    }
}

fn align(v: &Value, justify: bool) -> Result<Align, String> {
    match str_of(v).as_deref() {
        Some("start") => Ok(Align::Start),
        Some("center") => Ok(Align::Center),
        Some("end") => Ok(Align::End),
        Some("space-between") if justify => Ok(Align::SpaceBetween),
        _ if justify => Err("expected \"start\", \"center\", \"end\" or \"space-between\"".into()),
        _ => Err("expected \"start\", \"center\" or \"end\"".into()),
    }
}

/// A color: a `#…` one, the same in both themes, or a theme color bound to
/// its file's themes.
fn color(v: &Value) -> Result<Color, String> {
    match v {
        Value::Str(s, _) => rgba(s).map(Color::fixed),
        Value::Themed { light, dark, .. } => Ok(Color {
            light: rgba(light)?,
            dark: rgba(dark)?,
        }),
        _ => Err(format!("expected a color, found {}", show(v))),
    }
}

/// A `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa` color.
pub fn rgba(s: &str) -> Result<Rgba, String> {
    if s.starts_with("theme.") {
        return Err(format!(
            "{s} is a theme color: write it in braces, {{{s}}}, not in quotes"
        ));
    }
    let hex = s.strip_prefix('#').ok_or("expected a color like #rrggbb")?;
    if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
        return Err(format!("{s} is not a color"));
    }
    let d = |i: usize, n: usize| {
        u8::from_str_radix(&hex[i..i + n], 16).map_err(|_| format!("{s} is not a color"))
    };
    let dd = |i: usize| d(i, 1).map(|v| v * 17);
    match hex.len() {
        3 => Ok(Rgba {
            r: dd(0)?,
            g: dd(1)?,
            b: dd(2)?,
            a: 255,
        }),
        4 => Ok(Rgba {
            r: dd(0)?,
            g: dd(1)?,
            b: dd(2)?,
            a: dd(3)?,
        }),
        6 => Ok(Rgba {
            r: d(0, 2)?,
            g: d(2, 2)?,
            b: d(4, 2)?,
            a: 255,
        }),
        8 => Ok(Rgba {
            r: d(0, 2)?,
            g: d(2, 2)?,
            b: d(4, 2)?,
            a: d(6, 2)?,
        }),
        _ => Err(format!("{s} is not a color")),
    }
}

/// `c` written as `#rrggbbaa`.
fn hex(c: Rgba) -> String {
    format!("#{:02x}{:02x}{:02x}{:02x}", c.r, c.g, c.b, c.a)
}

fn fill(v: &Value) -> Result<Fill, String> {
    match v {
        Value::Str(s, _) => fill_of(s),
        // Each theme's string differs only in its colors, so the two fills
        // have the same shape.
        Value::Themed { light, dark, .. } => match (fill_of(light)?, fill_of(dark)?) {
            (Fill::Solid(l), Fill::Solid(d)) => Ok(Fill::Solid(Color {
                light: l.light,
                dark: d.light,
            })),
            (
                Fill::Linear { angle, stops: l },
                Fill::Linear {
                    stops: d,
                    angle: dark_angle,
                },
            ) if angle == dark_angle && l.len() == d.len() => Ok(Fill::Linear {
                angle,
                stops: l
                    .iter()
                    .zip(&d)
                    .map(|((l, at), (d, _))| {
                        (
                            Color {
                                light: l.light,
                                dark: d.light,
                            },
                            *at,
                        )
                    })
                    .collect(),
            }),
            _ => Err(format!("{} is not the same fill in both themes", show(v))),
        },
        _ => Err(format!("expected a color or a gradient, found {}", show(v))),
    }
}

/// A fill written as a string, its colors the same in both themes.
fn fill_of(s: &str) -> Result<Fill, String> {
    let Some(inner) = s
        .strip_prefix("linear-gradient(")
        .and_then(|r| r.strip_suffix(')'))
    else {
        return rgba(s).map(|c| Fill::Solid(Color::fixed(c)));
    };
    let wrong =
        || format!("expected \"linear-gradient(<angle>deg, <color> <stop>%, …)\", found \"{s}\"");
    let mut parts = inner.split(',').map(str::trim);
    let angle = parts
        .next()
        .and_then(|a| a.strip_suffix("deg"))
        .ok_or_else(wrong)?;
    let angle = parse::number(angle.trim())? as f32;
    let mut stops = Vec::new();
    for part in parts {
        let (c, at) = part.split_once(' ').ok_or_else(wrong)?;
        let at = at.trim().strip_suffix('%').ok_or_else(wrong)?;
        let at = parse::number(at)? as f32;
        stops.push((Color::fixed(rgba(c)?), at / 100.0));
    }
    if stops.len() < 2 {
        return Err(wrong());
    }
    Ok(Fill::Linear { angle, stops })
}

/// Whether a value holds a theme color, at any depth.
fn has_theme(v: &Value) -> bool {
    match v {
        Value::Themed { .. } | Value::Theme(..) => true,
        Value::Array(items) => items.iter().any(has_theme),
        Value::Object(fields) => fields.iter().any(|(_, v)| has_theme(v)),
        _ => false,
    }
}

fn shadow(v: &Value) -> Result<Shadow, String> {
    let Value::Object(fields) = v else {
        return Err("expected { x, y, blur, spread, color }".into());
    };
    let mut s = Shadow {
        x: 0.0,
        y: 0.0,
        blur: 0.0,
        spread: 0.0,
        color: Color::fixed(Rgba {
            r: 0,
            g: 0,
            b: 0,
            a: 64,
        }),
        at: Origin::default(),
    };
    for (k, v) in fields {
        match k.as_str() {
            "x" => s.x = num(v)?,
            "y" => s.y = num(v)?,
            "blur" => s.blur = num(v)?,
            "spread" => s.spread = num(v)?,
            "color" => s.color = color(v)?,
            other => return Err(format!("a shadow has no {other}")),
        }
    }
    Ok(s)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn files(list: &[(&str, &str)]) -> HashMap<String, String> {
        list.iter()
            .map(|(p, s)| (p.to_string(), s.to_string()))
            .collect()
    }

    #[test]
    fn an_instance_takes_its_props() {
        let fs = files(&[
            (
                "a/button.design",
                r##"<Frame props={{ label: "Button", fill: "#2563eb" }} fill={fill}><Text>{label}</Text></Frame>"##,
            ),
            (
                "a/screen.design",
                r#"import Button from "./button.design"
<Frame width={390}><Button label="Pay" x={10} opacity={0.5} /></Frame>"#,
            ),
        ]);
        let scene = resolve(&fs, "a/screen.design").unwrap();
        let button = &scene.root.children[0];
        assert_eq!(button.x, 10.0);
        assert_eq!(button.opacity, 0.5);
        assert_eq!(
            button.fill,
            Some(Fill::Solid(Color::fixed(Rgba {
                r: 0x25,
                g: 0x63,
                b: 0xeb,
                a: 255
            })))
        );
        assert_eq!(button.children[0].text.as_ref().unwrap().content, "Pay");
        assert_eq!(scene.files, vec!["a/screen.design", "a/button.design"]);
    }

    #[test]
    fn opacity_is_between_zero_and_one() {
        let fs = files(&[
            ("dot.design", "<Frame />"),
            (
                "screen.design",
                "import Dot from \"./dot.design\"\n<Frame opacity={1}>\n  <Rect opacity={50} />\n  <Dot opacity={-0.1} />\n</Frame>",
            ),
        ]);
        let problems: Vec<String> = resolve(&fs, "screen.design")
            .unwrap_err()
            .iter()
            .map(|p| p.to_string())
            .collect();
        assert_eq!(
            problems,
            vec![
                "screen.design:3:9: opacity: expected a number from 0 to 1, found 50",
                "screen.design:4:8: opacity: expected a number from 0 to 1, found -0.1",
            ]
        );
    }

    fn problems_in(fs: &HashMap<String, String>, path: &str) -> Vec<String> {
        resolve(fs, path)
            .unwrap_err()
            .iter()
            .map(|p| p.to_string())
            .collect()
    }

    #[test]
    fn a_color_with_any_character_but_hex_digits_is_a_problem() {
        // A pasted zero-width space, other non-ASCII, and plain non-hex.
        for (value, col) in [
            ("#fff\u{200b}", 13),
            ("#ffé", 13),
            ("#ff€f00", 13),
            ("#ggg", 13),
        ] {
            let fs = files(&[("a.design", &format!(r#"<Frame fill="{value}" />"#))]);
            assert_eq!(
                problems_in(&fs, "a.design"),
                vec![format!("a.design:1:8: fill: {value} is not a color")],
                "{value:?} at {col}"
            );
        }
    }

    #[test]
    fn props_belong_to_the_root_only() {
        let fs = files(&[(
            "a.design",
            r#"<Frame props={{ a: "x" }}>
  <Frame props={{ b: "y" }} />
</Frame>"#,
        )]);
        assert_eq!(
            problems_in(&fs, "a.design"),
            vec!["a.design:2:10: props: only a design's root declares props"]
        );
    }

    #[test]
    fn a_root_has_no_place_of_its_own() {
        let fs = files(&[
            (
                "dot.design",
                r#"<Frame x={40} y={30} width={10} height={10} />"#,
            ),
            (
                "a.design",
                r#"import Dot from "./dot.design"
<Frame width={100} height={100}>
  <Dot x={5} y={6} />
</Frame>"#,
            ),
        ]);
        let expected = [
            "dot.design:1:8: x: a design's root has no place of its own; place an instance with x and y where it is used",
            "dot.design:1:15: y: a design's root has no place of its own; place an instance with x and y where it is used",
        ];
        assert_eq!(problems_in(&fs, "dot.design"), expected);
        // Used as an instance, the root's own x and y are still a problem; the
        // instance's x and y are where it goes.
        assert_eq!(problems_in(&fs, "a.design"), expected);
        let fs = files(&[
            ("dot.design", r#"<Frame width={10} height={10} />"#),
            (
                "a.design",
                r#"import Dot from "./dot.design"
<Frame width={100} height={100}>
  <Dot x={5} y={6} />
</Frame>"#,
            ),
        ]);
        let dot = &resolve(&fs, "a.design").unwrap().root.children[0];
        assert_eq!((dot.x, dot.y), (5.0, 6.0));
    }

    #[test]
    fn fill_needs_a_parent_with_auto_layout() {
        let fs = files(&[
            ("dot.design", r#"<Frame width="fill" />"#),
            (
                "a.design",
                r#"import Dot from "./dot.design"
<Frame width={100} height={100}>
  <Rect width="fill" height={10} />
  <Dot />
  <Dot height="fill" />
  <Frame layout="row"><Rect width="fill" /></Frame>
</Frame>"#,
            ),
        ]);
        assert_eq!(
            problems_in(&fs, "a.design"),
            vec![
                "a.design:3:9: width: \"fill\" needs a parent with layout=\"row\" or \"column\"",
                "dot.design:1:8: width: \"fill\" needs a parent with layout=\"row\" or \"column\"",
                "dot.design:1:8: width: \"fill\" needs a parent with layout=\"row\" or \"column\"",
                "a.design:5:8: height: \"fill\" needs a parent with layout=\"row\" or \"column\"",
            ]
        );
    }

    #[test]
    fn a_tree_nests_at_most_so_deep_through_instances() {
        // Each file nests a little; through instances the tree goes too deep.
        let mut list = Vec::new();
        let depth = 40;
        for i in 0..depth {
            let body = if i + 1 < depth {
                let inner = "<Frame>".repeat(10) + "<N />" + &"</Frame>".repeat(10);
                format!("import N from \"./{}.design\"\n{inner}", i + 1)
            } else {
                "<Frame />".to_string()
            };
            list.push((format!("{i}.design"), body));
        }
        let fs: HashMap<String, String> = list.into_iter().collect();
        let found = problems_in(&fs, "0.design");
        assert_eq!(found.len(), 1, "{found:?}");
        assert!(
            found[0].ends_with(&format!("nested more than {MAX_DEPTH} deep")),
            "{found:?}"
        );
    }

    #[test]
    fn every_problem_is_reported() {
        let fs = files(&[
            (
                "button.design",
                r#"<Frame props={{ label: "B" }} padding="12px"><Text>{label}</Text></Frame>"#,
            ),
            (
                "screen.design",
                "import Button from \"./button.design\"\nimport Row from \"./row.design\"\n<Frame>\n  <Button lable=\"x\" />\n  <Row />\n  <Blob />\n</Frame>",
            ),
        ]);
        let problems: Vec<String> = resolve(&fs, "screen.design")
            .unwrap_err()
            .iter()
            .map(|p| p.to_string())
            .collect();
        assert_eq!(
            problems,
            vec![
                "screen.design:2:1: import ./row.design — no such file",
                "screen.design:4:11: Button has no prop \"lable\"",
                "button.design:1:31: padding: expected pixels or an array of 2 or 4, found \"12px\"",
                "screen.design:6:3: unknown element Blob",
            ]
        );
    }

    #[test]
    fn an_import_of_a_missing_file_is_a_problem_even_unused() {
        let fs = files(&[("cart.design", "import Row from \"./row.design\"\n<Frame />")]);
        let problems: Vec<String> = resolve(&fs, "cart.design")
            .unwrap_err()
            .iter()
            .map(|p| p.to_string())
            .collect();
        assert_eq!(
            problems,
            vec!["cart.design:1:1: import ./row.design — no such file"]
        );
    }

    #[test]
    fn a_design_that_uses_itself() {
        let fs = files(&[(
            "a.design",
            "import A from \"./a.design\"\n<Frame><A /></Frame>",
        )]);
        let problems = resolve(&fs, "a.design").unwrap_err();
        assert_eq!(
            problems[0].to_string(),
            "a.design:2:8: a.design uses itself"
        );
    }

    /// Files as bytes, so a test can hold an image.
    struct Mem(HashMap<String, Vec<u8>>);

    impl Files for Mem {
        fn bytes(&self, path: &str) -> Option<Vec<u8>> {
            self.0.get(path).cloned()
        }
        fn list(&self, path: &str) -> Option<Vec<String>> {
            listed(self.0.keys(), path)
        }
    }

    /// A 1×1 PNG that decodes.
    fn png() -> Vec<u8> {
        let mut out = Vec::new();
        let mut e = png::Encoder::new(&mut out, 1, 1);
        e.set_color(png::ColorType::Rgba);
        let mut w = e.write_header().unwrap();
        w.write_image_data(&[0, 0, 0, 255]).unwrap();
        drop(w);
        out
    }

    fn problems(source: &str) -> Vec<String> {
        let fs = Mem([
            ("d/a.design".to_string(), source.as_bytes().to_vec()),
            ("d/photo.png".to_string(), png()),
            ("d/notes.txt".to_string(), b"hi".to_vec()),
            (
                "d/b.design".to_string(),
                br#"<Frame props={{ label: "B" }}><Text>{label}</Text></Frame>"#.to_vec(),
            ),
        ]
        .into());
        match resolve(&fs, "d/a.design") {
            Ok(_) => Vec::new(),
            Err(p) => p.iter().map(|p| p.to_string()).collect(),
        }
    }

    #[test]
    fn each_problem_names_its_place() {
        let cases = [
            (
                "<Rect />",
                "d/a.design:1:1: the root element must be a Frame, not Rect",
            ),
            (
                "<Frame props=\"x\" />",
                "d/a.design:1:8: props: expected an object of defaults",
            ),
            (
                "<Frame fill=\"red\" />",
                "d/a.design:1:8: fill: expected a color like #rrggbb",
            ),
            (
                "<Frame fill=\"#12\" />",
                "d/a.design:1:8: fill: #12 is not a color",
            ),
            (
                "<Frame fill=\"linear-gradient(90deg, #fff 0%)\" />",
                "d/a.design:1:8: fill: expected \"linear-gradient(<angle>deg, <color> <stop>%, …)\", found \"linear-gradient(90deg, #fff 0%)\"",
            ),
            (
                "<Frame width=\"wide\" />",
                "d/a.design:1:8: width: expected pixels, \"hug\" or \"fill\", found \"wide\"",
            ),
            (
                "<Frame gap=\"4\" />",
                "d/a.design:1:8: gap: expected a number, found \"4\"",
            ),
            (
                "<Frame radius={[1, 2]} />",
                "d/a.design:1:8: radius: expected pixels or an array of 4",
            ),
            (
                "<Frame layout=\"grid\" />",
                "d/a.design:1:8: layout: expected \"row\", \"column\" or \"none\"",
            ),
            (
                "<Frame align=\"space-between\" />",
                "d/a.design:1:8: align: expected \"start\", \"center\" or \"end\"",
            ),
            (
                "<Frame clip=\"yes\" />",
                "d/a.design:1:8: clip: expected true or false",
            ),
            (
                "<Frame shadow={{ blurr: 4 }} />",
                "d/a.design:1:8: shadow: a shadow has no blurr",
            ),
            (
                "<Frame onClick=\"go ./b.design\" />",
                "d/a.design:1:8: onClick: expected \"navigate <path>\", \"back\", \"overlay <path>\" or \"close\"",
            ),
            (
                "<Frame size={4} />",
                "d/a.design:1:8: Frame takes no attribute size",
            ),
            (
                "<Frame><Text fill=\"#fff\">a</Text></Frame>",
                "d/a.design:1:14: Text takes no attribute fill",
            ),
            (
                "<Frame><Text weight={450}>a</Text></Frame>",
                "d/a.design:1:14: weight: expected 100 to 900 in steps of 100",
            ),
            (
                "<Frame><Text textAlign=\"justify\">a</Text></Frame>",
                "d/a.design:1:14: textAlign: expected \"left\", \"center\" or \"right\"",
            ),
            (
                "<Frame><Text><Rect /></Text></Frame>",
                "d/a.design:1:14: Text holds text only",
            ),
            (
                "<Frame>hello</Frame>",
                "d/a.design:1:8: text belongs in a Text, not a Frame",
            ),
            (
                "<Frame><Rect><Rect /></Rect></Frame>",
                "d/a.design:1:14: Rect takes no children",
            ),
            (
                "<Frame><Text>{nope}</Text></Frame>",
                "d/a.design:1:14: no text prop \"nope\"",
            ),
            (
                "<Frame gap={nope} />",
                "d/a.design:1:8: gap: no prop \"nope\"",
            ),
            (
                "<Frame><Vector viewBox=\"0 0 24 24\" /></Frame>",
                "d/a.design:1:8: Vector needs a path, d=\"M…\"",
            ),
            (
                "<Frame><Vector d=\"M0 0 Q\" /></Frame>",
                "d/a.design:1:16: d: not SVG path data: Unexpected EOF",
            ),
            (
                "<Frame><Vector d=\"M0 0L1 1\" viewBox=\"0 0 24\" /></Frame>",
                "d/a.design:1:29: viewBox: expected \"minX minY width height\"",
            ),
            (
                "<Frame><Image /></Frame>",
                "d/a.design:1:8: Image needs a file, src=\"…\"",
            ),
            (
                "<Frame><Image src=\"./gone.png\" /></Frame>",
                "d/a.design:1:15: src: ./gone.png — no such file",
            ),
            (
                "<Frame><Image src=\"../../x.png\" /></Frame>",
                "d/a.design:1:15: src: ../../x.png — outside the served folder",
            ),
            (
                "<Frame><Image src=\"./notes.txt\" /></Frame>",
                "d/a.design:1:15: src: ./notes.txt is not a PNG or JPEG file",
            ),
            (
                "<Frame><Rect clip /></Frame>",
                "d/a.design:1:14: Rect takes no attribute clip",
            ),
            (
                "<Frame fill=\"linear-gradient(2000000deg, #fff 0%, #000 100%)\" />",
                "d/a.design:1:8: fill: `2000000` is too large: numbers go up to 1000000",
            ),
            (
                "<Frame fill=\"linear-gradient(90deg, #fff -2000000%, #000 100%)\" />",
                "d/a.design:1:8: fill: `-2000000` is too small: numbers go down to -1000000",
            ),
            (
                "<Frame fill=\"linear-gradient(NaNdeg, #fff 0%, #000 100%)\" />",
                "d/a.design:1:8: fill: `NaN` is not a number",
            ),
            (
                "<Frame fill=\"linear-gradient(90deg, #fff 0%, #000 inf%)\" />",
                "d/a.design:1:8: fill: `inf` is not a number",
            ),
            (
                "<Frame><Vector d=\"M0 0L1 1\" viewBox=\"0 0 2000000 24\" /></Frame>",
                "d/a.design:1:29: viewBox: `2000000` is too large: numbers go up to 1000000",
            ),
            (
                "<Frame><Vector d=\"M0 0L1 1\" viewBox=\"0 0 inf 24\" /></Frame>",
                "d/a.design:1:29: viewBox: `inf` is not a number",
            ),
            (
                "<Frame><Vector d=\"M0 0L2000000 0\" /></Frame>",
                "d/a.design:1:16: d: `2000000` is too large: numbers go up to 1000000",
            ),
            (
                "<Frame><Vector d=\"M0 0L1e999 0\" /></Frame>",
                "d/a.design:1:16: d: `1e999` is too large: numbers go up to 1000000",
            ),
            (
                "<Frame><Vector d=\"M0 0L-3e6 0\" /></Frame>",
                "d/a.design:1:16: d: `-3e6` is too small: numbers go down to -1000000",
            ),
            (
                "import X from \"../../x.design\"\n<Frame />",
                "d/a.design:1:1: import ../../x.design — outside the served folder",
            ),
            (
                "import B from \"./b.design\"\n<Frame><B fill=\"#fff\" /></Frame>",
                "d/a.design:2:11: B has no prop \"fill\"",
            ),
            (
                "import B from \"./b.design\"\n<Frame><B>x</B></Frame>",
                "d/a.design:2:8: B takes no children",
            ),
            (
                "<Frame><Blob /></Frame>",
                "d/a.design:1:8: unknown element Blob",
            ),
        ];
        for (source, expected) in cases {
            assert_eq!(problems(source), vec![expected.to_string()], "{source}");
        }
    }

    /// An image file is decoded whole while resolving, so a broken one is a
    /// problem at its `src` — not a blank box — wherever the design is shown.
    #[test]
    fn an_image_that_does_not_decode_is_a_problem() {
        let mut broken = b"\x89PNG\r\n\x1a\n".to_vec();
        broken.extend(b"not a PNG past its signature");
        let shirt = std::fs::read(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../docs/designs/checkout/shirt.jpg"
        ))
        .unwrap();
        let truncated = shirt[..shirt.len() / 2].to_vec();
        for (name, data, expected) in [
            (
                "broken.png",
                broken,
                "d/a.design:2:8: src: ./broken.png is a PNG that doesn't decode: ",
            ),
            (
                "shirt.jpg",
                truncated,
                "d/a.design:2:8: src: ./shirt.jpg is a JPEG that doesn't decode: ",
            ),
        ] {
            let source =
                format!("<Frame>\n<Image src=\"./{name}\" width={{50}} height={{50}} />\n</Frame>");
            let fs = Mem([
                ("d/a.design".to_string(), source.into_bytes()),
                (format!("d/{name}"), data),
            ]
            .into());
            let found: Vec<String> = resolve(&fs, "d/a.design")
                .unwrap_err()
                .iter()
                .map(|p| p.to_string())
                .collect();
            assert_eq!(found.len(), 1, "{found:?}");
            assert!(found[0].starts_with(expected), "{found:?}");
        }
        // The whole file decodes: its pixels go with the scene.
        let fs = Mem([
            (
                "a.design".to_string(),
                br#"<Frame><Image src="./s.jpg" /></Frame>"#.to_vec(),
            ),
            ("s.jpg".to_string(), shirt),
        ]
        .into());
        let scene = resolve(&fs, "a.design").unwrap();
        let image = scene.root.children[0].image.as_ref().unwrap();
        let file = &scene.images[&image.id];
        assert_eq!((file.width, file.height), (160, 160));
        assert_eq!((file.pixels_width, file.pixels_height), (160, 160));
    }

    /// A file larger than [`MAX_IMAGE_SIDE`] is drawn from its pixels
    /// resampled to fit it, keeping its aspect; an `Image` still hugs the
    /// file's own size.
    #[test]
    fn a_large_image_file_is_resampled_once_to_fit() {
        let mut data = Vec::new();
        let mut e = png::Encoder::new(&mut data, 9000, 10);
        e.set_color(png::ColorType::Rgba);
        let mut w = e.write_header().unwrap();
        // Red to x = 4500, blue past it.
        let row: Vec<u8> = (0..9000)
            .flat_map(|x| {
                if x <= 4500 {
                    [255, 0, 0, 255]
                } else {
                    [0, 0, 255, 255]
                }
            })
            .collect();
        w.write_image_data(&row.repeat(10)).unwrap();
        drop(w);
        let file = ImageFile::new(data).unwrap();
        assert_eq!((file.width, file.height), (9000, 10));
        assert_eq!((file.pixels_width, file.pixels_height), (4096, 5));
        let px = |x: usize| &file.pixels[4 * x..][..4];
        assert_eq!(px(0), [255, 0, 0, 255]);
        assert_eq!(px(4095), [0, 0, 255, 255]);
        // Column 2048 covers x = 4500 to 4502.2: one part red, 1.2 blue.
        assert_eq!(px(2048), [116, 0, 139, 255]);
        // A fitting file is drawn from its own pixels.
        let (same, w, h) = fit(&[1, 2, 3, 4], 1, 1, MAX_IMAGE_SIDE);
        assert_eq!((same, w, h), (vec![1, 2, 3, 4], 1, 1));
        // A transparent pixel lends no color to its neighbour.
        let (mixed, _, _) = fit(&[255, 255, 255, 0, 0, 0, 255, 255], 2, 1, 1);
        assert_eq!(mixed, [0, 0, 255, 128]);
    }

    #[test]
    fn an_interaction_is_relative_to_the_file_that_wrote_it() {
        let fs = files(&[
            (
                "app/a.design",
                "import B from \"../lib/b.design\"\n<Frame><B /><B onClick=\"overlay ./c.design\" /></Frame>",
            ),
            ("app/c.design", "<Frame />"),
            (
                "lib/b.design",
                "<Frame onClick=\"navigate ./next.design\" />",
            ),
            ("lib/next.design", "<Frame />"),
        ]);
        let root = resolve(&fs, "app/a.design").unwrap().root;
        assert_eq!(
            root.children[0].on_click.as_deref(),
            Some("navigate lib/next.design")
        );
        assert_eq!(
            root.children[1].on_click.as_deref(),
            Some("overlay app/c.design")
        );
    }

    #[test]
    fn an_interaction_to_nowhere_is_a_problem() {
        for (click, expected) in [
            (
                "navigate ./nope.design",
                "d/a.design:1:8: onClick: navigate ./nope.design — no such file",
            ),
            (
                "overlay ../../x.design",
                "d/a.design:1:8: onClick: overlay ../../x.design — outside the served folder",
            ),
        ] {
            assert_eq!(
                problems(&format!("<Frame onClick=\"{click}\" />")),
                vec![expected.to_string()],
                "{click}"
            );
        }
    }

    #[test]
    fn a_valid_design_has_no_problems() {
        assert_eq!(
            problems(
                r##"import B from "./b.design"
<Frame fill="linear-gradient(90deg, #ffffff 0%, #000000ff 100%)">
  <B label="Go" x={4} y={5} width={80} height="hug" name="Go" onClick="back" />
  <Vector d="M0 0L24 24" viewBox="0 0 24 24" stroke="#000" />
  <Frame radius={8} clip><Image src="./photo.png" radius={[1, 2, 3, 4]} /></Frame>
</Frame>"##
            ),
            Vec::<String>::new()
        );
    }

    #[test]
    fn attributes_take_their_defaults() {
        let fs = files(&[("a.design", "<Frame><Text>a</Text><Rect /></Frame>")]);
        let root = resolve(&fs, "a.design").unwrap().root;
        assert_eq!((root.width, root.height), (Size::Hug, Size::Hug));
        assert_eq!(
            (root.layout, root.gap, root.padding),
            (Layout::None, 0.0, [0.0; 4])
        );
        assert_eq!((root.align, root.justify), (Align::Start, Align::Start));
        assert_eq!(
            (root.opacity, root.fill.clone(), root.clip),
            (1.0, None, false)
        );
        let text = root.children[0].text.clone().unwrap();
        assert_eq!(
            text,
            TextStyle {
                content: "a".into(),
                ..default_text()
            }
        );
        assert_eq!(
            (text.size, text.weight, text.line_height, text.align),
            (14.0, 400, 1.4, TextAlign::Left)
        );
        assert_eq!(root.children[1].stroke_width, 1.0);
        assert_eq!(root.children[1].radius, [0.0; 4]);
    }

    #[test]
    fn values_parse_into_their_types() {
        let fs = Mem(
            [
                (
                    "a.design".to_string(),
                    br##"<Frame padding={[1, 2]} radius={[1, 2, 3, 4]} fill="linear-gradient(135deg, #f00 0%, #0000ff80 100%)">
  <Frame padding={[1, 2, 3, 4]} fill="#abcd" />
  <Vector d="M2 4L10 20" />
  <Image src="./p.png" />
</Frame>"##
                        .to_vec(),
                ),
                ("p.png".to_string(), png()),
            ]
            .into(),
        );
        let scene = resolve(&fs, "a.design").unwrap();
        let root = &scene.root;
        assert_eq!(root.padding, [1.0, 2.0, 1.0, 2.0]);
        assert_eq!(root.radius, [1.0, 2.0, 3.0, 4.0]);
        let c = |r, g, b, a| Color::fixed(Rgba { r, g, b, a });
        assert_eq!(
            root.fill,
            Some(Fill::Linear {
                angle: 135.0,
                stops: vec![(c(255, 0, 0, 255), 0.0), (c(0, 0, 255, 0x80), 1.0)]
            })
        );
        assert_eq!(root.children[0].padding, [1.0, 2.0, 3.0, 4.0]);
        assert_eq!(
            root.children[0].fill,
            Some(Fill::Solid(c(0xaa, 0xbb, 0xcc, 0xdd)))
        );
        // A vector with no view box is drawn from its path's own bounds.
        assert_eq!(
            root.children[1].vector.as_ref().unwrap().view_box,
            [2.0, 4.0, 8.0, 16.0]
        );
        assert_eq!(root.children[2].image.as_ref().unwrap().src, "p.png");
        assert_eq!(scene.files, vec!["a.design", "p.png"]);
    }

    #[test]
    fn paths_stay_in_the_served_folder() {
        assert_eq!(
            join("a/b.design", "./c.design").as_deref(),
            Some("a/c.design")
        );
        assert_eq!(
            join("a/b.design", "../c.design").as_deref(),
            Some("c.design")
        );
        assert_eq!(join("a/b.design", "../../c.design"), None);
        assert_eq!(
            join("/a/b.design", "x/../y.png").as_deref(),
            Some("a/y.png")
        );
    }

    #[test]
    fn an_interaction_leads_only_to_a_design() {
        for (click, expected) in [
            (
                "navigate ./notes.txt",
                "d/a.design:1:8: onClick: navigate ./notes.txt — a design is a .design file",
            ),
            (
                "overlay ./photo.png",
                "d/a.design:1:8: onClick: overlay ./photo.png — a design is a .design file",
            ),
        ] {
            assert_eq!(
                problems(&format!("<Frame onClick=\"{click}\" />")),
                vec![expected.to_string()],
                "{click}"
            );
        }
        assert!(problems(r#"<Frame onClick="navigate ./b.design" />"#).is_empty());
    }

    #[test]
    fn sizes_and_spacing_are_never_negative() {
        for (attr, element) in [
            ("gap={-4}", "Frame"),
            ("padding={-1}", "Frame"),
            ("padding={[4, -2]}", "Frame"),
            ("radius={-3}", "Rect"),
            ("radius={[1, 2, -3, 4]}", "Rect"),
            ("strokeWidth={-1}", "Rect"),
            ("size={-12}", "Text"),
            ("lineHeight={-1}", "Text"),
        ] {
            let found = problems(&format!("<Frame><{element} {attr} /></Frame>"));
            assert_eq!(found.len(), 1, "{attr}: {found:?}");
            assert!(found[0].contains("of 0 or more"), "{attr}: {found:?}");
        }
    }

    #[test]
    fn an_import_name_is_unique_and_not_an_element() {
        let found = problems(
            r#"import B from "./b.design"
import B from "./b.design"
<Frame />"#,
        );
        assert_eq!(found, ["d/a.design:2:1: import B — B is already imported"]);
        let found = problems(
            r#"import Frame from "./b.design"
<Frame />"#,
        );
        assert_eq!(
            found,
            ["d/a.design:1:1: import Frame — Frame is a built-in element"]
        );
    }

    #[test]
    fn justify_names_all_it_takes() {
        assert_eq!(
            problems(r#"<Frame justify="middle" />"#),
            [
                "d/a.design:1:8: justify: expected \"start\", \"center\", \"end\" or \"space-between\""
            ]
        );
        assert_eq!(
            problems(r#"<Frame align="middle" />"#),
            ["d/a.design:1:8: align: expected \"start\", \"center\" or \"end\""]
        );
    }

    #[test]
    fn values_that_would_be_ignored_are_problems() {
        // x and y place a child only in a frame with no layout.
        let found =
            problems(r#"<Frame layout="row"><Rect width={10} height={10} x={5} /></Frame>"#);
        assert!(
            found
                .iter()
                .any(|p| p.contains("x: places a child only in a frame with layout=\"none\"")),
            "{found:?}"
        );
        // The same on an instance placed in a row.
        let found = problems(
            r#"import B from "./b.design"
<Frame layout="row"><B y={3} /></Frame>"#,
        );
        assert!(
            found.iter().any(|p| p.contains("y: places a child only")),
            "{found:?}"
        );
        // Negative sizes.
        let found = problems(r#"<Frame width={-1} height={-2} />"#);
        assert_eq!(found.len(), 2, "{found:?}");
        assert!(
            found[0].contains("width: expected pixels of 0 or more"),
            "{found:?}"
        );
        // An attribute given twice.
        let found = problems(r##"<Frame fill="#ff0000" fill="#00ff00" />"##);
        assert!(
            found.iter().any(|p| p.contains("fill is given twice")),
            "{found:?}"
        );
        let found = problems(
            r#"import B from "./b.design"
<Frame><B label="a" label="b" /></Frame>"#,
        );
        assert!(
            found.iter().any(|p| p.contains("label is given twice")),
            "{found:?}"
        );
        // An import of something that isn't a design says so.
        let found = problems(
            r#"import P from "./photo.png"
<Frame />"#,
        );
        assert_eq!(
            found,
            ["d/a.design:1:1: import ./photo.png — a design is a .design file"]
        );
        // x and y in a frame with no layout are fine.
        assert!(problems(r#"<Frame><Rect width={1} height={1} x={5} y={5} /></Frame>"#).is_empty());
    }

    const THEMES: &str = r##"kind: themes
light:
  surface: "#ffffff"
  text: "#000"
dark:
  surface: "#0f172a"
  text: "#f1f5f9"
"##;

    fn rgb(r: u8, g: u8, b: u8) -> Rgba {
        Rgba { r, g, b, a: 255 }
    }

    #[test]
    fn a_theme_color_has_a_value_in_each_theme() {
        let fs = files(&[
            ("themes.yml", THEMES),
            (
                "a.design",
                r##"<Frame fill={theme.surface} stroke="#ff0000"
       shadow={{ y: 2, color: theme.text }}>
  <Text color={theme.text}>Hi</Text>
  <Rect width={1} height={1} fill="linear-gradient(90deg, theme.surface 0%, #ff0000 100%)" />
</Frame>"##,
            ),
        ]);
        let scene = resolve(&fs, "a.design").unwrap();
        assert!(scene.themed);
        let surface = Color {
            light: rgb(255, 255, 255),
            dark: rgb(0x0f, 0x17, 0x2a),
        };
        let text = Color {
            light: rgb(0, 0, 0),
            dark: rgb(0xf1, 0xf5, 0xf9),
        };
        let root = &scene.root;
        assert_eq!(root.fill, Some(Fill::Solid(surface)));
        // A # color is the same in both.
        assert_eq!(root.stroke, Some(Color::fixed(rgb(255, 0, 0))));
        assert_eq!(root.shadow.as_ref().unwrap().color, text);
        assert_eq!(root.children[0].text.as_ref().unwrap().color, text);
        assert_eq!(
            root.children[1].fill,
            Some(Fill::Linear {
                angle: 90.0,
                stops: vec![(surface, 0.0), (Color::fixed(rgb(255, 0, 0)), 1.0)]
            })
        );
        assert_eq!(scene.files, vec!["a.design", "themes.yml"]);
        // A design with no theme color isn't themed, and reads no themes.
        let plain = resolve(
            &files(&[("themes.yml", THEMES), ("b.design", "<Frame />")]),
            "b.design",
        )
        .unwrap();
        assert!(!plain.themed);
        assert_eq!(plain.files, vec!["b.design"]);
    }

    /// Files that record every path asked for.
    struct Asked(HashMap<String, String>, std::cell::RefCell<Vec<String>>);

    impl Files for Asked {
        fn bytes(&self, path: &str) -> Option<Vec<u8>> {
            self.1.borrow_mut().push(path.to_string());
            self.0.bytes(path)
        }
        fn list(&self, path: &str) -> Option<Vec<String>> {
            self.0.list(path)
        }
    }

    #[test]
    fn the_nearest_themes_override_those_above_name_by_name() {
        let fs = Asked(
            files(&[
                ("themes.yml", THEMES),
                (
                    "app/themes.yml",
                    "kind: themes\nlight:\n  text: \"#111111\"\ndark: {}\n",
                ),
                // Another tool's file: passed over.
                ("app/screens/themes.yml", "kind: tokens\nlight: 1\n"),
                (
                    "app/screens/a.design",
                    "<Frame fill={theme.surface}><Text color={theme.text}>Hi</Text></Frame>",
                ),
            ]),
            Default::default(),
        );
        let scene = resolve(&fs, "app/screens/a.design").unwrap();
        assert_eq!(
            scene.root.fill,
            Some(Fill::Solid(Color {
                light: rgb(255, 255, 255),
                dark: rgb(0x0f, 0x17, 0x2a)
            }))
        );
        // Light's text from app/, dark's from the top.
        assert_eq!(
            scene.root.children[0].text.as_ref().unwrap().color,
            Color {
                light: rgb(0x11, 0x11, 0x11),
                dark: rgb(0xf1, 0xf5, 0xf9)
            }
        );
        // Every candidate is asked for once, the missing and the passed-over
        // ones too, so writing any of them counts as a change.
        let mut asked = fs.1.borrow().clone();
        asked.retain(|p| p.ends_with("themes.yml"));
        assert_eq!(
            asked,
            vec!["app/screens/themes.yml", "app/themes.yml", "themes.yml"]
                .into_iter()
                .rev()
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn a_theme_color_belongs_to_the_file_that_wrote_it() {
        let dark_red =
            "kind: themes\nlight:\n  accent: \"#ff0000\"\ndark:\n  accent: \"#880000\"\n";
        let blue = "kind: themes\nlight:\n  accent: \"#0000ff\"\ndark:\n  accent: \"#000088\"\n";
        let fs = files(&[
            ("kit/themes.yml", dark_red),
            (
                "kit/button.design",
                "<Frame props={{ fill: theme.accent }} fill={fill} />",
            ),
            ("app/themes.yml", blue),
            (
                "app/screen.design",
                "import Button from \"../kit/button.design\"\n<Frame layout=\"row\">\n  <Button />\n  <Button fill={theme.accent} />\n</Frame>",
            ),
        ]);
        let scene = resolve(&fs, "app/screen.design").unwrap();
        let fill = |n: usize| scene.root.children[n].fill.clone();
        // The default is the kit's red; the color the screen passes, its blue.
        assert_eq!(
            fill(0),
            Some(Fill::Solid(Color {
                light: rgb(255, 0, 0),
                dark: rgb(0x88, 0, 0)
            }))
        );
        assert_eq!(
            fill(1),
            Some(Fill::Solid(Color {
                light: rgb(0, 0, 255),
                dark: rgb(0, 0, 0x88)
            }))
        );
        assert!(scene.themed);
    }

    #[test]
    fn a_theme_color_that_isnt_there_is_a_problem_at_the_reference() {
        let one_sided = "kind: themes\nlight:\n  surface: \"#fff\"\n  edge: \"#000\"\ndark:\n  surface: \"#000\"\n";
        let design = r##"<Frame fill={theme.srface}>
  <Rect width={1} height={1} fill={theme.edge} />
  <Rect width={1} height={1} fill="linear-gradient(90deg, #000 0%, theme.nope 100%)" />
  <Text>{theme.surface}</Text>
</Frame>"##;
        let fs = files(&[("themes.yml", one_sided), ("a.design", design)]);
        assert_eq!(
            problems_in(&fs, "a.design"),
            vec![
                "a.design:1:14: theme.srface: the themes have no srface; they have edge, surface",
                "a.design:2:36: theme.edge: only the light theme has edge; a name needs a color in both",
                "a.design:3:68: theme.nope: the themes have no nope; they have edge, surface",
                "a.design:4:10: theme.surface is a color, not text: give it to color={theme.surface}",
            ]
        );
        // With no themes file above the design at all.
        let fs = files(&[("a/a.design", "<Frame fill={theme.surface} />")]);
        assert_eq!(
            problems_in(&fs, "a/a.design"),
            vec![
                "a/a.design:1:14: theme.surface: no themes.yml with kind: themes in this design's folder or above it"
            ]
        );
    }

    #[test]
    fn a_malformed_themes_file_is_a_problem_at_its_line() {
        let broken = r##"kind: themes
# the light one
light:
  surface: "#ffff"
  text: "#gg0000"
  edge: #000
  9lives: "#000"
dark: "#000"
colour: red
"##;
        let fs = files(&[
            ("themes.yml", broken),
            ("a.design", "<Frame fill={theme.surface} />"),
        ]);
        assert_eq!(
            problems_in(&fs, "a.design"),
            vec![
                "themes.yml:5:3: light.text: #gg0000 is not a color",
                "themes.yml:6:3: light.edge: no color: write it in quotes, \"#rrggbb\", as YAML reads # as a comment",
                "themes.yml:7:3: light.9lives: a name holds letters, digits, _ and -, and starts with a letter",
                "themes.yml:8:1: dark: expected a map of names to colors, like surface: \"#ffffff\"",
                "themes.yml:9:1: colour: a themes file has kind, fonts, light and dark only",
                "a.design:1:14: theme.surface: only the light theme has surface; a name needs a color in both",
            ]
        );
        let fs = files(&[
            ("themes.yml", "kind: themes\nlight: {}\n"),
            ("a.design", "<Frame fill={theme.surface} />"),
        ]);
        assert_eq!(
            problems_in(&fs, "a.design")[0],
            "themes.yml:1:1: a themes file has a light and a dark theme; this one has no dark"
        );
        let fs = files(&[
            ("themes.yml", "kind: themes\nlight: [\n"),
            ("a.design", "<Frame fill={theme.surface} />"),
        ]);
        assert!(
            problems_in(&fs, "a.design")[0]
                .starts_with("themes.yml:3:1: this themes file isn't valid YAML: "),
            "{:?}",
            problems_in(&fs, "a.design")
        );
        // A file that doesn't say it is a themes file is someone else's.
        let fs = files(&[("themes.yml", "light: [\n"), ("a.design", "<Frame />")]);
        assert!(resolve(&fs, "a.design").is_ok());
    }

    #[test]
    fn theme_is_no_props_or_imports_name() {
        let fs = files(&[
            ("themes.yml", THEMES),
            ("b.design", "<Frame />"),
            (
                "a.design",
                "import theme from \"./b.design\"\n<Frame props={{ theme: \"#fff\" }} fill={theme} />",
            ),
        ]);
        assert_eq!(
            problems_in(&fs, "a.design"),
            vec![
                "a.design:1:1: import theme — theme is the name of the design's themes",
                "a.design:2:8: props: theme is the name of the design's themes, not a prop",
                "a.design:2:34: fill: no prop \"theme\"",
            ]
        );
        // In quotes it is a string, not a color.
        let fs = files(&[
            ("themes.yml", THEMES),
            ("a.design", "<Frame fill=\"theme.surface\" />"),
        ]);
        assert_eq!(
            problems_in(&fs, "a.design"),
            vec![
                "a.design:1:8: fill: theme.surface is a theme color: write it in braces, {theme.surface}, not in quotes"
            ]
        );
    }

    fn figtree() -> Vec<u8> {
        std::fs::read(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../docs/designs/checkout/fonts/Figtree/Figtree-Variable.ttf"
        ))
        .unwrap()
    }

    fn inter(face: &str) -> Vec<u8> {
        std::fs::read(format!(
            "{}/fonts/Inter-{face}.ttf",
            env!("CARGO_MANIFEST_DIR")
        ))
        .unwrap()
    }

    fn mem(list: &[(&str, Vec<u8>)]) -> Mem {
        Mem(list
            .iter()
            .map(|(p, b)| (p.to_string(), b.clone()))
            .collect())
    }

    fn fonts_of(node: &Node, out: &mut Vec<Option<FontId>>) {
        if let Some(t) = &node.text {
            out.push(t.font);
        }
        for c in &node.children {
            fonts_of(c, out);
        }
    }

    /// A themes file naming `fonts`.
    fn named(fonts: &str) -> Vec<u8> {
        format!("kind: themes\nfonts:\n{fonts}light: {{}}\ndark: {{}}\n").into_bytes()
    }

    /// A text is set in the font its `font` names, through the themes of
    /// the file it is written in — a lower `themes.yml` adding and
    /// overriding names, inheriting the rest — or in Inter when it names
    /// none; one design mixes families, and a folder's licence is passed
    /// over.
    #[test]
    fn a_text_is_set_in_the_font_it_names_or_inter() {
        let fig = FontId::of(&figtree());
        let bold = FontId::of(&inter("Bold"));
        let fs = mem(&[
            (
                "themes.yml",
                named("  figtree: ./fonts/Figtree\n  heading: ./fonts/Figtree\n"),
            ),
            ("fonts/Figtree/Figtree-Variable.ttf", figtree()),
            ("fonts/Figtree/OFL.txt", b"licence".to_vec()),
            ("fonts/Inter/Inter-Bold.ttf", inter("Bold")),
            ("fonts/Inter/Inter-Regular.ttf", inter("Regular")),
            ("app/themes.yml", named("  heading: ../fonts/Inter\n")),
            (
                "app/a.design",
                br#"<Frame><Text font="figtree">a</Text><Text font="heading" weight={700}>b</Text><Text>c</Text></Frame>"#
                    .to_vec(),
            ),
        ]);
        let scene = resolve(&fs, "app/a.design").unwrap();
        let mut found = Vec::new();
        fonts_of(&scene.root, &mut found);
        assert_eq!(found, vec![Some(fig), Some(bold), None]);
        assert_eq!(scene.fonts.len(), 2);
        assert!(!scene.themed, "a font is no theme color");
        let plain = files(&[("a.design", "<Frame><Text>a</Text></Frame>")]);
        assert!(resolve(&plain, "a.design").unwrap().fonts.is_empty());
    }

    /// Weight picks the face: the static file of that weight, or the
    /// variable font set to it — and a scene carries only the faces its
    /// texts use, each once.
    #[test]
    fn weight_picks_the_face_and_a_scene_carries_only_those_used() {
        let fs = mem(&[
            ("themes.yml", named("  inter: ./f\n  fig: ./v.ttf\n")),
            ("f/Inter-Regular.ttf", inter("Regular")),
            ("f/Inter-Medium.ttf", inter("Medium")),
            ("f/Inter-SemiBold.ttf", inter("SemiBold")),
            ("f/Inter-Bold.ttf", inter("Bold")),
            ("v.ttf", figtree()),
            (
                "a.design",
                br#"<Frame><Text font="inter" weight={600}>a</Text><Text font="inter" weight={600}>b</Text><Text font="inter">c</Text><Text font="fig" weight={800}>d</Text><Text font="fig" weight={300}>e</Text></Frame>"#
                    .to_vec(),
            ),
        ]);
        let scene = resolve(&fs, "a.design").unwrap();
        let mut found = Vec::new();
        fonts_of(&scene.root, &mut found);
        let (semi, regular, fig) = (
            FontId::of(&inter("SemiBold")),
            FontId::of(&inter("Regular")),
            FontId::of(&figtree()),
        );
        assert_eq!(
            found,
            vec![Some(semi), Some(semi), Some(regular), Some(fig), Some(fig)]
        );
        assert_eq!(scene.fonts.len(), 3, "medium and bold aren't used");
    }

    fn font_problems(list: &[(&str, Vec<u8>)], path: &str) -> Vec<String> {
        match resolve(&mem(list), path) {
            Ok(_) => Vec::new(),
            Err(p) => p.iter().map(|p| p.to_string()).collect(),
        }
    }

    /// A weight the font lacks is a problem at the `weight`, or at the
    /// `Text` when it leaves the weight at 400, listing those it has.
    #[test]
    fn a_weight_the_font_lacks_is_a_problem_listing_those_it_has() {
        let design = |text: &str| {
            vec![
                ("themes.yml", named("  fig: ./v.ttf\n  bold: ./b\n")),
                ("v.ttf", figtree()),
                ("b/Inter-Bold.ttf", inter("Bold")),
                ("a.design", format!("<Frame>{text}</Frame>").into_bytes()),
            ]
        };
        for (text, expected) in [
            (
                r#"<Text weight={300}>a</Text>"#,
                "a.design:1:14: weight: Inter has no 300; it has 400, 500, 600 and 700",
            ),
            (
                r#"<Text font="fig" weight={200}>a</Text>"#,
                "a.design:1:25: weight: Figtree has no 200; it has 300, 400, 500, 600, 700, 800 and 900",
            ),
            (
                r#"<Text font="bold">a</Text>"#,
                "a.design:1:8: weight: Inter has no 400; it has 700",
            ),
        ] {
            assert_eq!(
                font_problems(&design(text), "a.design"),
                vec![expected],
                "{text}"
            );
        }
    }

    /// A name the themes don't give is a problem at the `font`, listing the
    /// names they do; a font that can't be used is one at its entry in the
    /// `themes.yml`, once however many texts use it.
    #[test]
    fn a_font_that_cant_be_used_is_a_problem_at_its_entry() {
        assert_eq!(
            font_problems(
                &[
                    ("themes.yml", named("  fig: ./v.ttf\n  body: ./v.ttf\n")),
                    ("v.ttf", figtree()),
                    (
                        "a.design",
                        br#"<Frame><Text font="figg">a</Text></Frame>"#.to_vec()
                    ),
                ],
                "a.design"
            ),
            vec!["a.design:1:14: font: no font named figg; the themes name body, fig"]
        );
        assert_eq!(
            font_problems(
                &[(
                    "a.design",
                    br#"<Frame><Text font="fig">a</Text></Frame>"#.to_vec()
                )],
                "a.design"
            ),
            vec![
                "a.design:1:14: font: no font named fig; no themes.yml in this design's folder or above it names fonts"
            ]
        );
        assert_eq!(
            font_problems(
                &[(
                    "a.design",
                    br#"<Frame><Text font={3}>a</Text></Frame>"#.to_vec()
                )],
                "a.design"
            ),
            vec![
                "a.design:1:14: font: expected the name of a font the themes name, like \"figtree\""
            ]
        );
        let mut big = vec![0, 1, 0, 0];
        big.resize(fonts::MAX_FONT_BYTES + 1, 0);
        let mut copy = inter("Regular");
        copy.push(0);
        let list = vec![
            ("d/v.ttf", figtree()),
            ("d/notes.txt", b"hi".to_vec()),
            ("d/web.woff2", b"wOF2rest".to_vec()),
            ("d/web.woff", b"wOFFrest".to_vec()),
            ("d/all.ttc", b"ttcfrest".to_vec()),
            ("d/big.ttf", big),
            ("d/broken.ttf", b"\0\x01\0\0broken".to_vec()),
            ("d/empty/OFL.txt", b"licence".to_vec()),
            ("d/mixed/Figtree.ttf", figtree()),
            ("d/mixed/Inter.ttf", inter("Regular")),
            ("d/twice/a.ttf", inter("Regular")),
            ("d/twice/b.ttf", copy),
            ("d/bad/a.ttf", b"nope".to_vec()),
        ];
        for (path, expected) in [
            ("./nope", "— no such file or folder"),
            ("../../up", "— outside the served folder"),
            (
                "./notes.txt",
                "is not a font: devpage reads .ttf and .otf files",
            ),
            (
                "./web.woff2",
                "is a WOFF2 file, which devpage doesn't read — decompress it to a .ttf or .otf",
            ),
            (
                "./web.woff",
                "is a WOFF file, which devpage doesn't read — decompress it to a .ttf or .otf",
            ),
            (
                "./all.ttc",
                "is a collection of fonts; name one font's own .ttf or .otf file",
            ),
            (
                "./big.ttf",
                "is 4.0 MB; a font file is at most 4 MB — subset it to the characters the design shows",
            ),
            (
                "./broken.ttf",
                "is a .ttf or .otf file that doesn't read as a font",
            ),
            ("./empty", "holds no .ttf or .otf file"),
            (
                "./mixed",
                "holds more than one family: Figtree (Figtree.ttf), Inter (Inter.ttf)",
            ),
            ("./twice", "holds two files of weight 400: a.ttf and b.ttf"),
            (
                "./bad",
                "holds a.ttf, which is not a font: devpage reads .ttf and .otf files",
            ),
        ] {
            let mut files = list.clone();
            files.push(("d/themes.yml", named(&format!("  x: {path}\n"))));
            files.push((
                "d/a.design",
                br#"<Frame><Text font="x">a</Text><Text font="x">b</Text></Frame>"#.to_vec(),
            ));
            assert_eq!(
                font_problems(&files, "d/a.design"),
                vec![format!("d/themes.yml:3:3: fonts.x: {path} {expected}")]
            );
        }
    }

    /// A themes file's `fonts` is a map of names — lowercase letters, digits
    /// and `-` — to paths; anything else is a problem at its line, and
    /// `font` is no key of a themes file.
    #[test]
    fn a_themes_files_fonts_are_names_to_paths() {
        let problems = font_problems(
            &[
                (
                    "themes.yml",
                    b"kind: themes\nfonts:\n  Figtree: ./v.ttf\n  my_font: ./v.ttf\n  ok: [1]\nfont: ./v.ttf\nlight: {}\ndark: {}\n"
                        .to_vec(),
                ),
                ("a.design", b"<Frame><Text>a</Text></Frame>".to_vec()),
            ],
            "a.design",
        );
        assert_eq!(
            problems,
            Vec::<String>::new(),
            "read only for a text that names a font"
        );
        let problems = font_problems(
            &[
                (
                    "themes.yml",
                    b"kind: themes\nfonts:\n  Figtree: ./v.ttf\n  my_font: ./v.ttf\n  ok: [1]\nfont: ./v.ttf\nlight: {}\ndark: {}\n"
                        .to_vec(),
                ),
                ("a.design", br#"<Frame><Text font="ok">a</Text></Frame>"#.to_vec()),
            ],
            "a.design",
        );
        assert_eq!(
            problems,
            vec![
                "themes.yml:3:3: fonts.Figtree: a font's name holds lowercase letters, digits and - only",
                "themes.yml:4:3: fonts.my_font: a font's name holds lowercase letters, digits and - only",
                "themes.yml:5:3: fonts.ok: expected a path to a font file or a folder of one family's, like ./fonts/Figtree",
                "themes.yml:6:1: font: a themes file has kind, fonts, light and dark only",
                "a.design:1:14: font: no font named ok; no themes.yml in this design's folder or above it names fonts",
            ]
        );
    }

    /// A value given as a prop — an image's `src`, a text's `font`, an
    /// interaction — is read where it was written: a path relative to that
    /// file, a font's name through its themes; its problem is there too.
    #[test]
    fn a_value_given_as_a_prop_is_read_where_it_was_written() {
        let list = |caller: &str| {
            vec![
                (
                    "app/a.design",
                    format!("import Card from \"../lib/card.design\"\n<Frame>{caller}</Frame>")
                        .into_bytes(),
                ),
                ("app/themes.yml", named("  mine: ./v.ttf\n")),
                ("app/me.png", png()),
                ("app/v.ttf", figtree()),
                ("app/next.design", b"<Frame />".to_vec()),
                ("lib/themes.yml", named("  own: ./own.ttf\n")),
                (
                    "lib/card.design",
                    br#"<Frame props={{ src: "./own.png", font: "own", go: "back" }} onClick={go}><Image src={src} /><Text font={font}>a</Text></Frame>"#
                        .to_vec(),
                ),
                ("lib/own.png", png()),
                ("lib/own.ttf", inter("Regular")),
            ]
        };
        let scene = resolve(
            &mem(&list(
                r#"<Card src="./me.png" font="mine" go="navigate ./next.design" />"#,
            )),
            "app/a.design",
        )
        .unwrap();
        let card = &scene.root.children[0];
        assert_eq!(card.children[0].image.as_ref().unwrap().src, "app/me.png");
        assert_eq!(
            card.children[1].text.as_ref().unwrap().font,
            Some(FontId::of(&figtree()))
        );
        assert_eq!(card.on_click.as_deref(), Some("navigate app/next.design"));
        // The defaults are the design's own file's.
        let scene = resolve(&mem(&list("<Card />")), "app/a.design").unwrap();
        let card = &scene.root.children[0];
        assert_eq!(card.children[0].image.as_ref().unwrap().src, "lib/own.png");
        assert_eq!(
            card.children[1].text.as_ref().unwrap().font,
            Some(FontId::of(&inter("Regular")))
        );
        // A bad value is a problem where it was written.
        assert_eq!(
            font_problems(
                &list(r#"<Card src="./no.png" font="own" go="overlay ./no.design" />"#),
                "app/a.design"
            ),
            vec![
                "app/a.design:2:43: onClick: overlay ./no.design — no such file",
                "app/a.design:2:18: src: ./no.png — no such file",
                "app/a.design:2:34: font: no font named own; the themes name mine",
            ]
        );
    }
}