gpui-base 0.6.0

Behavior, interaction, and infrastructure foundations for GPUI applications.
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
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
//! The dock area: the trees, the entity cache that mirrors them, and the
//! reconciliation that keeps the two in step.

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

use anyhow::Result;
use gpui::{
    AnyElement, AnyView, App, AppContext as _, Axis, Bounds, Context, Div, Empty, Entity,
    EventEmitter, FocusHandle, Focusable, InteractiveElement as _, IntoElement, ParentElement,
    Pixels, Point, Render, SharedString, Stateful, Styled as _, Subscription, WeakEntity, Window,
    div, prelude::FluentBuilder as _, px,
};

use crate::{
    ElementExt as _, Placement, ResizablePanelEvent, ResizableState, ResizeHandleContext,
    h_resizable, resizable::PANEL_MIN_SIZE, resizable_panel, v_resizable,
};

use super::{
    dock_placement::{Dock, DockSizing},
    drag::{AnyDrag, DropTarget},
    layout::{
        DockLayout, EditResult, InsertTarget, NodeId, NodeKind, PaneNode, PaneRef, PaneTree,
        PanelId, RootKind,
    },
    panel::{LivePanels, Panel, PanelEvent, PanelView},
    registry::{PanelBuildContext, PanelRegistry},
    state::{DockAreaState, DockPlacement, DockState, PanelInfo, PanelState, TileMeta},
    state_convert::{PanelBuilder, PanelSource as _},
    tab_group::{BareTabGroup, TabGroup, TabGroupConstraints, TabGroupEvent, TabGroupRenderer},
    tiles_state::{BareTiles, TilesEvent, TilesRenderer, TilesState},
};

/// What the dock area reports outward.
pub enum DockEvent {
    /// The layout changed. Subscribe to persist it; this fires on every edit,
    /// including each step of a tile drag, so a subscriber that writes to disk
    /// should debounce.
    LayoutChanged,
    /// A host-owned drag item was dropped inside the dock.
    DragDrop { item: AnyDrag, target: DropTarget },
}

/// What fills the whole area, when something does.
///
/// A zoom names a *container*, never the panel inside it. The old dock zoomed
/// the `TabPanel`: `TabPanel` is the only thing that ever emitted
/// `PanelEvent::ZoomIn` — `subscribe_panel` was handed `StackPanel`s too, but
/// those never zoom — so `set_zoomed_in` only ever received a whole tab panel,
/// and a zoomed panel kept its tab bar, its toolbar and its menu. That is
/// where the control that zooms back out lives. Naming the panel instead would
/// strip all of it and leave the user with no way back.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Zoomed {
    /// A tab group, rendered whole through its own [`TabGroupRenderer`].
    Group(NodeId),
    /// One tile of a canvas, rendered by that canvas through its own
    /// [`TilesRenderer`]. The canvas is what draws a tile's chrome, so the
    /// canvas is what is rendered.
    Tile { node: NodeId, panel: PanelId },
}

/// What a caller asked for when adding a panel, which is also which entry
/// point it came through.
#[derive(Clone, Copy)]
enum Added {
    /// Wherever the region's own shape puts it. The size seeds a dock that
    /// does not exist yet, and the slot of a group that has to be made.
    Anywhere(Option<Pixels>),
    /// A tile at these bounds, or nowhere: the bounds name a place only a
    /// canvas has, so a region without one is left alone rather than growing a
    /// tab group the caller never asked for.
    AsTile(Bounds<Pixels>),
}

impl Added {
    fn dock_size(self) -> Option<Pixels> {
        match self {
            Self::Anywhere(size) => size,
            Self::AsTile(_) => None,
        }
    }
}

/// One dock: its own layout tree plus the open/size/collapsible state.
struct DockRegion {
    tree: PaneTree,
    dock: Dock,
}

/// A cached container entity together with the subscription that carries its
/// intents back here. Kept as one value so dropping the cache entry drops the
/// subscription with it.
struct Cached<T> {
    entity: Entity<T>,
    _subscription: Subscription,
}

/// A split's cached `ResizableState`, plus the child order that state's panel
/// list currently mirrors.
///
/// The order is what makes a reconcile index-precise. `ResizableState` keeps
/// the authoritative size on `panels[ix]` and only ever consults the tree's
/// size as an initial value, so appending and truncating at the tail —
/// which is all `sync_panels_count` can do — leaves the survivors of a
/// non-tail removal wearing their predecessors' widths.
struct CachedSplit {
    entity: Entity<ResizableState>,
    children: Vec<NodeId>,
    /// The tree sizes the state last adopted. A reconcile that finds them
    /// unchanged leaves the state alone: re-adopting a `None` un-pins the
    /// measurement the layout pass resolved it to, and the split re-flexes
    /// although the edit never touched it.
    sizes: Vec<Option<Pixels>>,
    _subscription: Subscription,
}

/// The main area of the dock.
///
/// It owns one [`PaneTree`] per region and the entity cache that mirrors
/// them. Nothing else turns a tree edit into live entities.
pub struct DockArea {
    id: SharedString,
    version: Option<usize>,
    bounds: Bounds<Pixels>,
    this: WeakEntity<Self>,

    center: PaneTree,
    docks: HashMap<DockPlacement, DockRegion>,

    groups: HashMap<NodeId, Cached<TabGroup>>,
    splits: HashMap<NodeId, CachedSplit>,
    tiles: HashMap<NodeId, Cached<TilesState>>,
    panels: HashMap<PanelId, Arc<dyn PanelView>>,

    locked: bool,
    zoomed: Option<Zoomed>,
    focus_handle: FocusHandle,
    renderer: Rc<dyn DockAreaRenderer>,
}

impl DockArea {
    /// An empty area that draws nothing but its panels.
    ///
    /// `id` names the area for the host's own persistence; `version` is
    /// written into [`Self::dump`] and read back by [`Self::load`], for a host
    /// that wants to reject or migrate a layout an older build wrote.
    ///
    /// Install appearance with [`Self::with_renderer`].
    pub fn new(
        id: impl Into<SharedString>,
        version: Option<usize>,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Self {
        PanelRegistry::init(cx);

        Self {
            id: id.into(),
            version,
            bounds: Bounds::default(),
            this: cx.weak_entity(),
            center: PaneTree::new(RootKind::Split),
            docks: HashMap::new(),
            groups: HashMap::new(),
            splits: HashMap::new(),
            tiles: HashMap::new(),
            panels: HashMap::new(),
            locked: false,
            zoomed: None,
            focus_handle: cx.focus_handle(),
            renderer: Rc::new(BareDockArea),
        }
    }

    /// Install the appearance for this area and everything under it: the
    /// renderer also supplies the [`TabGroupRenderer`] and [`TilesRenderer`]
    /// every container it builds will use.
    pub fn with_renderer(mut self, renderer: Rc<dyn DockAreaRenderer>) -> Self {
        self.renderer = renderer;
        self
    }

    pub fn id(&self) -> SharedString {
        self.id.clone()
    }

    pub fn version(&self) -> Option<usize> {
        self.version
    }

    /// Change the schema version a later [`dump`](Self::dump) writes.
    ///
    /// Set at construction for an area whose layout never changes shape. A
    /// host that installs one of several preset layouts into the same area
    /// picks the version with the preset, which is after the area exists.
    pub fn set_version(&mut self, version: Option<usize>, cx: &mut Context<Self>) {
        self.version = version;
        cx.notify();
    }

    /// The area's own bounds, recorded each frame. Dock resizing measures
    /// against it.
    pub fn bounds(&self) -> Bounds<Pixels> {
        self.bounds
    }

    /// The tree for one region, or `None` for a dock that does not exist.
    ///
    /// The `Option` is in the signature rather than hidden behind a panic
    /// because a dock is genuinely optional — it is `Option<DockState>` in the
    /// persisted schema — and there is no borrowable empty tree to hand back
    /// for one that is absent.
    pub fn layout(&self, placement: DockPlacement) -> Option<&PaneTree> {
        match placement {
            DockPlacement::Center => Some(&self.center),
            _ => self.docks.get(&placement).map(|pane| &pane.tree),
        }
    }

    /// The live view for a panel, if the dock still holds it.
    pub fn panel(&self, panel: PanelId) -> Option<&Arc<dyn PanelView>> {
        self.panels.get(&panel)
    }

    pub fn is_locked(&self) -> bool {
        self.locked
    }

    /// Whether a region currently holds no visible panel.
    ///
    /// This is the question the old `DockItem::is_empty` answered, and it is
    /// the same one [`Self::is_node_visible`] answers per container: a region
    /// is empty when nothing in it would be drawn. A region that does not
    /// exist — a dock that was never installed — is empty too.
    pub fn is_empty(&self, placement: DockPlacement, cx: &App) -> bool {
        self.layout(placement)
            .is_none_or(|tree| !self.is_node_visible(tree.root(), cx))
    }

    /// Lock the layout against rearranging. Resizing stays available.
    pub fn set_locked(&mut self, locked: bool, window: &mut Window, cx: &mut Context<Self>) {
        if self.locked == locked {
            return;
        }
        self.locked = locked;
        // The lock is one of the facts every group is told, so it only takes
        // effect once the groups have been re-told.
        self.reconcile(window, cx);
    }
}

/// Installing layouts: the center region and the three docks.
impl DockArea {
    /// Replace the center region with a described layout. Whatever was there
    /// leaves the dock, so its panels are told [`Panel::on_removed`].
    pub fn set_center(&mut self, layout: DockLayout, window: &mut Window, cx: &mut Context<Self>) {
        let (tree, panels) = PaneTree::from_layout(layout, RootKind::Split);
        self.center = tree;
        self.panels.extend(panels);
        self.reconcile(window, cx);
        cx.emit(DockEvent::LayoutChanged);
    }

    /// Replace one dock with a described layout, creating the dock if the area
    /// does not have one there yet. A new dock keeps the size and open state of
    /// the one it replaces, so re-filling a dock does not resize it.
    ///
    /// [`DockPlacement::Center`] defers to [`Self::set_center`]: the center is
    /// not a dock and has no size or open state of its own.
    pub fn set_dock(
        &mut self,
        placement: DockPlacement,
        layout: DockLayout,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if placement == DockPlacement::Center {
            return self.set_center(layout, window, cx);
        }

        let (tree, panels) = PaneTree::from_layout(layout, RootKind::Any);
        let dock = self
            .docks
            .get(&placement)
            .map(|pane| pane.dock)
            .unwrap_or_else(|| Dock::new(PANEL_MIN_SIZE * 2.));
        self.docks.insert(placement, DockRegion { tree, dock });
        self.panels.extend(panels);
        self.reconcile(window, cx);
        cx.emit(DockEvent::LayoutChanged);
    }

    /// Take a dock away entirely, panels and all. Distinct from
    /// [`Self::toggle_dock`], which only takes it off screen.
    pub fn remove_dock(
        &mut self,
        placement: DockPlacement,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if self.docks.remove(&placement).is_none() {
            return;
        }
        // The dock's panels leave the dock entirely, so they are told, unlike
        // the panels of a dock that merely closed.
        self.reconcile(window, cx);
        cx.emit(DockEvent::LayoutChanged);
    }

    pub fn has_dock(&self, placement: DockPlacement) -> bool {
        self.docks.contains_key(&placement)
    }

    /// Whether a dock is on screen. A dock the area does not have is never
    /// open, so this answers the question a caller usually means without a
    /// preceding [`Self::has_dock`].
    pub fn is_dock_open(&self, placement: DockPlacement) -> bool {
        self.docks
            .get(&placement)
            .is_some_and(|pane| pane.dock.is_open())
    }

    /// Open a closed dock or close an open one. A dock that is not
    /// collapsible refuses to close; there is nothing to refuse when opening.
    pub fn toggle_dock(
        &mut self,
        placement: DockPlacement,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let Some(pane) = self.docks.get_mut(&placement) else {
            return;
        };
        if !pane.dock.is_collapsible() && pane.dock.is_open() {
            return;
        }
        let open = pane.dock.is_open();
        pane.dock.set_open(!open);
        // A closed dock takes its displayed panel off screen, which the
        // active-state contract counts as no panel being displayed — that is
        // what `TabGroupConstraints::collapsed` carries.
        self.reconcile(window, cx);
        cx.emit(DockEvent::LayoutChanged);
    }

    /// Whether a dock may be collapsed at all. A skin drawing a collapse
    /// affordance in a tab bar reads this to decide whether to offer one.
    pub fn is_dock_collapsible(&self, placement: DockPlacement) -> bool {
        self.docks
            .get(&placement)
            .is_some_and(|pane| pane.dock.is_collapsible())
    }

    pub fn set_dock_collapsible(
        &mut self,
        placement: DockPlacement,
        collapsible: bool,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if let Some(pane) = self.docks.get_mut(&placement) {
            pane.dock.set_collapsible(collapsible);
            cx.notify();
        }
    }

    /// The dock's size along its axis.
    pub fn dock_size(&self, placement: DockPlacement) -> Option<Pixels> {
        self.docks.get(&placement).map(|pane| pane.dock.size())
    }

    pub fn set_dock_size(
        &mut self,
        placement: DockPlacement,
        size: Pixels,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if let Some(pane) = self.docks.get_mut(&placement) {
            let previous = pane.dock.size();
            pane.dock.set_size(size);
            if pane.dock.size() == previous {
                return;
            }
            cx.notify();
            cx.emit(DockEvent::LayoutChanged);
        }
    }
}

/// Editing the layout.
impl DockArea {
    /// Add a panel to a region, merging it into the first tab group there,
    /// placing it on the region's tiles canvas if that is what the region is,
    /// or starting a group when the region is empty.
    pub fn add_panel<P: Panel>(
        &mut self,
        panel: Entity<P>,
        placement: DockPlacement,
        size: Option<Pixels>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let id = PanelId::from(panel.entity_id());
        self.add_panel_inner(
            id,
            Arc::new(panel),
            placement,
            Added::Anywhere(size),
            window,
            cx,
        );
    }

    /// Add an already-wrapped panel handle to a region.
    ///
    /// The companion to [`Self::add_panel`], for a layer that hands base its
    /// own concrete handle — see [`PanelView::as_any`] — rather than a bare
    /// entity. The id comes from [`PanelView::panel_id`], which is the only
    /// place it can come from once the entity is behind the handle.
    pub fn add_panel_view(
        &mut self,
        panel: Arc<dyn PanelView>,
        placement: DockPlacement,
        size: Option<Pixels>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let id = panel.panel_id(cx);
        self.add_panel_inner(id, panel, placement, Added::Anywhere(size), window, cx);
    }

    /// Add a panel to a region's tiles canvas at `bounds`.
    ///
    /// [`Self::add_panel`] places a tile too, but only where the canvas
    /// itself chooses; this is for a host that knows where the tile belongs —
    /// most of all one acting on [`DockEvent::DragDrop`] with a
    /// [`DropTarget::Canvas`], which reports *that* something was dropped on
    /// a canvas and leaves placing it to the host.
    ///
    /// A region with no tiles canvas has nowhere to put a tile, so nothing
    /// happens and the panel is not registered.
    pub fn add_tile<P: Panel>(
        &mut self,
        panel: Entity<P>,
        placement: DockPlacement,
        bounds: Bounds<Pixels>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let id = PanelId::from(panel.entity_id());
        self.add_panel_inner(
            id,
            Arc::new(panel),
            placement,
            Added::AsTile(bounds),
            window,
            cx,
        );
    }

    /// [`Self::add_tile`] for an already-wrapped handle, for the same reason
    /// [`Self::add_panel_view`] is the companion to [`Self::add_panel`].
    pub fn add_tile_view(
        &mut self,
        panel: Arc<dyn PanelView>,
        placement: DockPlacement,
        bounds: Bounds<Pixels>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let id = panel.panel_id(cx);
        self.add_panel_inner(id, panel, placement, Added::AsTile(bounds), window, cx);
    }

    fn add_panel_inner(
        &mut self,
        id: PanelId,
        panel: Arc<dyn PanelView>,
        placement: DockPlacement,
        added: Added,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        // The registration is written before the target is resolved, because
        // both want `&mut self`, so an add that finds nowhere to put the panel
        // has to undo it. *Undo*, not remove: adding a panel the dock already
        // holds is a legitimate call — a host re-placing one it owns — and
        // dropping its view would strand it in a tree with no entity, which is
        // what `reconcile`'s `views_of` asserts against. Restoring the previous
        // handle rather than keeping this one matters too: the two differ when
        // a panel registered through `add_panel_view` is then named by
        // `add_tile`, and keeping the bare entity would cost the panel its
        // title for a call that otherwise did nothing.
        let previous = self.panels.insert(id, panel);

        // A dock is created to hold the panel, but only for a caller that will
        // take whatever shape the region offers. A tile has to land on a
        // canvas, and a freshly made dock has none, so making one here would
        // leave an empty dock behind after the insert below declines.
        if matches!(added, Added::Anywhere(_))
            && placement != DockPlacement::Center
            && !self.docks.contains_key(&placement)
        {
            self.docks.insert(
                placement,
                DockRegion {
                    tree: PaneTree::new(RootKind::Any),
                    dock: Dock::new(added.dock_size().unwrap_or(PANEL_MIN_SIZE * 2.)),
                },
            );
        }

        let Some(tree) = self.tree_mut(placement) else {
            self.restore_registration(id, previous);
            return;
        };
        let target = match added {
            // An explicit tile: only a canvas can hold it. Falling back to a
            // tab group would put the panel somewhere the caller did not ask
            // for and silently discard the bounds.
            Added::AsTile(bounds) => match first_tiles_canvas(tree.root()) {
                Some(node) => InsertTarget::Tile { node, bounds },
                None => {
                    self.restore_registration(id, previous);
                    return;
                }
            },
            Added::Anywhere(size) => match first_tab_group(tree.root()) {
                Some(node) => InsertTarget::Tabs {
                    node,
                    ix: None,
                    activate: true,
                },
                // A region that is a tiles canvas takes a tile, at the
                // placement `TileMeta` defaults to — which is what the old
                // `DockItem::add_panel`'s `Tiles` arm did with no bounds in
                // hand. Splitting a canvas in two instead would wrap the whole
                // thing in a stack the user never asked for.
                None => match first_tiles_canvas(tree.root()) {
                    Some(node) => InsertTarget::Tile {
                        node,
                        bounds: TileMeta::default().bounds,
                    },
                    // An empty region has no container to merge into, so the
                    // panel makes one beside the root. `normalize` then removes
                    // the emptied root and, for a dock, collapses the wrapper
                    // away again.
                    None => InsertTarget::Split {
                        node: tree.root().id(),
                        placement: Placement::Right,
                        size,
                    },
                },
            },
        };
        let result = tree.insert_panel(id, target);
        if !result.changed() {
            // Nothing took the panel, so a newly registered one must not
            // linger in the view map and be told `on_removed` by the next
            // reconcile.
            self.restore_registration(id, previous);
            return;
        }
        self.commit(result, window, cx);
    }

    /// Put the view map back the way an add found it, for one that placed
    /// nothing. `previous` is what [`HashMap::insert`] handed back.
    fn restore_registration(&mut self, id: PanelId, previous: Option<Arc<dyn PanelView>>) {
        match previous {
            Some(view) => self.panels.insert(id, view),
            None => self.panels.remove(&id),
        };
    }

    /// Remove a panel from wherever it lives, telling it that it was removed.
    pub fn remove_panel<P: Panel>(
        &mut self,
        panel: Entity<P>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.remove_panel_id(PanelId::from(panel.entity_id()), window, cx);
    }

    /// Move a panel to a new home. The panel never leaves the dock, so it is
    /// never told it was removed.
    pub fn move_panel(
        &mut self,
        panel: PanelId,
        target: InsertTarget,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let Some(destination) = self.placement_of_node(target_node(&target)) else {
            return;
        };
        let source = self.placement_of_panel(panel);

        // A split target divides an existing slot, so the tree needs real
        // pixels to divide.
        if matches!(target, InsertTarget::Split { .. }) {
            self.adopt_measured_sizes(destination, cx);
        }

        // Read what the source group last told the panel *before* the edit,
        // so the destination can be seeded with it. Without this a panel
        // dragged between groups while displayed is told `true` twice.
        let was_active = self
            .layout(source.unwrap_or(destination))
            .and_then(|tree| tree.find_panel_node(panel))
            .and_then(|node| self.groups.get(&node))
            .and_then(|cached| cached.entity.read(cx).last_notified_active(panel));

        let changed = match source {
            Some(source) if source == destination => {
                let Some(tree) = self.tree_mut(destination) else {
                    return;
                };
                tree.move_panel(panel, target).changed()
            }
            source => {
                // Across trees a move is a detach plus an insert. The detach's
                // `removed_panels` is deliberately dropped on the floor: the
                // panel is still in the dock, so it must not hear `on_removed`.
                //
                // Both halves are committed on, not just the insert. A target
                // whose node kind does not match the insert is a silent no-op
                // in `apply_insert`, and committing on the insert alone would
                // early-return with the panel already gone from the source —
                // stranded in `self.panels`, belonging to no tree, for the
                // next reconcile to prune and destroy.
                let detached = source
                    .and_then(|source| self.tree_mut(source))
                    .is_some_and(|tree| tree.remove_panel(panel).changed());
                let Some(tree) = self.tree_mut(destination) else {
                    return;
                };
                let inserted = tree.insert_panel(panel, target).changed();
                detached || inserted
            }
        };

        self.commit_changed(changed, window, cx);

        if let Some(active) = was_active {
            if let Some(cached) = self
                .layout(destination)
                .and_then(|tree| tree.find_panel_node(panel))
                .and_then(|node| self.groups.get(&node))
            {
                let group = cached.entity.clone();
                group.update(cx, |group, _| group.seed_active(panel, active));
            }
        }
    }

    /// Put `panel` in a new tab group beside `node`.
    pub fn split_at(
        &mut self,
        node: NodeId,
        panel: PanelId,
        placement: Placement,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let Some(region) = self.placement_of_node(node) else {
            return;
        };
        self.adopt_measured_sizes(region, cx);
        let Some(tree) = self.tree_mut(region) else {
            return;
        };
        let result = tree.split(node, panel, placement, None);
        self.commit(result, window, cx);
    }

    fn remove_panel_id(&mut self, panel: PanelId, window: &mut Window, cx: &mut Context<Self>) {
        let Some(region) = self.placement_of_panel(panel) else {
            return;
        };
        let Some(tree) = self.tree_mut(region) else {
            return;
        };
        let result = tree.remove_panel(panel);
        self.commit(result, window, cx);
    }
}

/// Zooming.
///
/// There is no `set_zoomed_in(panel)` here. A zoom is a container's own act:
/// only the container knows whether its displayed panel is zoomable, and only
/// the container can tell that panel it was zoomed. So the way in is
/// [`TabGroupContext::toggle_zoom`](super::TabGroupContext::toggle_zoom) or
/// [`TileContext::toggle_zoom`](super::TileContext::toggle_zoom) — a skin has
/// one of those wherever it draws a zoom control — or
/// [`Self::set_zoomed_in`] by node, which delegates to the same place. The
/// area then installs the container that reported it.
impl DockArea {
    /// Zoom the tab group at `node` in, as if its own zoom control had been
    /// used.
    ///
    /// Nothing happens for a node that is not a live tab group, or when the
    /// group refuses — the group is the one that knows.
    pub fn set_zoomed_in(&mut self, node: NodeId, window: &mut Window, cx: &mut Context<Self>) {
        self.set_zoom(Some(Zoomed::Group(node)), window, cx);
    }

    /// Clear the zoom, putting the zoomed container's own flag back with it.
    ///
    /// A container toggles its zoom itself and only reports it, so an area
    /// that dropped the view without telling the container would leave it
    /// believing it still fills the dock — and a zoomed group refuses drops.
    pub fn set_zoomed_out(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.set_zoom(None, window, cx);
    }

    pub fn is_zoomed(&self) -> bool {
        self.zoomed.is_some()
    }

    /// The tab group filling the area, if a group is what is zoomed.
    pub fn zoomed_group(&self) -> Option<NodeId> {
        match self.zoomed {
            Some(Zoomed::Group(node)) => Some(node),
            _ => None,
        }
    }

    /// The tile filling the area, if a tile is what is zoomed.
    pub fn zoomed_tile(&self) -> Option<PanelId> {
        match self.zoomed {
            Some(Zoomed::Tile { panel, .. }) => Some(panel),
            _ => None,
        }
    }

    /// The one place `self.zoomed` is written.
    ///
    /// Every write drives the container's own flag through the same call, and
    /// the new target is recorded only if that container accepted it. So the
    /// area cannot show a container the container does not think is zoomed,
    /// and cannot leave a container flagged zoomed while showing something
    /// else — the split state a group would carry as a permanent lock.
    fn set_zoom(&mut self, zoomed: Option<Zoomed>, window: &mut Window, cx: &mut Context<Self>) {
        if self.zoomed == zoomed {
            return;
        }

        if let Some(previous) = self.zoomed {
            self.drive_zoom(previous, false, window, cx);
        }
        let accepted = match zoomed {
            Some(next) => self.drive_zoom(next, true, window, cx).then_some(next),
            None => None,
        };
        self.zoomed = accepted;
        cx.notify();
    }

    /// Ask one container to zoom in or out, and report whether it now agrees.
    ///
    /// A container that has already been left out of the cache — its node is
    /// gone from the tree — has nothing to say and nothing to put back, so it
    /// answers `false` and a zoom naming it is never installed.
    fn drive_zoom(
        &mut self,
        zoomed: Zoomed,
        zoom_in: bool,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> bool {
        match zoomed {
            Zoomed::Group(node) => {
                let Some(group) = self.groups.get(&node).map(|cached| cached.entity.clone()) else {
                    return false;
                };
                group.update(cx, |group, cx| {
                    group.set_zoomed(zoom_in, window, cx);
                    group.is_zoomed() == zoom_in
                })
            }
            Zoomed::Tile { node, panel } => {
                let Some(canvas) = self.tiles.get(&node).map(|cached| cached.entity.clone()) else {
                    return false;
                };
                canvas.update(cx, |canvas, cx| {
                    canvas.set_zoomed(zoom_in.then_some(panel), window, cx);
                    canvas.zoomed_tile() == zoom_in.then_some(panel)
                })
            }
        }
    }

    /// The container that fills the area when something is zoomed.
    ///
    /// The container, not the panel inside it: this is what keeps a zoomed
    /// group's tab bar and a zoomed tile's chrome on screen.
    fn zoomed_view(&self) -> Option<AnyView> {
        match self.zoomed? {
            Zoomed::Group(node) => Some(self.groups.get(&node)?.entity.clone().into()),
            Zoomed::Tile { node, .. } => Some(self.tiles.get(&node)?.entity.clone().into()),
        }
    }
}

/// Persistence.
impl DockArea {
    /// Read a persisted layout, rebuilding every panel through
    /// [`PanelRegistry`]. A panel this build does not know about becomes a
    /// placeholder that carries the original [`PanelState`] forward, so the
    /// next save does not erase it.
    pub fn load(
        &mut self,
        state: DockAreaState,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Result<()> {
        self.version = state.version;
        self.zoomed = None;
        // Nothing in the old layout survives a load, so the caches are
        // emptied rather than reconciled: every node id in the new trees is
        // freshly minted and would miss the old cache anyway.
        self.groups.clear();
        self.splits.clear();
        self.tiles.clear();
        self.docks.clear();
        // `self.panels` is deliberately *not* cleared: leaving the outgoing
        // panels in it lets `reconcile` prune them, which is what tells them
        // they were removed.

        let dock_area = self.this.clone();
        let renderer = self.renderer.clone();
        let mut built = Vec::new();
        self.center = {
            let mut builder = RegistryPanelBuilder {
                dock_area: dock_area.clone(),
                renderer: renderer.clone(),
                built: &mut built,
                window,
                cx,
            };
            PaneTree::from_state(&state.center, RootKind::Split, &mut builder)
        };

        for dock_state in [state.left_dock, state.right_dock, state.bottom_dock]
            .into_iter()
            .flatten()
        {
            let tree = {
                let mut builder = RegistryPanelBuilder {
                    dock_area: dock_area.clone(),
                    renderer: renderer.clone(),
                    built: &mut built,
                    window,
                    cx,
                };
                PaneTree::from_state(dock_state.panel(), RootKind::Any, &mut builder)
            };
            let mut dock = Dock::new(dock_state.size());
            dock.set_open(dock_state.open());
            self.docks
                .insert(dock_state.placement(), DockRegion { tree, dock });
        }

        self.panels.extend(built);
        self.reconcile(window, cx);
        cx.emit(DockEvent::LayoutChanged);
        Ok(())
    }

    /// Write the layout out.
    ///
    /// Slot sizes are resolved to concrete pixels first. The tree represents
    /// an unconstrained slot as `None` and the writer emits `0.0` for it,
    /// which *this* reader maps back to `None` — but an older build has no
    /// notion of the sentinel and would construct a real zero-pixel panel from
    /// it. Preference order is the split's measured size, then the tree's own
    /// size, then [`PANEL_MIN_SIZE`] for a slot nothing has ever measured.
    ///
    /// The measurement wins because the tree does not track every change to
    /// it. `ResizableState` only emits `Resized` from a finished drag, so that
    /// is all the subscription in [`Self::split_entity`] writes back;
    /// `adjust_to_container_size` rescales every slot silently on each window
    /// resize, insert and remove. Preferring the tree would persist load-time
    /// or last-drag pixels after a window resize, and worse, mix them: a slot
    /// left `None` by a later insert would be filled from the current
    /// measurement while its untouched siblings kept file-era numbers, so the
    /// written ratio would match neither the file nor the screen. Reading the
    /// measurement for every slot of a split writes one internally consistent
    /// set, which is what the old `StackPanel::dump` did.
    pub fn dump(&self, cx: &App) -> DockAreaState {
        let source = LivePanels::new(&self.panels, cx);

        DockAreaState {
            version: self.version,
            center: self.resolved_tree(&self.center, cx).to_state(&source),
            left_dock: self.dump_dock(DockPlacement::Left, &source, cx),
            right_dock: self.dump_dock(DockPlacement::Right, &source, cx),
            bottom_dock: self.dump_dock(DockPlacement::Bottom, &source, cx),
        }
    }

    fn dump_dock(
        &self,
        placement: DockPlacement,
        source: &LivePanels<'_>,
        cx: &App,
    ) -> Option<DockState> {
        let pane = self.docks.get(&placement)?;
        Some(DockState::new(
            self.resolved_tree(&pane.tree, cx).to_state(source),
            placement,
            pane.dock.size(),
            pane.dock.is_open(),
        ))
    }

    fn resolved_tree(&self, tree: &PaneTree, cx: &App) -> PaneTree {
        let mut tree = tree.clone();
        self.resolve_sizes(tree.root_mut(), cx);
        tree
    }

    fn resolve_sizes(&self, node: &mut PaneNode, cx: &App) {
        let measured = self
            .splits
            .get(&node.id())
            .map(|cached| cached.entity.read(cx).sizes().clone())
            .unwrap_or_default();

        let NodeKind::Split {
            children, sizes, ..
        } = node.kind_mut()
        else {
            return;
        };

        for (ix, size) in sizes.iter_mut().enumerate() {
            // A slot already holding zero is exactly as unsafe as an absent
            // one: it is the same byte in the file and the same zero-pixel
            // panel in an older build. So both the measurement and the stored
            // value have to clear zero before they can be written.
            let on_screen = measured.get(ix).copied().filter(|size| *size > px(0.));
            let stored = (*size).filter(|size| *size > px(0.));
            *size = Some(on_screen.or(stored).unwrap_or(PANEL_MIN_SIZE));
        }

        for child in children.iter_mut() {
            self.resolve_sizes(child, cx);
        }
    }
}

/// Reconciliation.
impl DockArea {
    /// Apply one edit: bring the entity cache back in line and say so.
    ///
    /// `on_removed` is not fired from `EditResult::removed_panels` here.
    /// [`Self::reconcile`] fires it instead, from the panels it prunes: that
    /// is the same set for a plain removal, and it also covers the panels a
    /// wholesale `set_center`, `set_dock`, `remove_dock` or `load` displaces,
    /// which no `EditResult` describes at all. It is also the safer default —
    /// a caller cannot forget a list it does not pass.
    fn commit(&mut self, result: EditResult, window: &mut Window, cx: &mut Context<Self>) {
        self.commit_changed(result.changed(), window, cx);
    }

    /// [`Self::commit`] for an edit that took more than one `EditResult`.
    fn commit_changed(&mut self, changed: bool, window: &mut Window, cx: &mut Context<Self>) {
        if !changed {
            return;
        }

        self.reconcile(window, cx);
        cx.emit(DockEvent::LayoutChanged);
    }

    /// Bring the entity cache in line with the trees.
    ///
    /// Because `NodeId` survives every edit and every normalization rule, a
    /// steady-state pass creates and drops nothing; only genuinely new or dead
    /// containers churn. That is what keeps a drag from resetting the state of
    /// panels it did not touch.
    fn reconcile(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        // Planned first, applied second: the plan borrows the trees, and
        // applying it needs `&mut self` to fill the caches.
        let mut plans = Vec::new();
        plan_tree(&self.center, false, self.locked, &mut plans);
        for pane in self.docks.values() {
            plan_tree(&pane.tree, !pane.dock.is_open(), self.locked, &mut plans);
        }

        // Sets rather than vectors: these are membership tests, run once per
        // cached entity and once per live panel, and a drag reaches this path
        // on every mouse move.
        let mut live_nodes = HashSet::with_capacity(plans.len());
        let mut live_panels: HashSet<PanelId> = HashSet::new();

        for plan in plans {
            live_nodes.insert(plan.node());
            match plan {
                ContainerPlan::Split {
                    node,
                    axis,
                    children,
                    sizes,
                } => {
                    let state = self.split_entity(node, cx);
                    let (previous, adopted) = self
                        .splits
                        .get(&node)
                        .map(|cached| (cached.children.clone(), cached.sizes.clone()))
                        .unwrap_or_default();
                    // Only a split the edit changed is handed anything. The
                    // state of every other split may legitimately disagree
                    // with its tree — a window resize rescales it silently —
                    // and pushing the tree's sizes back would move slots the
                    // edit never named. For a slot the tree leaves `None`, it
                    // would also un-pin the measurement the first layout pass
                    // resolved it to, and the whole split re-flexes.
                    if previous != children || adopted != sizes {
                        state.update(cx, |state, cx| {
                            sync_split_panels(state, &previous, &children, &sizes, cx);
                            state.sync_panels_count(axis, children.len(), cx);
                            // The tree is authoritative on how space divides,
                            // so its sizes land last — `insert_panel`
                            // renormalizes everything it touches, which would
                            // otherwise undo the share an edit just decided.
                            //
                            // What the tree decides is the *share*, not the
                            // pixel count. The file holds absolute pixels
                            // measured in whatever window last saved it, so
                            // restoring into a different one leaves their
                            // total off the container — and
                            // `adjust_to_container_size` rescales the state to
                            // the container on the very next pass. Adopting
                            // the raw numbers would re-assert the stale total,
                            // so hand over the share instead and both sides
                            // already agree.
                            state.adopt_sizes(&scale_sizes_to(state.container_size(), &sizes), cx);
                        });
                    }
                    if let Some(cached) = self.splits.get_mut(&node) {
                        cached.children = children;
                        cached.sizes = sizes;
                    }
                }
                ContainerPlan::Group {
                    node,
                    panels,
                    active_ix,
                    constraints,
                } => {
                    live_panels.extend(panels.iter().copied());
                    let views = self.views_of(&panels);
                    let group = self.group_entity(node, window, cx);
                    group.update(cx, |group, cx| {
                        // Every group must be told this. A group nobody has
                        // constrained stays `sealed()` and silently declines
                        // drags, drops and closes.
                        group.set_constraints(constraints, window, cx);
                        group.sync_from_tree(views, active_ix, window, cx);
                    });
                }
                ContainerPlan::Tiles { node, tiles } => {
                    live_panels.extend(tiles.iter().map(|(panel, _, _)| *panel));
                    let mirrored = tiles
                        .iter()
                        .filter_map(|(panel, bounds, z_index)| {
                            self.panels
                                .get(panel)
                                .map(|view| (view.clone(), *bounds, *z_index))
                        })
                        .collect();
                    let canvas = self.tiles_entity(node, window, cx);
                    canvas.update(cx, |canvas, cx| canvas.sync_from_tree(mirrored, cx));
                }
            }
        }

        self.groups.retain(|node, _| live_nodes.contains(node));
        self.splits.retain(|node, _| live_nodes.contains(node));
        self.tiles.retain(|node, _| live_nodes.contains(node));

        let departed: Vec<Arc<dyn PanelView>> = self
            .panels
            .iter()
            .filter(|(panel, _)| !live_panels.contains(panel))
            .map(|(_, view)| view.clone())
            .collect();
        self.panels.retain(|panel, _| live_panels.contains(panel));

        // A zoomed container fills the whole area, so one that has just left
        // the dock would otherwise keep filling it with nothing behind it.
        //
        // It is the container going away that ends the zoom, not a panel:
        // a group survives its displayed panel closing, and the next tab
        // takes over, still zoomed. The old `TabPanel::remove_panel` instead
        // emitted `ZoomOut` on every removal, which cleared the dock's zoom
        // even for a panel in some other tab panel entirely — and left the
        // zoomed `TabPanel` still flagged zoomed while the dock was not.
        let zoom_survives = match self.zoomed {
            Some(Zoomed::Group(node)) => self.groups.contains_key(&node),
            Some(Zoomed::Tile { node, panel }) => {
                self.tiles.contains_key(&node) && self.panels.contains_key(&panel)
            }
            None => true,
        };
        if !zoom_survives {
            self.set_zoom(None, window, cx);
        }

        cx.notify();
        // Last, so a panel reacting to this sees a dock that already agrees
        // with its trees.
        for view in departed {
            view.on_removed(window, cx);
        }
    }

    /// The views for a group's panel ids, in tab order.
    fn views_of(&self, panels: &[PanelId]) -> Vec<Arc<dyn PanelView>> {
        debug_assert!(
            panels.iter().all(|panel| self.panels.contains_key(panel)),
            "every panel in a tree must have a live view; a missing one would \
             silently shift the group's active index"
        );
        panels
            .iter()
            .filter_map(|panel| self.panels.get(panel).cloned())
            .collect()
    }

    fn group_entity(
        &mut self,
        node: NodeId,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Entity<TabGroup> {
        if let Some(cached) = self.groups.get(&node) {
            return cached.entity.clone();
        }

        let renderer = self.renderer.tab_group_renderer();
        let entity = cx.new(|cx| TabGroup::new(node, window, cx).with_renderer(renderer));
        let subscription = cx.subscribe_in(&entity, window, Self::on_tab_group_event);
        self.groups.insert(
            node,
            Cached {
                entity: entity.clone(),
                _subscription: subscription,
            },
        );
        entity
    }

    fn tiles_entity(
        &mut self,
        node: NodeId,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Entity<TilesState> {
        if let Some(cached) = self.tiles.get(&node) {
            return cached.entity.clone();
        }

        let renderer = self.renderer.tiles_renderer();
        let entity = cx.new(|cx| TilesState::new(node, window, cx).with_renderer(renderer));
        let subscription = cx.subscribe_in(&entity, window, Self::on_tiles_event);
        self.tiles.insert(
            node,
            Cached {
                entity: entity.clone(),
                _subscription: subscription,
            },
        );
        entity
    }

    fn split_entity(&mut self, node: NodeId, cx: &mut Context<Self>) -> Entity<ResizableState> {
        if let Some(cached) = self.splits.get(&node) {
            return cached.entity.clone();
        }

        let entity = cx.new(|_| ResizableState::default());
        // A drag on a resize handle changes only the measured sizes. Writing
        // them straight back keeps the tree describing the layout the user
        // arranged, which is what a later insert or removal scales from and
        // what a region with no live split entity is dumped from.
        //
        // It does not make the tree authoritative on slot sizes generally, and
        // `dump` does not treat it as such: only a finished drag arrives here,
        // while `adjust_to_container_size` rewrites the measurements silently
        // on every window resize. See [`Self::dump`].
        let subscription =
            cx.subscribe(&entity, move |this, state, _: &ResizablePanelEvent, cx| {
                let sizes: Vec<Option<Pixels>> = state
                    .read(cx)
                    .sizes()
                    .iter()
                    .map(|size| Some(*size))
                    .collect();
                let Some(region) = this.placement_of_node(node) else {
                    return;
                };
                let Some(tree) = this.tree_mut(region) else {
                    return;
                };
                if tree.set_sizes(node, sizes.clone()).changed() {
                    cx.emit(DockEvent::LayoutChanged);
                }
                // The state is where these came from, so the next reconcile
                // has nothing to hand it.
                if let Some(cached) = this.splits.get_mut(&node) {
                    cached.sizes = sizes;
                }
            });
        self.splits.insert(
            node,
            CachedSplit {
                entity: entity.clone(),
                children: Vec::new(),
                sizes: Vec::new(),
                _subscription: subscription,
            },
        );
        entity
    }
}

/// Intents arriving from the containers.
impl DockArea {
    fn on_tab_group_event(
        &mut self,
        group: &Entity<TabGroup>,
        event: &TabGroupEvent,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        match event {
            TabGroupEvent::Drop { panel, target, .. } => {
                self.move_panel(*panel, *target, window, cx)
            }
            TabGroupEvent::DragDrop { item, target } => cx.emit(DockEvent::DragDrop {
                item: item.clone(),
                target: target.clone(),
            }),
            TabGroupEvent::ClosePanel { panel } => self.remove_panel_id(*panel, window, cx),
            TabGroupEvent::ActiveChanged { ix } => {
                let node = group.read(cx).node();
                let Some(region) = self.placement_of_node(node) else {
                    return;
                };
                let Some(tree) = self.tree_mut(region) else {
                    return;
                };
                let result = tree.set_active(node, *ix);
                self.commit(result, window, cx);
            }
            TabGroupEvent::ZoomIn => {
                let node = group.read(cx).node();
                self.set_zoom(Some(Zoomed::Group(node)), window, cx);
            }
            // Only the group that is actually on screen can give the dock
            // back. A group told to zoom out to make room for another one
            // reports it too, and that report must not undo the zoom that
            // replaced it.
            TabGroupEvent::ZoomOut => {
                let node = group.read(cx).node();
                if self.zoomed == Some(Zoomed::Group(node)) {
                    self.set_zoom(None, window, cx);
                }
            }
        }
    }

    fn on_tiles_event(
        &mut self,
        canvas: &Entity<TilesState>,
        event: &TilesEvent,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let node = canvas.read(cx).node();
        let Some(region) = self.placement_of_node(node) else {
            return;
        };

        match event {
            TilesEvent::BoundsChanged { panel, bounds } => {
                let Some(tree) = self.tree_mut(region) else {
                    return;
                };
                let result = tree.set_tile_bounds(*panel, *bounds);
                self.commit(result, window, cx);
            }
            TilesEvent::BringToFront { panel } => {
                let Some(tree) = self.tree_mut(region) else {
                    return;
                };
                let result = tree.bring_to_front(*panel);
                self.commit(result, window, cx);
            }
            TilesEvent::ClosePanel { panel } => self.remove_panel_id(*panel, window, cx),
            TilesEvent::DragDrop { item } => cx.emit(DockEvent::DragDrop {
                item: item.clone(),
                target: DropTarget::Canvas,
            }),
            TilesEvent::ZoomIn { panel } => {
                self.set_zoom(
                    Some(Zoomed::Tile {
                        node,
                        panel: *panel,
                    }),
                    window,
                    cx,
                );
            }
            // As with a tab group: only the canvas actually on screen can
            // give the dock back.
            TilesEvent::ZoomOut => {
                if matches!(self.zoomed, Some(Zoomed::Tile { node: zoomed, .. }) if zoomed == node)
                {
                    self.set_zoom(None, window, cx);
                }
            }
        }
    }
}

/// Region lookup.
impl DockArea {
    /// Feed every split's measured size back into the tree before an edit
    /// that has to divide space.
    ///
    /// Done here rather than continuously: the tree is the record of what the
    /// user arranged, and rewriting it on every layout pass would let a
    /// transient window size become the stored layout.
    fn adopt_measured_sizes(&mut self, placement: DockPlacement, cx: &App) {
        let measured: HashMap<NodeId, Vec<Pixels>> = self
            .splits
            .iter()
            // Only splits that have actually been laid out. A split created
            // earlier in this same edit has a zero container and its `sizes`
            // are whatever `insert_panel` left behind — adopting those would
            // freeze a placeholder ratio into the tree, and every later edit
            // would divide space according to it.
            .filter(|(_, cached)| cached.entity.read(cx).container_size() > Pixels::ZERO)
            .map(|(node, cached)| (*node, cached.entity.read(cx).sizes().clone()))
            .collect();

        if let Some(tree) = self.tree_mut(placement) {
            tree.adopt_measured_sizes(&measured);
        }
    }

    fn tree_mut(&mut self, placement: DockPlacement) -> Option<&mut PaneTree> {
        match placement {
            DockPlacement::Center => Some(&mut self.center),
            _ => self.docks.get_mut(&placement).map(|pane| &mut pane.tree),
        }
    }

    /// Which region a container belongs to. Unambiguous because `NodeId`s are
    /// allocated globally rather than per tree.
    fn placement_of_node(&self, node: NodeId) -> Option<DockPlacement> {
        if self.center.find_node(node).is_some() {
            return Some(DockPlacement::Center);
        }
        self.docks
            .iter()
            .find(|(_, pane)| pane.tree.find_node(node).is_some())
            .map(|(placement, _)| *placement)
    }

    fn placement_of_panel(&self, panel: PanelId) -> Option<DockPlacement> {
        if self.center.find_panel_node(panel).is_some() {
            return Some(DockPlacement::Center);
        }
        self.docks
            .iter()
            .find(|(_, pane)| pane.tree.find_panel_node(panel).is_some())
            .map(|(placement, _)| *placement)
    }

    /// Resize one dock from a pointer position, clamped so neither this dock
    /// nor the one opposite is squeezed below its minimum.
    fn resize_dock(
        &mut self,
        placement: DockPlacement,
        pointer: Point<Pixels>,
        cx: &mut Context<Self>,
    ) {
        let opposite = match placement {
            DockPlacement::Left => self.dock_size(DockPlacement::Right),
            DockPlacement::Right => self.dock_size(DockPlacement::Left),
            _ => None,
        };
        let sizing = DockSizing::new(placement)
            .with_area_bounds(self.bounds)
            .with_opposite_dock_size(opposite.unwrap_or(px(0.)));
        let size = sizing.clamp(sizing.size_from_pointer(pointer));

        if let Some(pane) = self.docks.get_mut(&placement) {
            pane.dock.set_size(size);
            cx.notify();
        }
    }
}

/// Rendering.
impl DockArea {
    /// Lower one container to an element.
    fn render_node(&self, node: &PaneNode, window: &mut Window, cx: &mut App) -> AnyElement {
        match node.kind() {
            PaneRef::Split {
                axis,
                children,
                sizes,
            } => {
                let group = match axis {
                    Axis::Horizontal => h_resizable(("dock-split", node.id().as_u64())),
                    Axis::Vertical => v_resizable(("dock-split", node.id().as_u64())),
                };
                // A container whose every panel is hidden must not keep
                // occupying its slot. No renderer hook could supply this:
                // only the area can see the panels behind a node.
                let shown: Vec<bool> = children
                    .iter()
                    .map(|child| self.is_node_visible(child, cx))
                    .collect();
                // The slot that absorbs the leftover has to be one that is
                // actually drawn. A hidden slot renders nothing and grows
                // nothing, so making it the flexible one leaves every drawn
                // slot rigid and the split ends short of its container — the
                // empty strip this picks the *last shown* slot to avoid.
                let grows = shown.iter().rposition(|shown| *shown);
                let panels: Vec<_> = children
                    .iter()
                    .zip(sizes.iter())
                    .enumerate()
                    .map(|(ix, (child, size))| {
                        resizable_panel()
                            .visible(shown[ix])
                            .child(self.render_node(child, window, cx))
                            // `flex_none` is what makes the size stick.
                            // `ResizablePanel` sets `flex_grow: 1` on itself,
                            // so a slot given a size would otherwise treat it
                            // as a flex-basis and still absorb an equal share
                            // of the leftover — a 200px sidebar rendering
                            // 1075px wide in a 1950px split.
                            // The growth slot absorbs container growth. A
                            // drag records every measured size as pixels; if
                            // all of them became `flex_none`, a later viewport
                            // resize would leave an empty strip after the
                            // split instead of keeping the Dock filled.
                            .when_some(*size, |panel, size| {
                                panel
                                    .size(size)
                                    .when(Some(ix) != grows, |panel| panel.flex_none())
                            })
                    })
                    .collect();

                let group = group
                    .when_some(self.splits.get(&node.id()), |group, cached| {
                        group.with_state(&cached.entity)
                    })
                    .with_handle_appearance({
                        let renderer = self.renderer.clone();
                        Rc::new(move |handle, window, cx| {
                            renderer.render_split_handle(handle, window, cx)
                        })
                    })
                    .children(panels);

                self.renderer
                    .split_frame(node.id(), axis, window, cx)
                    // A split frame with no size collapses: base puts it
                    // between a `resizable_panel` and the resizable group, and
                    // between `center_frame` and the centre's root split, and
                    // neither parent sizes it. `size_full` and `flex_1` are
                    // belt and braces -- either alone passes every case I could
                    // construct, so this does not depend on which one wins in a
                    // given parent.
                    .size_full()
                    .flex_1()
                    .min_h(px(0.))
                    .overflow_hidden()
                    .child(group)
                    .into_any_element()
            }
            PaneRef::Tabs { .. } => match self.groups.get(&node.id()) {
                Some(cached) => cached.entity.clone().into_any_element(),
                None => Empty.into_any_element(),
            },
            PaneRef::Tiles { .. } => match self.tiles.get(&node.id()) {
                Some(cached) => cached.entity.clone().into_any_element(),
                None => Empty.into_any_element(),
            },
        }
    }

    /// Whether anything in this container is on screen.
    ///
    /// Mirrors the old `StackPanel::render`, which asked each slot's
    /// `TabPanel::visible` — "does this group hold any visible panel?" — and
    /// hid the slot when it did not.
    fn is_node_visible(&self, node: &PaneNode, cx: &App) -> bool {
        let panels = LivePanels::new(&self.panels, cx);
        match node.kind() {
            PaneRef::Split { children, .. } => {
                children.iter().any(|child| self.is_node_visible(child, cx))
            }
            PaneRef::Tabs { panels: ids, .. } => ids.iter().any(|panel| panels.is_visible(*panel)),
            PaneRef::Tiles { panels: tiles } => {
                tiles.iter().any(|tile| panels.is_visible(tile.panel()))
            }
        }
    }

    fn render_dock(
        &self,
        placement: DockPlacement,
        window: &mut Window,
        cx: &mut App,
    ) -> Option<AnyElement> {
        let pane = self.docks.get(&placement)?;
        let dock = self.dock_context(placement, &pane.dock);

        // A closed left or right dock takes no space at all; a closed bottom
        // dock keeps a strip so its tab bar stays clickable. Nothing is drawn
        // for a dock with no extent, and the renderer is not asked for chrome
        // nobody can see.
        let size = dock_extent(&dock);
        if size <= px(0.) {
            return Some(div().into_any_element());
        }

        let content = self.render_node(pane.tree.root(), window, cx);
        // The box is applied here rather than left to the renderer, and that is
        // the whole point of it being here. A dock's extent along its own axis
        // is not presentation -- it is what makes the dock a column beside the
        // centre instead of a block in the flow below it -- and a renderer that
        // did not know to state it produced a dock with no width, every pane
        // inside it shrunk to its content. `render_dock` on the renderer is a
        // chrome hook, so a renderer that draws nothing at all still gets a
        // dock that is the right shape.
        let chrome = self.renderer.render_dock(&dock, content, window, cx);
        Some(dock_frame(&dock, size).child(chrome).into_any_element())
    }

    fn dock_context(&self, placement: DockPlacement, dock: &Dock) -> DockContext {
        let area = self.this.clone();

        DockContext {
            placement,
            size: dock.size(),
            open: dock.is_open(),
            collapsible: dock.is_collapsible(),
            on_toggle: {
                let area = area.clone();
                Rc::new(move |window, cx| {
                    _ = area.update(cx, |area, cx| area.toggle_dock(placement, window, cx));
                })
            },
            on_resize: Rc::new(move |pointer, _, cx| {
                _ = area.update(cx, |area, cx| area.resize_dock(placement, pointer, cx));
            }),
        }
    }
}

impl EventEmitter<DockEvent> for DockArea {}

impl Focusable for DockArea {
    fn focus_handle(&self, _: &App) -> FocusHandle {
        self.focus_handle.clone()
    }
}

impl Render for DockArea {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let area = cx.entity();
        let renderer = self.renderer.clone();

        renderer
            .frame(window, cx)
            // Structure, applied after the hook and not inside it. A dock area
            // lays its left dock, centre and right dock out in a row; a frame
            // that is not one stacks them down the window instead, which is
            // what every renderer that is not `DockSkin` used to get, because
            // the row lived in `DockSkin`'s override of this hook and the trait
            // default is a bare `div`.
            .relative()
            .size_full()
            .overflow_hidden()
            .flex()
            .flex_row()
            .on_prepaint(move |bounds, _, cx| {
                area.update(cx, |area, _| area.bounds = bounds);
            })
            .track_focus(&self.focus_handle)
            .map(|frame| match self.zoomed_view() {
                Some(view) => frame.child(view),
                None => frame
                    .when_some(
                        self.render_dock(DockPlacement::Left, window, cx),
                        ParentElement::child,
                    )
                    .child(
                        renderer
                            .center_frame(window, cx)
                            // Same reason as the frame above: the centre is
                            // whatever the side docks leave, in a column with
                            // the bottom dock. Without this it is neither, and
                            // shrinks to its content.
                            .flex()
                            .flex_1()
                            .flex_col()
                            .overflow_hidden()
                            .child(self.render_node(self.center.root(), window, cx))
                            .when_some(
                                self.render_dock(DockPlacement::Bottom, window, cx),
                                ParentElement::child,
                            ),
                    )
                    .when_some(
                        self.render_dock(DockPlacement::Right, window, cx),
                        ParentElement::child,
                    ),
            })
    }
}

/// One container's worth of reconciliation work, snapshotted out of the tree.
enum ContainerPlan {
    Split {
        node: NodeId,
        axis: Axis,
        children: Vec<NodeId>,
        sizes: Vec<Option<Pixels>>,
    },
    Group {
        node: NodeId,
        panels: Vec<PanelId>,
        active_ix: usize,
        constraints: TabGroupConstraints,
    },
    Tiles {
        node: NodeId,
        tiles: Vec<(PanelId, Bounds<Pixels>, usize)>,
    },
}

impl ContainerPlan {
    fn node(&self) -> NodeId {
        match self {
            Self::Split { node, .. } | Self::Group { node, .. } | Self::Tiles { node, .. } => *node,
        }
    }
}

/// Re-express slot sizes as shares of `container`, keeping their proportions.
///
/// Returns them unchanged unless every slot is constrained and both the
/// container and the recorded total are usable: an unconstrained slot is laid
/// out by flex and takes the leftover, so scaling only the constrained ones
/// would move a divider nothing asked to move.
fn scale_sizes_to(container: Pixels, sizes: &[Option<Pixels>]) -> Vec<Option<Pixels>> {
    let total: f32 = sizes.iter().flatten().map(|size| size.as_f32()).sum();
    if container <= px(0.) || total <= 0. || sizes.iter().any(Option::is_none) {
        return sizes.to_vec();
    }

    let scale = container.as_f32() / total;
    sizes
        .iter()
        .map(|size| size.map(|size| px(size.as_f32() * scale)))
        .collect()
}

/// Bring one split's `ResizableState` panel list from `previous` to `next`,
/// inserting and removing at the exact index rather than at the tail.
///
/// `ResizableState` treats the size handed to `insert_panel` as an initial
/// value only; from then on `panels[ix].size` is authoritative. So an
/// append-and-truncate sync leaves every survivor of a non-tail removal
/// wearing the width of whoever used to sit at its index — which is the most
/// ordinary edit in the dock, a drag that empties a group, and it is carried
/// into the save file by `resolve_sizes`.
fn sync_split_panels(
    state: &mut ResizableState,
    previous: &[NodeId],
    next: &[NodeId],
    sizes: &[Option<Pixels>],
    cx: &mut Context<ResizableState>,
) {
    let mut current = previous.to_vec();

    // Removals from the tail, so the indices ahead of each removal stay valid.
    for ix in (0..current.len()).rev() {
        if !next.contains(&current[ix]) {
            if ix < state.sizes().len() {
                state.remove_panel(ix, cx);
            }
            current.remove(ix);
        }
    }

    for (ix, node) in next.iter().enumerate() {
        if current.get(ix) == Some(node) {
            continue;
        }
        let at = ix.min(state.sizes().len());
        // Passed through as-is. The tree already decided this slot's share
        // when the panel was inserted — a drop halves the neighbour it landed
        // beside — so there is nothing to compute here, and nothing that
        // depends on a container this state may not have measured yet.
        state.insert_panel(sizes.get(ix).copied().flatten(), Some(at), cx);
        current.insert(at.min(current.len()), *node);
    }

    debug_assert_eq!(
        current, next,
        "the split's panel list must end up mirroring its children exactly; \
         a reordering edit would need its own case here"
    );
}

fn plan_tree(tree: &PaneTree, collapsed: bool, locked: bool, out: &mut Vec<ContainerPlan>) {
    // The root has nothing beside it by definition.
    plan_node(tree.root(), true, collapsed, locked, out);
}

fn plan_node(
    node: &PaneNode,
    alone: bool,
    collapsed: bool,
    locked: bool,
    out: &mut Vec<ContainerPlan>,
) {
    match node.kind() {
        PaneRef::Split {
            axis,
            children,
            sizes,
        } => {
            out.push(ContainerPlan::Split {
                node: node.id(),
                axis,
                children: children.iter().map(PaneNode::id).collect(),
                sizes: sizes.to_vec(),
            });
            let children_alone = children.len() <= 1;
            for child in children {
                plan_node(child, children_alone, collapsed, locked, out);
            }
        }
        PaneRef::Tabs { panels, active_ix } => out.push(ContainerPlan::Group {
            node: node.id(),
            panels: panels.to_vec(),
            active_ix,
            constraints: TabGroupConstraints::in_split(alone)
                .dock_locked(locked)
                .collapsed(collapsed),
        }),
        PaneRef::Tiles { panels } => out.push(ContainerPlan::Tiles {
            node: node.id(),
            tiles: panels
                .iter()
                .map(|tile| (tile.panel(), tile.bounds(), tile.z_index()))
                .collect(),
        }),
    }
}

fn first_tab_group(node: &PaneNode) -> Option<NodeId> {
    match node.kind() {
        PaneRef::Tabs { .. } => Some(node.id()),
        PaneRef::Split { children, .. } => children.iter().find_map(first_tab_group),
        PaneRef::Tiles { .. } => None,
    }
}

fn first_tiles_canvas(node: &PaneNode) -> Option<NodeId> {
    match node.kind() {
        PaneRef::Tiles { .. } => Some(node.id()),
        PaneRef::Split { children, .. } => children.iter().find_map(first_tiles_canvas),
        PaneRef::Tabs { .. } => None,
    }
}

fn target_node(target: &InsertTarget) -> NodeId {
    match target {
        InsertTarget::Tabs { node, .. }
        | InsertTarget::Split { node, .. }
        | InsertTarget::Tile { node, .. } => *node,
    }
}

/// Rebuilds panels out of persisted state through [`PanelRegistry`].
struct RegistryPanelBuilder<'a, 'w, 'c> {
    dock_area: WeakEntity<DockArea>,
    renderer: Rc<dyn DockAreaRenderer>,
    built: &'a mut Vec<(PanelId, Arc<dyn PanelView>)>,
    window: &'w mut Window,
    cx: &'c mut App,
}

impl PanelBuilder for RegistryPanelBuilder<'_, '_, '_> {
    fn build(&mut self, state: &PanelState, info: &PanelInfo) -> PanelId {
        let context = PanelBuildContext::new(self.dock_area.clone(), state, info);
        let view =
            match PanelRegistry::build_panel(&state.panel_name, context, self.window, self.cx) {
                Some(view) => view,
                None => self
                    .renderer
                    .build_placeholder(state, self.window, self.cx)
                    .unwrap_or_else(|| {
                        Arc::new(self.cx.new(|cx| PlaceholderPanel::new(state.clone(), cx)))
                            as Arc<dyn PanelView>
                    }),
            };

        let id = view.panel_id(self.cx);
        self.built.push((id, view));
        id
    }
}

/// Stands in for a panel this build cannot construct.
///
/// It draws nothing — an "unknown panel" message is presentation and belongs
/// above this seam — but it keeps the original [`PanelState`] and hands it
/// back from [`Panel::dump`], so a layout written by a newer build survives a
/// load and save here instead of losing the panel.
struct PlaceholderPanel {
    state: PanelState,
    focus_handle: FocusHandle,
}

impl PlaceholderPanel {
    fn new(state: PanelState, cx: &mut Context<Self>) -> Self {
        Self {
            state,
            focus_handle: cx.focus_handle(),
        }
    }
}

impl Panel for PlaceholderPanel {
    fn panel_name(&self) -> &'static str {
        "InvalidPanel"
    }

    fn dump(&self, _: &App) -> PanelState {
        self.state.clone()
    }
}

impl EventEmitter<PanelEvent> for PlaceholderPanel {}

impl Focusable for PlaceholderPanel {
    fn focus_handle(&self, _: &App) -> FocusHandle {
        self.focus_handle.clone()
    }
}

impl Render for PlaceholderPanel {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        Empty
    }
}

type DockToggleHandler = Rc<dyn Fn(&mut Window, &mut App)>;
type DockResizeHandler = Rc<dyn Fn(Point<Pixels>, &mut Window, &mut App)>;

/// What a skin needs to draw one dock, and the callbacks it invokes rather
/// than reimplementing the open/close and clamping behavior.
#[derive(Clone)]
pub struct DockContext {
    placement: DockPlacement,
    size: Pixels,
    open: bool,
    collapsible: bool,
    on_toggle: DockToggleHandler,
    on_resize: DockResizeHandler,
}

impl DockContext {
    pub fn placement(&self) -> DockPlacement {
        self.placement
    }

    /// The dock's extent along its own axis: width for left/right, height for
    /// bottom.
    pub fn size(&self) -> Pixels {
        self.size
    }

    pub fn is_open(&self) -> bool {
        self.open
    }

    pub fn is_collapsible(&self) -> bool {
        self.collapsible
    }

    pub fn toggle(&self, window: &mut Window, cx: &mut App) {
        (self.on_toggle)(window, cx);
    }

    /// Resize from a pointer position in window coordinates. Base clamps it
    /// against the area bounds and the opposite dock.
    pub fn resize_to(&self, pointer: Point<Pixels>, window: &mut Window, cx: &mut App) {
        (self.on_resize)(pointer, window, cx);
    }
}

/// A closed bottom dock keeps this much, so its tab bar stays clickable. A
/// closed side dock keeps nothing: there is no tab bar left to click at zero
/// width, and reopening it is the application's to offer.
pub const CLOSED_BOTTOM_STRIP: Pixels = px(29.);

/// How much room a dock asks for along its own axis.
pub fn dock_extent(dock: &DockContext) -> Pixels {
    match (dock.is_open(), dock.placement()) {
        (true, _) => dock.size(),
        (false, DockPlacement::Bottom) => CLOSED_BOTTOM_STRIP,
        (false, _) => px(0.),
    }
}

/// The box a dock occupies: its extent along its own axis, full across, and
/// held at that size rather than stretched by the row it sits in.
///
/// Structural, not decorative, which is why it is built here and not in a
/// renderer. See [`DockArea::render_dock`].
pub fn dock_frame(dock: &DockContext, size: Pixels) -> Div {
    div()
        .flex()
        .flex_none()
        .relative()
        .overflow_hidden()
        .map(|this| match dock.placement() {
            DockPlacement::Left | DockPlacement::Right => this.flex_row().h_full().w(size),
            DockPlacement::Bottom => this.w_full().h(size),
            // Base never builds a dock for the centre.
            DockPlacement::Center => this,
        })
}

/// Appearance for the dock area. Base draws none of it.
///
/// The frame hooks return the element itself rather than wrapping one, for the
/// same reason [`TabGroupRenderer`]'s do: base tracks focus and records the
/// area bounds on the very element the skin styles.
///
/// There is no separate `render_resize_handle` hook. A handle needs to be
/// positioned against the dock it resizes, and positioning is the skin's; the
/// skin draws it inside [`Self::render_dock`] and drives it through
/// [`DockContext::resize_to`].
#[allow(unused_variables)]
pub trait DockAreaRenderer: 'static {
    /// The area's outer frame, which base records its bounds on.
    /// Appearance only. The area is laid out as a row around whatever this
    /// returns, because that is what makes a dock a column beside the centre
    /// rather than a block above it, and a renderer cannot be expected to know
    /// it had a row to declare.
    fn frame(&self, window: &mut Window, cx: &mut App) -> Stateful<Div> {
        div().id("dock-area")
    }

    /// One split container's frame, around base's resizable group.
    ///
    /// This one really is a wrapper, unlike the other frame hooks, and
    /// deliberately: base attaches nothing to it, so there is no hit area to
    /// separate from the painted area. It exists because the old `StackPanel`
    /// carried real appearance here — a background and an overflow clip — and
    /// without it a skin could style a dock and a tab group but nothing in
    /// between. `Stateful<Div>` rather than a plain one so the skin keeps a
    /// role, a tooltip, and scroll tracking.
    fn split_frame(
        &self,
        node: NodeId,
        axis: Axis,
        window: &mut Window,
        cx: &mut App,
    ) -> Stateful<Div> {
        div().id(("dock-split-frame", node.as_u64()))
    }

    /// The column holding the center region and the bottom dock.
    /// Appearance only; see [`DockAreaRenderer::frame`]. The centre fills what
    /// the side docks leave and stacks with the bottom dock either way.
    fn center_frame(&self, window: &mut Window, cx: &mut App) -> Stateful<Div> {
        div().id("dock-area-center")
    }

    /// The painted part of the divider between two slots of a split.
    ///
    /// `None` keeps base's own one-pixel line, so a skin that has no opinion
    /// about dividers implements nothing. The hit area, the cursor and the
    /// drag itself stay with base either way — this hook supplies appearance
    /// only, and is told the axis and whether the divider is being dragged.
    fn render_split_handle(
        &self,
        handle: &ResizeHandleContext,
        window: &mut Window,
        cx: &mut App,
    ) -> Option<AnyElement> {
        None
    }

    /// One dock's chrome around its content: the title strip, the collapse
    /// affordance, and the resize handle.
    ///
    /// Chrome only. The dock's own box -- its extent along its own axis, and
    /// the `flex_none` that holds it there -- is applied by
    /// [`DockArea::render_dock`] around whatever this returns, so a renderer
    /// cannot misplace a dock by not knowing to size it, and the default here
    /// can be what it is: the content, undecorated.
    fn render_dock(
        &self,
        dock: &DockContext,
        content: AnyElement,
        window: &mut Window,
        cx: &mut App,
    ) -> AnyElement {
        content
    }

    /// The stand-in for a panel this build cannot construct — one whose
    /// `panel_name` no [`PanelRegistry`] builder answers to. `None` takes
    /// base's own placeholder, which draws nothing.
    ///
    /// The hook exists because a placeholder cannot be wrapped after the
    /// fact: presentation reaches base only through the handle a panel is
    /// registered behind, so whoever creates the panel decides what it can
    /// draw. An "unknown panel" message is presentation, so the skin creates
    /// that panel or does without one.
    ///
    /// A placeholder is what gets written back out on the next save, so one
    /// supplied here should answer [`Panel::dump`] with `state` unchanged —
    /// otherwise saving after a load erases the panel it stood in for. Base's
    /// own placeholder does; nothing here can enforce it of a skin's.
    fn build_placeholder(
        &self,
        state: &PanelState,
        window: &mut Window,
        cx: &mut App,
    ) -> Option<Arc<dyn PanelView>> {
        None
    }

    fn tab_group_renderer(&self) -> Rc<dyn TabGroupRenderer>;

    fn tiles_renderer(&self) -> Rc<dyn TilesRenderer>;
}

/// The renderer an area starts with: the layout and nothing else.
struct BareDockArea;

impl DockAreaRenderer for BareDockArea {
    fn tab_group_renderer(&self) -> Rc<dyn TabGroupRenderer> {
        Rc::new(BareTabGroup)
    }

    fn tiles_renderer(&self) -> Rc<dyn TilesRenderer> {
        Rc::new(BareTiles)
    }
}

#[cfg(test)]
impl DockArea {
    /// Every cached container, as `(node, entity)`.
    ///
    /// Entity ids, not just node ids: node ids alone would compare equal even
    /// if every container entity had been torn down and rebuilt under the same
    /// key, which is exactly the failure the reconciliation contract exists to
    /// prevent.
    pub(crate) fn container_entity_ids(&self) -> Vec<(NodeId, gpui::EntityId)> {
        let mut ids: Vec<(NodeId, gpui::EntityId)> = self
            .groups
            .iter()
            .map(|(node, cached)| (*node, cached.entity.entity_id()))
            .chain(
                self.splits
                    .iter()
                    .map(|(node, cached)| (*node, cached.entity.entity_id())),
            )
            .chain(
                self.tiles
                    .iter()
                    .map(|(node, cached)| (*node, cached.entity.entity_id())),
            )
            .collect();
        ids.sort();
        ids
    }
}

#[cfg(test)]
mod tests {
    use gpui::{TestAppContext, VisualTestContext};

    use std::{
        cell::{Cell, RefCell},
        rc::Rc,
    };

    use super::*;
    use crate::dock::test_support::{Log, PanelSignal, TestPanel, drain, drain_active, log_of};
    use crate::dock::{TabGroupContext, TileContext};

    /// The file holds pixels measured in whatever window last saved it, so its
    /// total is off the container the layout is restored into.
    #[test]
    fn slot_sizes_are_re_expressed_as_shares_of_the_container() {
        let scaled = scale_sizes_to(px(800.), &[Some(px(300.)), Some(px(100.))]);

        assert_eq!(scaled, vec![Some(px(600.)), Some(px(200.))]);
    }

    /// An unconstrained slot is laid out by flex and takes the leftover, so
    /// scaling only its siblings would move a divider nothing asked to move.
    #[test]
    fn an_unconstrained_slot_leaves_every_size_alone() {
        let sizes = [Some(px(300.)), None];

        assert_eq!(scale_sizes_to(px(800.), &sizes), sizes.to_vec());
    }

    /// Nothing to scale against before the first layout pass, or when the
    /// recorded sizes carry no length at all.
    #[test]
    fn an_unusable_container_or_total_leaves_every_size_alone() {
        let sizes = [Some(px(300.)), Some(px(100.))];
        assert_eq!(scale_sizes_to(px(0.), &sizes), sizes.to_vec());

        let zeroed = [Some(px(0.)), Some(px(0.))];
        assert_eq!(scale_sizes_to(px(800.), &zeroed), zeroed.to_vec());
    }

    fn setup(cx: &mut TestAppContext) -> (Entity<DockArea>, &mut VisualTestContext) {
        cx.update(|cx| {
            let _ = crate::Theme::global_mut(cx);
        });
        cx.add_window_view(|window, cx| DockArea::new("test-dock", None, window, cx))
    }

    #[gpui::test]
    fn dock_size_change_emits_one_layout_event(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.set_dock(
                    DockPlacement::Left,
                    DockLayout::tabs().panel(TestPanel::new("Left", cx)),
                    window,
                    cx,
                );
            });
        });

        let events = Rc::new(Cell::new(0));
        let observed = events.clone();
        let _subscription = cx.update(|window, cx| {
            window.subscribe(&area, cx, move |_, event: &DockEvent, _, _| {
                if matches!(event, DockEvent::LayoutChanged) {
                    observed.set(observed.get() + 1);
                }
            })
        });

        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.set_dock_size(DockPlacement::Left, px(320.), window, cx);
                area.set_dock_size(DockPlacement::Left, px(320.), window, cx);
            });
        });
        assert_eq!(
            events.get(),
            1,
            "only an effective size change is persisted"
        );
    }

    /// Two tab groups side by side, holding one logging panel each.
    fn two_groups<'a>(
        log: &Log,
        cx: &'a mut TestAppContext,
    ) -> (
        Entity<DockArea>,
        Entity<TestPanel>,
        &'a mut VisualTestContext,
    ) {
        let (area, cx) = setup(cx);
        let log = log.clone();
        let alpha = cx.update(|window, cx| {
            let alpha = TestPanel::logging("Alpha", &log, cx);
            let beta = TestPanel::logging("Beta", &log, cx);
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::h_split()
                        .child(DockLayout::tabs().panel(alpha.clone()), None)
                        .child(DockLayout::tabs().panel(beta), None),
                    window,
                    cx,
                );
            });
            alpha
        });
        (area, alpha, cx)
    }

    /// The id of the center split's `ix`-th child container.
    fn child_node(area: &Entity<DockArea>, ix: usize, cx: &mut VisualTestContext) -> NodeId {
        cx.read(|cx| {
            let PaneRef::Split { children, .. } = area
                .read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .root()
                .kind()
            else {
                panic!("the center root is a split");
            };
            children[ix].id()
        })
    }

    fn panel_id_of(panel: &Entity<TestPanel>) -> PanelId {
        PanelId::from(panel.entity_id())
    }

    fn move_alpha_into_the_other_group(
        area: &Entity<DockArea>,
        alpha: &Entity<TestPanel>,
        cx: &mut VisualTestContext,
    ) {
        let target = child_node(area, 1, cx);
        let alpha_id = panel_id_of(alpha);
        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.move_panel(
                    alpha_id,
                    InsertTarget::Tabs {
                        node: target,
                        ix: None,
                        activate: true,
                    },
                    window,
                    cx,
                );
            });
        });
        cx.run_until_parked();
    }

    fn collect_sizes(state: &PanelState, out: &mut Vec<Pixels>) {
        if let PanelInfo::Stack { sizes, .. } = &state.info {
            out.extend(sizes.iter().copied());
        }
        for child in &state.children {
            collect_sizes(child, out);
        }
    }

    fn register_test_panels(cx: &mut App) {
        for name in ["Alpha", "Beta", "Gamma"] {
            crate::dock::registry::register_panel(cx, name, move |_, _, cx| {
                Arc::new(TestPanel::new(name, cx)) as Arc<dyn PanelView>
            });
        }
    }

    /// One tab group holding `names`, installed as the whole center.
    ///
    /// The `DockItem::tabs` the old `TabPanel` tests built is now a described
    /// layout the area reconciles, so the group entity is reached through the
    /// tree rather than handed back by the constructor.
    fn one_group<'a>(
        log: &Log,
        names: &[&'static str],
        active_ix: Option<usize>,
        cx: &'a mut TestAppContext,
    ) -> (
        Entity<DockArea>,
        Vec<Entity<TestPanel>>,
        &'a mut VisualTestContext,
    ) {
        let (area, cx) = setup(cx);
        let log = log.clone();
        let names = names.to_vec();
        let panels = cx.update(|window, cx| {
            let panels: Vec<_> = names
                .iter()
                .map(|name| TestPanel::logging(name, &log, cx))
                .collect();
            let layout = panels
                .iter()
                .fold(DockLayout::tabs(), |layout, panel| {
                    layout.panel(panel.clone())
                })
                .active_index(active_ix.unwrap_or(0));
            area.update(cx, |area, cx| area.set_center(layout, window, cx));
            panels
        });
        (area, panels, cx)
    }

    /// The live group behind the center split's `ix`-th child.
    fn group_of(
        area: &Entity<DockArea>,
        ix: usize,
        cx: &mut VisualTestContext,
    ) -> Entity<TabGroup> {
        let node = child_node(area, ix, cx);
        cx.read(|cx| area.read(cx).groups.get(&node).unwrap().entity.clone())
    }

    fn move_panel_into(
        area: &Entity<DockArea>,
        panel: PanelId,
        node: NodeId,
        ix: Option<usize>,
        activate: bool,
        cx: &mut VisualTestContext,
    ) {
        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.move_panel(panel, InsertTarget::Tabs { node, ix, activate }, window, cx);
            });
        });
        cx.run_until_parked();
    }

    fn is_center_empty(area: &Entity<DockArea>, cx: &mut VisualTestContext) -> bool {
        cx.read(|cx| area.read(cx).is_empty(DockPlacement::Center, cx))
    }

    #[gpui::test]
    fn a_layout_installs_and_dumps_back_to_the_same_state(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        cx.update(|window, cx| {
            let alpha = TestPanel::new("Alpha", cx);
            let beta = TestPanel::new("Beta", cx);
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::h_split()
                        .child(DockLayout::tabs().panel(alpha), Some(px(300.)))
                        .child(DockLayout::tabs().panel(beta), None),
                    window,
                    cx,
                );
            });
        });

        let state = cx.read(|cx| area.read(cx).dump(cx));
        assert_eq!(state.center.panel_name, "StackPanel");
        assert_eq!(state.center.children.len(), 2);
        assert_eq!(state.center.children[0].children[0].panel_name, "Alpha");
        assert_eq!(state.center.children[1].children[0].panel_name, "Beta");
    }

    #[gpui::test]
    fn moving_a_panel_reuses_its_entity(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, alpha, cx) = two_groups(&log, cx);
        cx.run_until_parked();
        drain(&log);

        let destination = child_node(&area, 1, cx);
        let destination_entity = cx.read(|cx| {
            area.read(cx)
                .groups
                .get(&destination)
                .unwrap()
                .entity
                .entity_id()
        });

        move_alpha_into_the_other_group(&area, &alpha, cx);

        assert_eq!(
            cx.read(|cx| area
                .read(cx)
                .groups
                .get(&destination)
                .unwrap()
                .entity
                .entity_id()),
            destination_entity,
            "the group the panel arrived in was reused, not rebuilt"
        );

        // A liveness flag on the panel would not say this. The invariant is
        // that the panel is still in the tree and was never told it was
        // removed — which is exactly what `EditResult::removed_panels` encodes
        // by excluding moves.
        let alpha_id = panel_id_of(&alpha);
        assert!(
            cx.read(|cx| area
                .read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .find_panel_node(alpha_id))
                .is_some(),
            "the moved panel is still in the tree"
        );

        let state = cx.read(|cx| area.read(cx).dump(cx));
        // One child, not two: emptying the first group removes it, and a
        // `RootKind::Split` root is never collapsed, so what is left is a
        // one-child split root.
        assert_eq!(
            state.center.children.len(),
            1,
            "the emptied group collapsed out of the split"
        );
        assert_eq!(
            state.center.children[0].children.len(),
            2,
            "both panels now share the surviving group"
        );
    }

    #[gpui::test]
    fn a_moved_panel_is_not_told_it_was_removed(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, alpha, cx) = two_groups(&log, cx);
        cx.run_until_parked();
        drain(&log);

        move_alpha_into_the_other_group(&area, &alpha, cx);

        assert!(
            !drain(&log).contains(&("Alpha", PanelSignal::Removed)),
            "moving a panel between groups must never deliver on_removed"
        );
    }

    #[gpui::test]
    fn removing_a_panel_does_tell_it_it_was_removed(cx: &mut TestAppContext) {
        // Without this, `a_moved_panel_is_not_told_it_was_removed` would pass
        // just as well against a `DockArea` that never calls `on_removed` at
        // all.
        let log = log_of();
        let (area, alpha, cx) = two_groups(&log, cx);
        cx.run_until_parked();
        drain(&log);

        cx.update(|window, cx| {
            area.update(cx, |area, cx| area.remove_panel(alpha.clone(), window, cx));
        });
        cx.run_until_parked();

        assert!(
            drain(&log).contains(&("Alpha", PanelSignal::Removed)),
            "a genuine removal must deliver on_removed"
        );
    }

    #[gpui::test]
    fn reconciling_an_unchanged_tree_creates_no_entities(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, _alpha, cx) = two_groups(&log, cx);
        cx.run_until_parked();
        drain(&log);

        let before = cx.read(|cx| area.read(cx).container_entity_ids());
        cx.update(|window, cx| area.update(cx, |area, cx| area.reconcile(window, cx)));
        let after = cx.read(|cx| area.read(cx).container_entity_ids());

        assert!(!before.is_empty(), "there were containers to preserve");
        assert_eq!(
            before, after,
            "a steady-state pass creates and drops nothing"
        );
        cx.run_until_parked();
        assert_eq!(
            drain(&log),
            vec![],
            "and no panel was re-added or re-activated by it"
        );
    }

    #[gpui::test]
    fn a_loaded_layout_round_trips_through_dump(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        cx.update(|_, cx| register_test_panels(cx));

        let json = include_str!("fixtures/nested_splits.json");
        let state: DockAreaState = serde_json::from_str(json).unwrap();

        cx.update(|window, cx| {
            area.update(cx, |area, cx| area.load(state.clone(), window, cx).unwrap())
        });
        let dumped = cx.read(|cx| area.read(cx).dump(cx));

        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.load(dumped.clone(), window, cx).unwrap()
            })
        });
        let again = cx.read(|cx| area.read(cx).dump(cx));

        assert_eq!(dumped, again, "load/dump must reach a fixpoint");
        assert_eq!(
            dumped.center.children.len(),
            3,
            "the fixture's nesting is flattened, as the state layer already pins"
        );
        assert_eq!(dumped.center.children[0].children[0].panel_name, "Alpha");
    }

    #[gpui::test]
    fn a_dumped_live_layout_has_no_zero_sizes(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        cx.update(|window, cx| {
            let alpha = TestPanel::new("Alpha", cx);
            let beta = TestPanel::new("Beta", cx);
            let gamma = TestPanel::new("Gamma", cx);
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::v_split()
                        // Unconstrained, which the tree stores as `None` and
                        // the writer would otherwise emit as 0.0.
                        .child(DockLayout::tabs().panel(alpha), None)
                        // Already zero. Resolving only the `None` slots would
                        // leave this one writing the same unsafe byte.
                        .child(DockLayout::tabs().panel(beta), Some(px(0.)))
                        .child(DockLayout::tabs().panel(gamma), Some(px(240.))),
                    window,
                    cx,
                );
            });
        });

        let state = cx.read(|cx| area.read(cx).dump(cx));
        let mut sizes = Vec::new();
        collect_sizes(&state.center, &mut sizes);

        assert!(!sizes.is_empty(), "the layout has slots to check");
        assert!(
            sizes.iter().all(|size| *size > px(0.)),
            "an older build reads a persisted 0.0 back as a real zero-pixel panel: {sizes:?}"
        );
    }

    /// The tree only hears about slot sizes a drag finished on: the `Resized`
    /// subscription fires from `done_resizing`, while every window resize
    /// rescales `ResizableState::sizes()` silently. So `dump` reads the
    /// measurement for a split it has on screen, and this pins that it does —
    /// preferring the tree here would persist the described `300.0` after a
    /// layout pass has already rescaled that slot to fit the window.
    #[gpui::test]
    fn a_dumped_split_writes_the_sizes_it_is_actually_drawn_at(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        cx.update(|window, cx| {
            let alpha = TestPanel::new("Alpha", cx);
            let beta = TestPanel::new("Beta", cx);
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::h_split()
                        .child(DockLayout::tabs().panel(alpha), Some(px(300.)))
                        .child(DockLayout::tabs().panel(beta), Some(px(300.))),
                    window,
                    cx,
                );
            });
        });
        cx.run_until_parked();

        let root = cx.read(|cx| {
            area.read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .root()
                .id()
        });
        let measured = cx.read(|cx| area.read(cx).splits[&root].entity.read(cx).sizes().clone());
        assert_ne!(
            measured,
            vec![px(300.), px(300.)],
            "the split has to have been rescaled by a layout pass, or this \
             test cannot tell the two preferences apart"
        );

        let state = cx.read(|cx| area.read(cx).dump(cx));
        let PanelInfo::Stack { sizes, .. } = &state.center.info else {
            panic!("the center writes a stack");
        };
        assert_eq!(
            sizes, &measured,
            "the written sizes are the ones on screen, not the ones the tree \
             was built from"
        );
    }

    /// A drop that splits carries no size — `TabGroup` builds
    /// `InsertTarget::Split { size: None }` — so the split has to decide one,
    /// and sharing the container equally is the decision. Passing the `None`
    /// straight to `ResizableState` instead makes the new slot the flexible
    /// one among fixed siblings, and it stops looking like a half.
    #[gpui::test]
    fn a_panel_dropped_beside_another_takes_half_the_split(cx: &mut TestAppContext) {
        let log = Log::default();
        let (area, panels, cx) = one_group(&log, &["Alpha", "Beta"], None, cx);
        let group = child_node(&area, 0, cx);
        let beta = panel_id_of(&panels[1]);

        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.move_panel(
                    beta,
                    InsertTarget::Split {
                        node: group,
                        placement: Placement::Right,
                        size: None,
                    },
                    window,
                    cx,
                );
            });
        });
        cx.run_until_parked();

        let root = cx.read(|cx| {
            area.read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .root()
                .id()
        });
        let sizes = cx.read(|cx| area.read(cx).splits[&root].entity.read(cx).sizes().clone());

        assert_eq!(sizes.len(), 2, "the drop splits the center in two");
        let (left, right) = (sizes[0].as_f32(), sizes[1].as_f32());
        assert!(
            (left - right).abs() <= (left + right) * 0.02,
            "the two halves must be within 2% of each other, got {left} and {right}"
        );
    }

    /// The other drop geometry: a placement whose axis differs from the
    /// parent's wraps the target in a fresh split, so the sizes are decided
    /// by a `ResizableState` that has never been measured.
    #[gpui::test]
    fn a_panel_dropped_across_the_axis_still_takes_half(cx: &mut TestAppContext) {
        let log = Log::default();
        let (area, panels, cx) = one_group(&log, &["Alpha", "Beta"], None, cx);
        let group = child_node(&area, 0, cx);
        let beta = panel_id_of(&panels[1]);

        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.move_panel(
                    beta,
                    InsertTarget::Split {
                        node: group,
                        placement: Placement::Bottom,
                        size: None,
                    },
                    window,
                    cx,
                );
            });
        });
        cx.run_until_parked();

        // Dropping across the axis wraps the target in a new split, which
        // becomes the center root's only child — the root itself still holds
        // one slot.
        let wrapper = child_node(&area, 0, cx);
        let sizes = cx.read(|cx| {
            area.read(cx).splits[&wrapper]
                .entity
                .read(cx)
                .sizes()
                .clone()
        });
        assert_eq!(sizes.len(), 2, "the drop splits the group in two");
        let (top, bottom) = (sizes[0].as_f32(), sizes[1].as_f32());
        assert!(
            (top - bottom).abs() <= (top + bottom) * 0.02,
            "the two halves must be within 2% of each other, got {top} and {bottom}"
        );
    }

    /// A drop into a split that already holds more than one slot, which is the
    /// shape a real workspace is in by the time anyone drags anything.
    #[gpui::test]
    fn a_panel_dropped_into_a_populated_split_takes_an_even_share(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        let panels = cx.update(|window, cx| {
            let alpha = TestPanel::new("Alpha", cx);
            let beta = TestPanel::new("Beta", cx);
            let gamma = TestPanel::new("Gamma", cx);
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::h_split()
                        .child(DockLayout::tabs().panel(alpha.clone()), Some(px(240.)))
                        .child(
                            DockLayout::tabs().panel(beta.clone()).panel(gamma.clone()),
                            None,
                        ),
                    window,
                    cx,
                );
            });
            vec![alpha, beta, gamma]
        });
        cx.run_until_parked();

        let right = child_node(&area, 1, cx);
        let gamma = panel_id_of(&panels[2]);
        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.move_panel(
                    gamma,
                    InsertTarget::Split {
                        node: right,
                        placement: Placement::Right,
                        size: None,
                    },
                    window,
                    cx,
                );
            });
        });
        cx.run_until_parked();

        let root = cx.read(|cx| {
            area.read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .root()
                .id()
        });
        let sizes = cx.read(|cx| area.read(cx).splits[&root].entity.read(cx).sizes().clone());
        assert_eq!(sizes.len(), 3, "three slots side by side");
        let dropped = sizes[2].as_f32();
        let neighbour = sizes[1].as_f32();
        assert!(
            (dropped - neighbour).abs() <= (dropped + neighbour) * 0.02,
            "the dropped panel splits its neighbour evenly, got neighbour {neighbour} and dropped {dropped}"
        );
    }

    /// A dock's root is usually a bare tab group, so a drop beside it takes
    /// the "wrap the target in a new split" path rather than the "insert into
    /// the existing split" one — and that split has never been measured.
    #[gpui::test]
    fn a_panel_dropped_beside_a_dock_takes_half(cx: &mut TestAppContext) {
        for placement in [DockPlacement::Bottom, DockPlacement::Left] {
            let (area, cx) = setup(cx);
            let dropped = cx.update(|window, cx| {
                let resident = TestPanel::new("Resident", cx);
                let dropped = TestPanel::new("Dropped", cx);
                area.update(cx, |area, cx| {
                    area.set_center(
                        DockLayout::tabs().panel(TestPanel::new("Center", cx)),
                        window,
                        cx,
                    );
                    area.set_dock(
                        placement,
                        DockLayout::tabs().panel(resident).panel(dropped.clone()),
                        window,
                        cx,
                    );
                    area.set_dock_size(placement, px(400.), window, cx);
                });
                dropped
            });
            cx.run_until_parked();

            let group = cx.read(|cx| {
                area.read(cx)
                    .layout(placement)
                    .unwrap()
                    .find_panel_node(panel_id_of(&dropped))
                    .expect("both panels start in the dock's only group")
            });

            cx.update(|window, cx| {
                area.update(cx, |area, cx| {
                    area.move_panel(
                        panel_id_of(&dropped),
                        InsertTarget::Split {
                            node: group,
                            placement: Placement::Bottom,
                            size: None,
                        },
                        window,
                        cx,
                    );
                });
            });
            cx.run_until_parked();

            let split = cx.read(|cx| {
                let tree = area.read(cx).layout(placement).unwrap();
                let root = tree.root();
                match root.kind() {
                    PaneRef::Split { .. } => root.id(),
                    _ => panic!("the drop must have produced a split"),
                }
            });
            let sizes = cx.read(|cx| area.read(cx).splits[&split].entity.read(cx).sizes().clone());

            assert_eq!(sizes.len(), 2, "{placement:?}: the drop splits in two");
            let (first, second) = (sizes[0].as_f32(), sizes[1].as_f32());
            assert!(
                (first - second).abs() <= (first + second) * 0.02,
                "{placement:?}: expected halves, got {first} and {second}"
            );
        }
    }

    /// A slot given an explicit size keeps it on the frame after the first.
    ///
    /// The layout is laid out once with a flexible sibling, and the flexible
    /// slot's placeholder measurement used to drag the fixed one with it when
    /// the container was first measured — the layout visibly jumped once,
    /// then settled.
    #[gpui::test]
    fn an_explicit_slot_size_survives_the_first_layout_pass(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        cx.update(|window, cx| {
            let sidebar = TestPanel::new("Sidebar", cx);
            let content = TestPanel::new("Content", cx);
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::h_split()
                        .child(DockLayout::tabs().panel(sidebar), Some(px(200.)))
                        .child(DockLayout::tabs().panel(content), None),
                    window,
                    cx,
                );
            });
        });
        cx.run_until_parked();

        let root = cx.read(|cx| {
            area.read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .root()
                .id()
        });
        let sizes = cx.read(|cx| area.read(cx).splits[&root].entity.read(cx).sizes().clone());

        // Within a couple of pixels of what was asked for — the measured
        // value carries the frame's own rounding. The bug this pins made it
        // 587px.
        let fixed = sizes
            .first()
            .copied()
            .expect("the split has slots")
            .as_f32();
        assert!(
            (fixed - 200.).abs() <= 4.,
            "the fixed slot keeps its 200px instead of being rescaled by the \
             flexible sibling's placeholder, got {fixed}"
        );
    }

    /// A panel that draws a measurable box, so a test can read where a slot
    /// actually landed rather than what `ResizableState` believes about it.
    struct MeasuredPanel {
        name: &'static str,
        focus_handle: FocusHandle,
    }

    impl MeasuredPanel {
        fn new(name: &'static str, cx: &mut App) -> Entity<Self> {
            cx.new(|cx| Self {
                name,
                focus_handle: cx.focus_handle(),
            })
        }
    }

    impl Panel for MeasuredPanel {
        fn panel_name(&self) -> &'static str {
            self.name
        }
    }

    impl EventEmitter<PanelEvent> for MeasuredPanel {}

    impl Focusable for MeasuredPanel {
        fn focus_handle(&self, _: &App) -> FocusHandle {
            self.focus_handle.clone()
        }
    }

    impl Render for MeasuredPanel {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            let name = self.name;
            div().size_full().debug_selector(move || name.into())
        }
    }

    fn draw_frames(cx: &mut VisualTestContext, frames: usize) {
        for _ in 0..frames {
            cx.update(|window, cx| window.draw(cx).clear(cx));
        }
    }

    /// Switching a tab edits one group, yet `commit` reconciles every
    /// container. Reconciling a split the edit did not touch re-adopted the
    /// tree's `None` for its flexible slot, un-pinning the size the first
    /// layout pass had measured for it, so the split re-flexed from scratch
    /// and its sized neighbour shrank. This is the dock example's left column
    /// getting shorter on every tab click in the bottom dock.
    #[gpui::test]
    fn switching_a_tab_leaves_an_untouched_split_where_it_was_drawn(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::tabs().panel(TestPanel::new("Center", cx)),
                    window,
                    cx,
                );
                area.set_dock(
                    DockPlacement::Left,
                    DockLayout::v_split()
                        .child(
                            DockLayout::tabs().panel(MeasuredPanel::new("upper-left", cx)),
                            None,
                        )
                        .child(
                            DockLayout::tabs().panel(MeasuredPanel::new("lower-left", cx)),
                            Some(px(360.)),
                        ),
                    window,
                    cx,
                );
                area.set_dock_size(DockPlacement::Left, px(350.), window, cx);
                area.set_dock(
                    DockPlacement::Bottom,
                    DockLayout::tabs()
                        .panel(TestPanel::new("Tooltip", cx))
                        .panel(TestPanel::new("Icon", cx)),
                    window,
                    cx,
                );
                area.set_dock_size(DockPlacement::Bottom, px(200.), window, cx);
            });
        });
        cx.run_until_parked();
        draw_frames(cx, 3);
        let before = (
            cx.debug_bounds("upper-left").unwrap(),
            cx.debug_bounds("lower-left").unwrap(),
        );

        let bottom = cx.read(|cx| {
            area.read(cx)
                .layout(DockPlacement::Bottom)
                .unwrap()
                .root()
                .id()
        });
        let group = cx.read(|cx| area.read(cx).groups[&bottom].entity.clone());
        cx.update(|window, cx| {
            group.update(cx, |group, cx| group.select_tab(1, window, cx));
        });
        cx.run_until_parked();
        draw_frames(cx, 3);
        let after = (
            cx.debug_bounds("upper-left").unwrap(),
            cx.debug_bounds("lower-left").unwrap(),
        );

        assert_eq!(
            before, after,
            "a tab change in the bottom dock must not move the left split"
        );
    }

    /// The other way a reconcile could move an untouched split: its file holds
    /// pixels measured in some other window, the first layout pass rescaled
    /// the state to the container it actually has, and handing the file's
    /// pixels back on a tab change slides the divider to a third position.
    #[gpui::test]
    fn switching_a_tab_keeps_a_restored_split_at_its_rescaled_share(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::h_split()
                        .child(
                            DockLayout::tabs()
                                .panel(TestPanel::new("Alpha", cx))
                                .panel(TestPanel::new("Beta", cx)),
                            Some(px(620.)),
                        )
                        .child(
                            DockLayout::tabs().panel(MeasuredPanel::new("second", cx)),
                            Some(px(350.)),
                        ),
                    window,
                    cx,
                );
            });
        });
        cx.run_until_parked();
        draw_frames(cx, 3);
        // The second slot's box tells where the divider is: its left edge is
        // the first slot's width, and the two add up to the container.
        let before = cx.debug_bounds("second").unwrap();
        assert_ne!(
            before.right(),
            px(970.),
            "the window must not match the recorded total, or this test cannot \
             tell a rescaled split from the file's pixels"
        );

        let group = group_of(&area, 0, cx);
        cx.update(|window, cx| {
            group.update(cx, |group, cx| group.select_tab(1, window, cx));
        });
        cx.run_until_parked();
        draw_frames(cx, 3);
        let after = cx.debug_bounds("second").unwrap();

        assert_eq!(
            before, after,
            "a tab change must not hand the file's pixels back to the split"
        );
    }

    /// The headline claim of the whole extraction, in one place: a layout
    /// written by the shipped dock loads into the tree world, draws, and saves
    /// back to a state the next load reproduces exactly.
    ///
    /// The fixture is a real user's file — a two-group center plus all three
    /// docks — and its panels are not registered here, so every leaf takes the
    /// placeholder path that carries the original `PanelState` forward. That
    /// is the load-bearing half: a build that dropped an unknown panel would
    /// still reach a fixpoint, so the region assertions below check the
    /// content is *there* before the fixpoint says it is stable.
    #[gpui::test]
    fn the_shipped_fixture_survives_a_load_dump_load_round_trip(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        let fixture: DockAreaState =
            serde_json::from_str(include_str!("fixtures/layout.json")).unwrap();

        cx.update(|window, cx| area.update(cx, |area, cx| area.load(fixture, window, cx).unwrap()));
        cx.run_until_parked();
        let first = cx.read(|cx| area.read(cx).dump(cx));

        assert_eq!(first.center.children.len(), 2, "the center's two groups");
        assert_eq!(first.center.children[0].children.len(), 15);
        assert_eq!(first.center.children[1].children.len(), 1);
        for dock in [&first.left_dock, &first.bottom_dock, &first.right_dock] {
            let dock = dock.as_ref().expect("all three docks are attached");
            assert!(dock.open());
            assert!(
                !dock.panel().children.is_empty(),
                "a dock that loaded empty would round-trip just as stably"
            );
        }
        assert_eq!(first.left_dock.as_ref().unwrap().size(), px(350.));
        assert_eq!(first.bottom_dock.as_ref().unwrap().size(), px(200.));
        assert_eq!(first.right_dock.as_ref().unwrap().size(), px(320.));

        cx.update(|window, cx| {
            area.update(cx, |area, cx| area.load(first.clone(), window, cx).unwrap())
        });
        cx.run_until_parked();
        let second = cx.read(|cx| area.read(cx).dump(cx));

        assert_eq!(second, first, "dump == dump(load(dump))");
    }

    #[gpui::test]
    fn an_unregistered_panel_survives_a_load_and_save_round_trip(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        cx.update(|_, cx| register_test_panels(cx));

        let json = include_str!("fixtures/unregistered_panel.json");
        let state: DockAreaState = serde_json::from_str(json).unwrap();

        cx.update(|window, cx| area.update(cx, |area, cx| area.load(state, window, cx).unwrap()));
        let dumped = cx.read(|cx| area.read(cx).dump(cx));

        let leaf = &dumped.center.children[0].children[0];
        assert_eq!(leaf.panel_name, "PanelFromTheFuture");
        assert_eq!(
            leaf.info,
            PanelInfo::panel(serde_json::json!({"keep": "me"})),
            "a panel this build cannot construct keeps its payload"
        );
    }

    #[gpui::test]
    fn a_dock_carries_its_own_tree_and_survives_a_round_trip(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        cx.update(|window, cx| {
            let alpha = TestPanel::new("Alpha", cx);
            let beta = TestPanel::new("Beta", cx);
            area.update(cx, |area, cx| {
                area.set_center(DockLayout::tabs().panel(alpha), window, cx);
                area.set_dock(
                    DockPlacement::Left,
                    DockLayout::tabs().panel(beta),
                    window,
                    cx,
                );
            });
        });

        // Node ids are globally allocated, so the center and the dock never
        // claim the same entity-cache slot.
        //
        // Comparing the two *roots* would not pin this: under a per-tree
        // counter the center's root is minted after its tab group and the
        // dock's is not, so the roots differ anyway. The collision is between
        // the two trees' tab-group nodes, and the property the cache actually
        // depends on is that no id is shared at all.
        let center_ids = cx.read(|cx| {
            area.read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .node_ids()
        });
        let dock_ids = cx.read(|cx| {
            area.read(cx)
                .layout(DockPlacement::Left)
                .unwrap()
                .node_ids()
        });
        assert!(!center_ids.is_empty() && !dock_ids.is_empty());
        assert!(
            center_ids.iter().all(|id| !dock_ids.contains(id)),
            "every tree in one area must draw from one id space: \
             center {center_ids:?} vs left {dock_ids:?}"
        );

        let state = cx.read(|cx| area.read(cx).dump(cx));
        let left = state.left_dock.clone().expect("the left dock is written");
        assert_eq!(left.placement(), DockPlacement::Left);
        assert!(left.open());
        assert_eq!(left.panel().children[0].panel_name, "Beta");
        assert!(state.right_dock.is_none());
    }

    #[gpui::test]
    fn a_panel_moved_between_regions_keeps_its_active_state(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, alpha, cx) = two_groups(&log, cx);
        cx.run_until_parked();
        // Alpha is the displayed tab of its own group, so it has been told
        // `true` exactly once.
        assert!(drain(&log).contains(&("Alpha", PanelSignal::Active(true))));

        move_alpha_into_the_other_group(&area, &alpha, cx);

        assert!(
            !drain(&log).contains(&("Alpha", PanelSignal::Active(true))),
            "a displayed panel dragged to another group must not be told `true` twice"
        );
    }

    #[gpui::test]
    fn a_groups_close_intent_reaches_the_tree(cx: &mut TestAppContext) {
        // Nothing else here proves `DockArea` subscribes to `TabGroupEvent`
        // at all: a group reports intents and does nothing itself, so an
        // unsubscribed area is a dock region that silently does nothing.
        let log = log_of();
        let (area, alpha, cx) = two_groups(&log, cx);
        cx.run_until_parked();
        drain(&log);

        let node = child_node(&area, 0, cx);
        let alpha_id = panel_id_of(&alpha);
        cx.update(|_, cx| {
            let group = area.read(cx).groups.get(&node).unwrap().entity.clone();
            group.update(cx, |group, cx| group.close_panel(alpha_id, cx));
        });
        cx.run_until_parked();

        assert!(
            cx.read(|cx| area
                .read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .find_panel_node(alpha_id))
                .is_none(),
            "the close intent was applied to the tree"
        );
        assert!(drain(&log).contains(&("Alpha", PanelSignal::Removed)));
    }

    #[gpui::test]
    fn replacing_the_center_tells_the_panels_that_left(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, _alpha, cx) = two_groups(&log, cx);
        cx.run_until_parked();
        drain(&log);

        cx.update(|window, cx| {
            let gamma = TestPanel::new("Gamma", cx);
            area.update(cx, |area, cx| {
                area.set_center(DockLayout::tabs().panel(gamma), window, cx)
            });
        });
        cx.run_until_parked();

        let seen = drain(&log);
        assert!(seen.contains(&("Alpha", PanelSignal::Removed)));
        assert!(seen.contains(&("Beta", PanelSignal::Removed)));
    }

    #[gpui::test]
    fn closing_a_zoomed_panel_clears_the_zoom(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, alpha, cx) = two_groups(&log, cx);
        cx.run_until_parked();

        let node = child_node(&area, 0, cx);
        cx.update(|window, cx| area.update(cx, |area, cx| area.set_zoomed_in(node, window, cx)));
        assert!(cx.read(|cx| area.read(cx).is_zoomed()));

        cx.update(|window, cx| {
            area.update(cx, |area, cx| area.remove_panel(alpha.clone(), window, cx))
        });

        assert!(
            !cx.read(|cx| area.read(cx).is_zoomed()),
            "a zoomed panel that left the dock must not keep filling it"
        );
    }

    /// A canvas region is the one shape `add_panel` cannot merge into a tab
    /// group, and the old `DockItem::add_panel` gave it its own arm. Without
    /// one, the `None` fallback splits the region and wraps the whole canvas
    /// in a stack the user never asked for.
    #[gpui::test]
    fn adding_a_panel_to_a_tiles_region_lands_on_the_canvas(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        let bounds = Bounds {
            origin: gpui::point(px(40.), px(40.)),
            size: gpui::size(px(200.), px(150.)),
        };
        let beta = cx.update(|window, cx| {
            let alpha = TestPanel::new("Alpha", cx);
            let beta = TestPanel::new("Beta", cx);
            area.update(cx, |area, cx| {
                area.set_center(DockLayout::tiles().tile(alpha, bounds), window, cx);
                area.add_panel(beta.clone(), DockPlacement::Center, None, window, cx);
            });
            beta
        });
        cx.run_until_parked();

        let canvas_node = child_node(&area, 0, cx);
        let panels = cx.read(|cx| {
            let PaneRef::Tiles { panels } = area
                .read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .find_node(canvas_node)
                .expect("the canvas is still there, not split in two")
                .kind()
            else {
                panic!("the region is still a tiles canvas");
            };
            panels.to_vec()
        });
        assert_eq!(panels.len(), 2, "the panel joined the canvas as a tile");

        // Registration, not just placement: a tile the area holds no view for
        // is dropped by the next `reconcile` and persists as an empty name.
        let beta_id = panel_id_of(&beta);
        assert!(
            cx.read(|cx| area.read(cx).panel(beta_id).is_some()),
            "the added panel's view is registered"
        );
        let state = cx.read(|cx| area.read(cx).dump(cx));
        let names: Vec<&str> = state
            .center
            .children
            .iter()
            .map(|child| child.panel_name.as_str())
            .collect();
        assert_eq!(names, vec!["Alpha", "Beta"]);
    }

    /// The bounds are the whole point of this entry: a host acting on
    /// `DockEvent::DragDrop { target: DropTarget::Canvas }` knows where the
    /// drop landed and has no other way to say so.
    #[gpui::test]
    fn add_tile_places_the_panel_where_it_was_asked_to(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        let first = Bounds {
            origin: gpui::point(px(10.), px(10.)),
            size: gpui::size(px(100.), px(100.)),
        };
        let dropped = Bounds {
            origin: gpui::point(px(320.), px(180.)),
            size: gpui::size(px(240.), px(160.)),
        };
        let beta = cx.update(|window, cx| {
            let alpha = TestPanel::new("Alpha", cx);
            let beta = TestPanel::new("Beta", cx);
            area.update(cx, |area, cx| {
                area.set_center(DockLayout::tiles().tile(alpha, first), window, cx);
                area.add_tile(beta.clone(), DockPlacement::Center, dropped, window, cx);
            });
            beta
        });
        cx.run_until_parked();

        let beta_id = panel_id_of(&beta);
        let canvas_node = child_node(&area, 0, cx);
        let tile = cx.read(|cx| {
            let PaneRef::Tiles { panels } = area
                .read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .find_node(canvas_node)
                .unwrap()
                .kind()
            else {
                panic!("the region is still a tiles canvas");
            };
            *panels.iter().find(|tile| tile.panel() == beta_id).unwrap()
        });
        assert_eq!(tile.bounds(), dropped);
        assert!(
            cx.read(|cx| area.read(cx).panel(beta_id).is_some()),
            "the added panel's view is registered"
        );
    }

    /// An explicit tile names a place only a canvas has. Falling through to
    /// the tab-group arm would put the panel somewhere the caller never asked
    /// for and drop the bounds on the floor.
    #[gpui::test]
    fn add_tile_does_nothing_to_a_region_with_no_canvas(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, _, cx) = one_group(&log, &["Alpha"], None, cx);
        let bounds = Bounds {
            origin: gpui::point(px(10.), px(10.)),
            size: gpui::size(px(100.), px(100.)),
        };
        let beta = cx.update(|window, cx| {
            let beta = TestPanel::new("Beta", cx);
            area.update(cx, |area, cx| {
                area.add_tile(beta.clone(), DockPlacement::Center, bounds, window, cx);
            });
            beta
        });
        cx.run_until_parked();

        let beta_id = panel_id_of(&beta);
        assert!(
            cx.read(|cx| area.read(cx).panel(beta_id).is_none()),
            "a panel nothing took must not linger in the view map"
        );
        let state = cx.read(|cx| area.read(cx).dump(cx));
        assert_eq!(state.center.children[0].children.len(), 1);

        // Nor does asking a dock that does not exist conjure an empty one to
        // decline the tile from.
        cx.update(|window, cx| {
            let gamma = TestPanel::new("Gamma", cx);
            area.update(cx, |area, cx| {
                area.add_tile(gamma, DockPlacement::Left, bounds, window, cx);
            });
        });
        cx.run_until_parked();
        assert!(
            cx.read(|cx| area.read(cx).layout(DockPlacement::Left).is_none()),
            "a tile with nowhere to go must not leave a dock behind"
        );
    }

    /// The call `add_tile` was written for is a host re-placing a panel it
    /// already holds, so a failed one must leave that panel exactly as it
    /// found it. Registering first and removing on failure would drop the view
    /// of a panel still sitting in a tree, which `reconcile`'s `views_of`
    /// asserts against in dev and answers with a shifted active index in
    /// release.
    #[gpui::test]
    fn a_declined_add_leaves_an_already_docked_panel_untouched(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, panels, cx) = one_group(&log, &["Alpha"], None, cx);
        let alpha = panels[0].clone();
        let alpha_id = panel_id_of(&alpha);
        let bounds = Bounds {
            origin: gpui::point(px(10.), px(10.)),
            size: gpui::size(px(100.), px(100.)),
        };

        let registered = cx.read(|cx| {
            Arc::as_ptr(
                area.read(cx)
                    .panel(alpha_id)
                    .expect("one_group registers it"),
            ) as *const ()
        });

        // The center is a tab group, so there is no canvas to take the tile.
        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.add_tile(alpha.clone(), DockPlacement::Center, bounds, window, cx);
            });
        });
        cx.run_until_parked();

        let handle = |cx: &mut VisualTestContext| {
            cx.read(|cx| {
                Arc::as_ptr(area.read(cx).panel(alpha_id).expect("still registered")) as *const ()
            })
        };
        assert_eq!(
            handle(cx),
            registered,
            "a panel that was already docked keeps the very handle it was \
             registered with; `add_tile` takes a bare entity, so overwriting \
             would cost a panel installed through `add_panel_view` its title"
        );
        assert!(
            cx.read(|cx| area
                .read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .find_panel_node(alpha_id))
                .is_some(),
            "and keeps its place in the tree"
        );
        assert!(
            !drain(&log).contains(&("Alpha", PanelSignal::Removed)),
            "a declined add is not a removal"
        );

        // The whole dock still reconciles, which is the failure `views_of`
        // would otherwise assert on.
        let state = cx.read(|cx| area.read(cx).dump(cx));
        assert_eq!(state.center.children[0].children[0].panel_name, "Alpha");
    }

    #[gpui::test]
    fn dragging_a_tile_writes_its_new_bounds_back_into_the_tree(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        let bounds = Bounds {
            origin: gpui::point(px(40.), px(40.)),
            size: gpui::size(px(200.), px(150.)),
        };
        let alpha = cx.update(|window, cx| {
            let alpha = TestPanel::new("Alpha", cx);
            area.update(cx, |area, cx| {
                area.set_center(DockLayout::tiles().tile(alpha.clone(), bounds), window, cx);
            });
            alpha
        });

        let node = cx.read(|cx| {
            area.read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .root()
                .id()
        });
        // A `RootKind::Split` center wraps the canvas, so the canvas is the
        // wrapper's only child.
        let canvas_node = child_node(&area, 0, cx);
        assert_ne!(node, canvas_node);
        let canvas = cx.read(|cx| {
            area.read(cx)
                .tiles
                .get(&canvas_node)
                .unwrap()
                .entity
                .clone()
        });

        // A drag of exactly one grid step, far from every other edge, so no
        // snapping rewrites it.
        cx.update(|window, cx| {
            let tile = canvas.read(cx).tiles(cx)[0].clone();
            tile.begin_move(gpui::point(px(100.), px(100.)), window, cx);
            tile.move_to(gpui::point(px(150.), px(100.)), window, cx);
            tile.end_move(window, cx);
        });

        let node = cx.read(|cx| {
            area.read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .find_node(canvas_node)
                .unwrap()
                .clone()
        });
        let PaneRef::Tiles { panels } = node.kind() else {
            panic!("expected a tiles node");
        };
        assert_eq!(panels[0].panel(), panel_id_of(&alpha));
        assert_eq!(
            panels[0].bounds().origin.x,
            px(90.),
            "the canvas reports the move and the tree records it"
        );
    }

    /// The skin's stand-in for a panel this build cannot construct. It keeps
    /// the original state, which is the obligation
    /// [`DockAreaRenderer::build_placeholder`] documents.
    struct SkinPlaceholder {
        state: PanelState,
        focus_handle: FocusHandle,
    }

    impl Panel for SkinPlaceholder {
        fn panel_name(&self) -> &'static str {
            "SkinPlaceholder"
        }

        fn dump(&self, _: &App) -> PanelState {
            self.state.clone()
        }
    }

    impl EventEmitter<PanelEvent> for SkinPlaceholder {}

    impl Focusable for SkinPlaceholder {
        fn focus_handle(&self, _: &App) -> FocusHandle {
            self.focus_handle.clone()
        }
    }

    impl Render for SkinPlaceholder {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            Empty
        }
    }

    struct PlaceholderSkin {
        asked: Rc<std::cell::RefCell<Vec<String>>>,
    }

    impl DockAreaRenderer for PlaceholderSkin {
        fn build_placeholder(
            &self,
            state: &PanelState,
            _: &mut Window,
            cx: &mut App,
        ) -> Option<Arc<dyn PanelView>> {
            self.asked.borrow_mut().push(state.panel_name.clone());
            let state = state.clone();
            Some(Arc::new(cx.new(|cx| SkinPlaceholder {
                state,
                focus_handle: cx.focus_handle(),
            })))
        }

        fn tab_group_renderer(&self) -> Rc<dyn TabGroupRenderer> {
            Rc::new(BareTabGroup)
        }

        fn tiles_renderer(&self) -> Rc<dyn TilesRenderer> {
            Rc::new(BareTiles)
        }
    }

    /// A panel no builder answers for becomes the skin's placeholder rather
    /// than base's draw-nothing one, so the "unknown panel" message the old
    /// `InvalidPanel` drew has somewhere to live.
    #[gpui::test]
    fn an_unbuildable_panel_becomes_the_skins_placeholder(cx: &mut TestAppContext) {
        cx.update(|cx| {
            let _ = crate::Theme::global_mut(cx);
        });
        let asked: Rc<std::cell::RefCell<Vec<String>>> = Rc::default();
        let skin = Rc::new(PlaceholderSkin {
            asked: asked.clone(),
        });
        let (area, cx) = cx.add_window_view(|window, cx| {
            DockArea::new("test-dock", None, window, cx).with_renderer(skin)
        });

        // Nothing is registered, so the round trip cannot rebuild this panel.
        cx.update(|window, cx| {
            let ghost = TestPanel::new("Ghost", cx);
            area.update(cx, |area, cx| {
                area.set_center(DockLayout::tabs().panel(ghost), window, cx)
            });
        });
        let state = cx.read(|cx| area.read(cx).dump(cx));
        cx.update(|window, cx| area.update(cx, |area, cx| area.load(state, window, cx).unwrap()));
        cx.run_until_parked();

        assert_eq!(*asked.borrow(), vec!["Ghost".to_string()]);
        assert_eq!(
            cx.read(|cx| area
                .read(cx)
                .panels
                .values()
                .map(|panel| panel.panel_name(cx))
                .collect::<Vec<_>>()),
            vec!["SkinPlaceholder"],
            "base installed the skin's placeholder, not its own"
        );
        assert_eq!(
            cx.read(|cx| area.read(cx).dump(cx)).center.children[0].children[0].panel_name,
            "Ghost",
            "and the unknown panel still survives the next save"
        );
    }

    #[gpui::test]
    fn a_persisted_tiles_canvas_restores_its_panels(cx: &mut TestAppContext) {
        // Every tiles canvas the old dock ever wrote has `TabPanel`-shaped
        // children. Read literally, each one misses the registry, becomes a
        // placeholder, and the user's panels inside it are never built at
        // all — a saved canvas comes back as blank tiles.
        let (area, cx) = setup(cx);
        cx.update(|_, cx| register_test_panels(cx));

        let json = include_str!("fixtures/tiles_tab_panel_children.json");
        let state: DockAreaState = serde_json::from_str(json).unwrap();
        cx.update(|window, cx| area.update(cx, |area, cx| area.load(state, window, cx).unwrap()));

        let dumped = cx.read(|cx| area.read(cx).dump(cx));
        let tiles = &dumped.center;
        assert_eq!(tiles.panel_name, "Tiles");
        assert_eq!(
            tiles
                .children
                .iter()
                .map(|child| child.panel_name.as_str())
                .collect::<Vec<_>>(),
            vec!["Alpha", "Beta", "Gamma"],
            "the real panels are restored, not `InvalidPanel` placeholders"
        );

        // And they are live entities the canvas can draw, not just bytes.
        let canvas_node = child_node(&area, 0, cx);
        let canvas = cx.read(|cx| {
            area.read(cx)
                .tiles
                .get(&canvas_node)
                .unwrap()
                .entity
                .clone()
        });
        let names = cx.read(|cx| {
            canvas
                .read(cx)
                .tiles(cx)
                .iter()
                .map(|tile| tile.panel().panel_name(cx))
                .collect::<Vec<_>>()
        });
        assert_eq!(names, vec!["Alpha", "Beta", "Gamma"]);
    }

    #[gpui::test]
    fn removing_a_non_tail_child_shifts_the_split_sizes_with_it(cx: &mut TestAppContext) {
        // `ResizableState` keeps the authoritative size on `panels[ix]`, so a
        // tail-truncating sync leaves the survivors of a non-tail removal
        // wearing their predecessors' widths.
        let log = log_of();
        let (area, cx) = setup(cx);
        let alpha = cx.update(|window, cx| {
            let alpha = TestPanel::logging("Alpha", &log, cx);
            let beta = TestPanel::logging("Beta", &log, cx);
            let gamma = TestPanel::logging("Gamma", &log, cx);
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::h_split()
                        .child(DockLayout::tabs().panel(alpha.clone()), Some(px(100.)))
                        .child(DockLayout::tabs().panel(beta), Some(px(200.)))
                        .child(DockLayout::tabs().panel(gamma), Some(px(300.))),
                    window,
                    cx,
                );
            });
            alpha
        });

        let root = cx.read(|cx| {
            area.read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .root()
                .id()
        });
        let split = cx.read(|cx| area.read(cx).splits.get(&root).unwrap().entity.clone());
        let sizes = |cx: &mut VisualTestContext| cx.read(|cx| split.read(cx).sizes().clone());

        // Absolute widths are `ResizableState`'s business — it redistributes
        // against the measured container — so what is asserted is which slot
        // disappeared, through the ratio the survivors keep.
        let before = sizes(cx);
        assert_eq!(before.len(), 3);
        let kept_if_correct = before[1] / before[2];
        let kept_if_truncated = before[0] / before[1];
        assert!(
            (kept_if_correct - kept_if_truncated).abs() > 0.1,
            "the fixture must be able to tell the two outcomes apart"
        );

        cx.update(|window, cx| area.update(cx, |area, cx| area.remove_panel(alpha, window, cx)));

        let after = sizes(cx);
        assert_eq!(after.len(), 2);
        assert!(
            (after[0] / after[1] - kept_if_correct).abs() < 0.01,
            "the survivors kept their own proportions: slot 0 was removed, not \
             the tail — got {after:?} from {before:?}"
        );
    }

    #[gpui::test]
    fn a_panel_moves_between_the_center_and_a_dock(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, alpha, cx) = two_groups(&log, cx);
        cx.update(|window, cx| {
            let gamma = TestPanel::logging("Gamma", &log, cx);
            area.update(cx, |area, cx| {
                area.set_dock(
                    DockPlacement::Left,
                    DockLayout::tabs().panel(gamma),
                    window,
                    cx,
                );
            });
        });
        cx.run_until_parked();
        drain(&log);

        let alpha_id = panel_id_of(&alpha);
        let dock_group = cx.read(|cx| {
            area.read(cx)
                .layout(DockPlacement::Left)
                .unwrap()
                .root()
                .id()
        });

        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.move_panel(
                    alpha_id,
                    InsertTarget::Tabs {
                        node: dock_group,
                        ix: None,
                        activate: true,
                    },
                    window,
                    cx,
                );
            });
        });
        cx.run_until_parked();

        assert!(
            cx.read(|cx| area
                .read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .find_panel_node(alpha_id))
                .is_none(),
            "the panel left the center"
        );
        assert_eq!(
            cx.read(|cx| area
                .read(cx)
                .layout(DockPlacement::Left)
                .unwrap()
                .find_panel_node(alpha_id)),
            Some(dock_group),
            "and arrived in the dock's group"
        );

        let seen = drain(&log);
        assert!(
            !seen.contains(&("Alpha", PanelSignal::Removed)),
            "crossing regions is still a move, not a removal"
        );
        assert!(
            !seen.contains(&("Alpha", PanelSignal::Active(true))),
            "and it was displayed in both, so it is not told `true` twice"
        );
    }

    #[gpui::test]
    fn a_move_onto_an_unusable_target_leaves_no_stranded_panel(cx: &mut TestAppContext) {
        // `apply_insert` is a silent no-op when the target node's kind does
        // not match. Committing on the insert alone would early-return with
        // the panel already gone from the source tree but still in the view
        // map, for some later unrelated edit to prune and destroy.
        let log = log_of();
        let (area, _alpha, cx) = two_groups(&log, cx);
        let gamma = cx.update(|window, cx| {
            let gamma = TestPanel::logging("Gamma", &log, cx);
            area.update(cx, |area, cx| {
                area.set_dock(
                    DockPlacement::Left,
                    DockLayout::tabs().panel(gamma.clone()),
                    window,
                    cx,
                );
            });
            gamma
        });
        cx.run_until_parked();
        drain(&log);

        let gamma_id = panel_id_of(&gamma);
        // The center root is a split, so a `Tabs` insert naming it does
        // nothing at all.
        let center_root = cx.read(|cx| {
            area.read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .root()
                .id()
        });

        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.move_panel(
                    gamma_id,
                    InsertTarget::Tabs {
                        node: center_root,
                        ix: None,
                        activate: true,
                    },
                    window,
                    cx,
                );
            });
        });
        cx.run_until_parked();

        assert!(
            cx.read(|cx| area.read(cx).panel(gamma_id).is_none()),
            "the view map agrees with the trees straight away, rather than \
             carrying a panel that belongs to no tree"
        );
        assert!(
            drain(&log).contains(&("Gamma", PanelSignal::Removed)),
            "and the panel was told so at the point of the call"
        );
    }

    #[gpui::test]
    fn an_all_hidden_container_reports_itself_invisible(cx: &mut TestAppContext) {
        // What the old `StackPanel::render` asked of each slot before hiding
        // it. `render_node` feeds this straight to `resizable_panel().visible`.
        let (area, cx) = setup(cx);
        let beta = cx.update(|window, cx| {
            let alpha = TestPanel::new("Alpha", cx);
            let beta = TestPanel::new("Beta", cx);
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::h_split()
                        .child(DockLayout::tabs().panel(alpha), None)
                        .child(DockLayout::tabs().panel(beta.clone()), None),
                    window,
                    cx,
                );
            });
            beta
        });

        let visible = |ix: usize, cx: &mut VisualTestContext| {
            let node = child_node(&area, ix, cx);
            cx.read(|cx| {
                let area = area.read(cx);
                let tree = area.layout(DockPlacement::Center).unwrap();
                area.is_node_visible(tree.find_node(node).unwrap(), cx)
            })
        };

        assert!(visible(0, cx) && visible(1, cx));

        cx.update(|_, cx| beta.update(cx, |beta, cx| beta.set_visible(false, cx)));

        assert!(visible(0, cx), "the visible group still holds its slot");
        assert!(
            !visible(1, cx),
            "a group whose every panel is hidden must give its slot up"
        );
    }

    #[gpui::test]
    fn a_locked_area_seals_its_groups(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, _alpha, cx) = two_groups(&log, cx);
        cx.run_until_parked();

        let node = child_node(&area, 0, cx);
        let group = cx.read(|cx| area.read(cx).groups.get(&node).unwrap().entity.clone());
        assert!(
            cx.read(|cx| group.read(cx).is_closable(cx)),
            "an unlocked group's panel can be closed"
        );

        cx.update(|window, cx| area.update(cx, |area, cx| area.set_locked(true, window, cx)));

        assert!(
            !cx.read(|cx| group.read(cx).is_closable(cx)),
            "the lock reaches every group through the constraints push"
        );
    }

    // The tests below were ported from `crates/component/src/dock/tab_panel.rs` when
    // the dock skin was rebuilt on this crate. They are the surviving record
    // of the `is_empty` semantics and the documented `set_active` contract.

    /// An empty `StackPanel` used to dump as `PanelInfo::Panel`, the
    /// `PanelState` default, so restoring looked it up in `PanelRegistry` and
    /// failed.
    #[gpui::test]
    fn empty_center_round_trips_as_a_stack(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        let center = cx.read(|cx| area.read(cx).dump(cx).center);

        assert_eq!(center.panel_name, "StackPanel");
        assert!(
            matches!(center.info, PanelInfo::Stack { .. }),
            "got {:?}",
            center.info
        );
    }

    #[gpui::test]
    fn fresh_center_is_empty(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);

        assert!(
            is_center_empty(&area, cx),
            "DockArea::new starts with an empty split centre"
        );
    }

    #[gpui::test]
    fn center_holding_a_tab_group_is_not_empty(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, _panels, cx) = one_group(&log, &["A", "B"], None, cx);
        cx.run_until_parked();

        assert!(!is_center_empty(&area, cx));
    }

    /// The tree still lists the group's node here until the last panel goes,
    /// so anything reading node counts rather than panels would report
    /// non-empty.
    #[gpui::test]
    fn center_is_empty_again_once_every_panel_is_removed(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, panels, cx) = one_group(&log, &["A", "B"], None, cx);
        cx.run_until_parked();

        for panel in panels {
            cx.update(|window, cx| {
                area.update(cx, |area, cx| area.remove_panel(panel.clone(), window, cx))
            });
        }
        cx.run_until_parked();

        assert!(is_center_empty(&area, cx));
    }

    #[gpui::test]
    fn center_is_not_empty_after_adding_to_a_tab_group(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        assert!(is_center_empty(&area, cx));

        cx.update(|window, cx| {
            let alpha = TestPanel::new("Alpha", cx);
            area.update(cx, |area, cx| {
                area.add_panel(alpha, DockPlacement::Center, None, window, cx)
            });
        });
        cx.run_until_parked();

        assert!(!is_center_empty(&area, cx));
    }

    /// The pre-wrapped companion of `add_panel`, for a layer that hands base
    /// its own handle. The panel it registers is the very handle it was
    /// given, keyed by the id that handle reports.
    #[gpui::test]
    fn add_panel_view_registers_the_handle_it_was_given(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);

        let view = cx.update(|window, cx| {
            let view: Arc<dyn PanelView> = Arc::new(TestPanel::new("Alpha", cx));
            area.update(cx, |area, cx| {
                area.add_panel_view(view.clone(), DockPlacement::Center, None, window, cx)
            });
            view
        });
        cx.run_until_parked();

        let id = cx.read(|cx| view.panel_id(cx));
        assert!(
            cx.read(|cx| area
                .read(cx)
                .panel(id)
                .is_some_and(|stored| Arc::ptr_eq(stored, &view))),
            "the stored handle is the one that was handed over, under its own id"
        );
        assert!(!is_center_empty(&area, cx));
    }

    /// Rendering skips invisible panels, so a centre holding only hidden ones
    /// draws nothing and counts as empty.
    #[gpui::test]
    fn center_holding_only_hidden_panels_is_empty(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, panels, cx) = one_group(&log, &["A", "B"], None, cx);
        cx.run_until_parked();
        assert!(!is_center_empty(&area, cx));

        cx.update(|_, cx| {
            for panel in &panels {
                panel.update(cx, |panel, cx| panel.set_visible(false, cx));
            }
        });
        cx.run_until_parked();

        assert_eq!(
            cx.read(|cx| area
                .read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .panels()
                .count()),
            2,
            "hiding a panel does not remove it from the tab group"
        );
        assert!(is_center_empty(&area, cx));
    }

    /// The old `TabPanel` inside `Tiles` had no parent `StackPanel` to remove
    /// itself from, so emptying it left the tile behind and the walk had to
    /// recurse. `normalize` now removes the emptied canvas outright, which is
    /// the stronger outcome and is what this pins.
    #[gpui::test]
    fn center_holding_only_empty_tiles_is_empty(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        let bounds = Bounds {
            origin: gpui::point(px(10.), px(10.)),
            size: gpui::size(px(200.), px(200.)),
        };
        let alpha = cx.update(|window, cx| {
            let alpha = TestPanel::new("Alpha", cx);
            area.update(cx, |area, cx| {
                area.set_center(DockLayout::tiles().tile(alpha.clone(), bounds), window, cx)
            });
            alpha
        });
        cx.run_until_parked();
        assert!(!is_center_empty(&area, cx));

        cx.update(|window, cx| area.update(cx, |area, cx| area.remove_panel(alpha, window, cx)));
        cx.run_until_parked();

        assert!(is_center_empty(&area, cx));
    }

    /// The recursion the previous test no longer reaches: a canvas that still
    /// holds its tile, but whose every panel is hidden.
    #[gpui::test]
    fn center_holding_only_hidden_tiles_is_empty(cx: &mut TestAppContext) {
        let (area, cx) = setup(cx);
        let bounds = Bounds {
            origin: gpui::point(px(10.), px(10.)),
            size: gpui::size(px(200.), px(200.)),
        };
        let alpha = cx.update(|window, cx| {
            let alpha = TestPanel::new("Alpha", cx);
            area.update(cx, |area, cx| {
                area.set_center(DockLayout::tiles().tile(alpha.clone(), bounds), window, cx)
            });
            alpha
        });
        cx.run_until_parked();
        assert!(!is_center_empty(&area, cx));

        cx.update(|_, cx| alpha.update(cx, |alpha, cx| alpha.set_visible(false, cx)));

        assert_eq!(
            cx.read(|cx| area
                .read(cx)
                .layout(DockPlacement::Center)
                .unwrap()
                .panels()
                .count()),
            1,
            "the tile is still on the canvas"
        );
        assert!(is_center_empty(&area, cx));
    }

    #[gpui::test]
    fn single_panel_group_receives_initial_active(cx: &mut TestAppContext) {
        let log = log_of();
        let (_area, _panels, cx) = one_group(&log, &["A"], None, cx);
        cx.run_until_parked();

        assert_eq!(drain_active(&log), [("A", true)]);
    }

    #[gpui::test]
    fn multi_tab_construction_notifies_only_displayed_panel(cx: &mut TestAppContext) {
        let log = log_of();
        let (_area, _panels, cx) = one_group(&log, &["A", "B", "C"], None, cx);
        cx.run_until_parked();

        // No false-then-true flip on A, no duplicate true, B/C silent.
        assert_eq!(drain_active(&log), [("A", true)]);
    }

    #[gpui::test]
    fn active_index_restore_notifies_that_panel_only(cx: &mut TestAppContext) {
        let log = log_of();
        let (_area, _panels, cx) = one_group(&log, &["A", "B", "C"], Some(2), cx);
        cx.run_until_parked();

        assert_eq!(drain_active(&log), [("C", true)]);
    }

    #[gpui::test]
    fn switching_tabs_sends_false_then_true(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, _panels, cx) = one_group(&log, &["A", "B"], None, cx);
        cx.run_until_parked();
        drain(&log);

        let group = group_of(&area, 0, cx);
        cx.update(|window, cx| group.update(cx, |group, cx| group.select_tab(1, window, cx)));
        cx.run_until_parked();

        assert_eq!(drain_active(&log), [("A", false), ("B", true)]);
    }

    #[gpui::test]
    fn reselecting_active_tab_stays_silent(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, _panels, cx) = one_group(&log, &["A", "B"], None, cx);
        cx.run_until_parked();
        drain(&log);

        let group = group_of(&area, 0, cx);
        cx.update(|window, cx| group.update(cx, |group, cx| group.select_tab(0, window, cx)));
        cx.run_until_parked();

        assert_eq!(drain_active(&log), []);
    }

    /// The old `TabPanel::insert_panel_at` took a brand-new panel; the tree
    /// API inserts a panel that is already in the dock, so `C` arrives from a
    /// second group. It was a background tab there and so has been told
    /// nothing, which is what makes the arrival a genuine activation rather
    /// than a seeded handoff.
    #[gpui::test]
    fn inserting_at_active_ix_swaps_notifications(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, cx) = setup(cx);
        let c = cx.update(|window, cx| {
            let a = TestPanel::logging("A", &log, cx);
            let b = TestPanel::logging("B", &log, cx);
            let x = TestPanel::logging("X", &log, cx);
            let c = TestPanel::logging("C", &log, cx);
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::h_split()
                        .child(DockLayout::tabs().panel(a).panel(b), None)
                        .child(DockLayout::tabs().panel(x).panel(c.clone()), None),
                    window,
                    cx,
                );
            });
            c
        });
        cx.run_until_parked();
        drain(&log);

        let destination = child_node(&area, 0, cx);
        let c_id = panel_id_of(&c);
        move_panel_into(&area, c_id, destination, Some(0), true, cx);

        assert_eq!(drain_active(&log), [("A", false), ("C", true)]);
        let group = group_of(&area, 0, cx);
        assert_eq!(cx.read(|cx| group.read(cx).active_ix()), 0);
        assert_eq!(
            cx.read(|cx| group.read(cx).panels()[0].panel_id(cx)),
            c_id,
            "the arriving panel took the slot it named"
        );
    }

    #[gpui::test]
    fn removing_before_active_keeps_displayed_panel(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, panels, cx) = one_group(&log, &["A", "B", "C"], None, cx);
        let group = group_of(&area, 0, cx);
        cx.update(|window, cx| group.update(cx, |group, cx| group.select_tab(1, window, cx)));
        cx.run_until_parked();
        drain(&log);

        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.remove_panel(panels[0].clone(), window, cx)
            })
        });
        cx.run_until_parked();

        assert_eq!(drain_active(&log), []);
        assert_eq!(cx.read(|cx| group.read(cx).active_ix()), 0);
        assert_eq!(
            cx.read(|cx| group.read(cx).panels()[0].panel_id(cx)),
            panel_id_of(&panels[1]),
            "the same panel is still displayed, at its new index"
        );
    }

    /// Collapsing is now a dock closing, which is what
    /// `TabGroupConstraints::collapsed` carries.
    #[gpui::test]
    fn collapse_and_expand_notify_active_panel(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, cx) = setup(cx);
        cx.update(|window, cx| {
            let a = TestPanel::logging("A", &log, cx);
            let b = TestPanel::logging("B", &log, cx);
            area.update(cx, |area, cx| {
                area.set_dock(
                    DockPlacement::Left,
                    DockLayout::tabs().panel(a).panel(b),
                    window,
                    cx,
                );
            });
        });
        cx.run_until_parked();
        drain(&log);

        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.toggle_dock(DockPlacement::Left, window, cx)
            })
        });
        cx.run_until_parked();
        assert_eq!(drain_active(&log), [("A", false)]);

        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.toggle_dock(DockPlacement::Left, window, cx)
            })
        });
        cx.run_until_parked();
        assert_eq!(drain_active(&log), [("A", true)]);
    }

    #[gpui::test]
    fn background_add_is_silent_but_first_panel_is_not(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, cx) = setup(cx);
        let d = cx.update(|window, cx| {
            let a = TestPanel::logging("A", &log, cx);
            let b = TestPanel::logging("B", &log, cx);
            let c = TestPanel::logging("C", &log, cx);
            let d = TestPanel::logging("D", &log, cx);
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::h_split()
                        .child(DockLayout::tabs().panel(a).panel(b), None)
                        .child(DockLayout::tabs().panel(c).panel(d.clone()), None),
                    window,
                    cx,
                );
            });
            d
        });
        cx.run_until_parked();
        drain(&log);

        // D is a background tab in its own group and arrives as a background
        // tab in the other one, so nothing changes for anybody.
        let destination = child_node(&area, 0, cx);
        move_panel_into(&area, panel_id_of(&d), destination, None, false, cx);
        assert_eq!(drain_active(&log), []);

        // The first panel of a region that had none is displayed regardless,
        // so it must be told.
        cx.update(|window, cx| {
            let e = TestPanel::logging("E", &log, cx);
            area.update(cx, |area, cx| {
                area.add_panel(e, DockPlacement::Left, None, window, cx)
            });
        });
        cx.run_until_parked();
        assert_eq!(drain_active(&log), [("E", true)]);
    }

    #[gpui::test]
    fn drag_active_panel_to_other_group_stays_silent_for_it(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, cx) = setup(cx);
        let a = cx.update(|window, cx| {
            let a = TestPanel::logging("A", &log, cx);
            let b = TestPanel::logging("B", &log, cx);
            let c = TestPanel::logging("C", &log, cx);
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::h_split()
                        .child(DockLayout::tabs().panel(a.clone()).panel(b), None)
                        .child(DockLayout::tabs().panel(c), None),
                    window,
                    cx,
                );
            });
            a
        });
        cx.run_until_parked();
        drain(&log);

        // A was already told `true`; becoming the target's displayed tab must
        // not repeat it.
        let destination = child_node(&area, 1, cx);
        move_panel_into(&area, panel_id_of(&a), destination, None, true, cx);

        // Two groups reconcile independently, so their deliveries interleave
        // in no guaranteed order; what is pinned is which ones happen.
        let seen = drain_active(&log);
        assert!(seen.contains(&("B", true)), "got {seen:?}");
        assert!(seen.contains(&("C", false)), "got {seen:?}");
        assert!(
            !seen.iter().any(|(name, _)| *name == "A"),
            "the moved panel was displayed before and after: {seen:?}"
        );
    }

    #[gpui::test]
    fn drag_active_panel_to_background_slot_deactivates_it(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, cx) = setup(cx);
        let a = cx.update(|window, cx| {
            let a = TestPanel::logging("A", &log, cx);
            let c = TestPanel::logging("C", &log, cx);
            let d = TestPanel::logging("D", &log, cx);
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::h_split()
                        .child(DockLayout::tabs().panel(a.clone()), None)
                        .child(DockLayout::tabs().panel(c).panel(d), None),
                    window,
                    cx,
                );
            });
            a
        });
        cx.run_until_parked();
        drain(&log);

        // A was told `true` and becomes a background tab, so it gets one
        // `false`.
        let destination = child_node(&area, 1, cx);
        move_panel_into(&area, panel_id_of(&a), destination, None, false, cx);

        assert_eq!(drain_active(&log), [("A", false)]);
    }

    #[gpui::test]
    fn closing_a_tile_removes_its_panel(cx: &mut TestAppContext) {
        // `TileContext::is_closable` would otherwise be a control a skin can
        // draw and never wire up.
        let log = log_of();
        let (area, cx) = setup(cx);
        let bounds = Bounds {
            origin: gpui::point(px(10.), px(10.)),
            size: gpui::size(px(200.), px(200.)),
        };
        let alpha = cx.update(|window, cx| {
            let alpha = TestPanel::logging("Alpha", &log, cx);
            let beta = TestPanel::logging("Beta", &log, cx);
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::tiles()
                        .tile(alpha.clone(), bounds)
                        .tile(beta, bounds),
                    window,
                    cx,
                );
            });
            alpha
        });
        cx.run_until_parked();
        drain(&log);

        let canvas_node = child_node(&area, 0, cx);
        let canvas = cx.read(|cx| {
            area.read(cx)
                .tiles
                .get(&canvas_node)
                .unwrap()
                .entity
                .clone()
        });
        cx.update(|window, cx| {
            let tile = canvas.read(cx).tiles(cx)[0].clone();
            assert!(tile.is_closable());
            tile.close(window, cx);
        });
        cx.run_until_parked();

        assert!(
            cx.read(|cx| area.read(cx).panel(panel_id_of(&alpha)).is_none()),
            "the closed tile's panel left the dock"
        );
        assert!(drain(&log).contains(&("Alpha", PanelSignal::Removed)));
    }

    /// A skin that records what it was asked to draw.
    ///
    /// The chrome is the point: a tab bar is drawn by the *group*, and a
    /// tile's drag bar by the *canvas*. Neither runs if the area renders the
    /// bare panel instead, so what lands in these logs says which of the two
    /// is on screen — a question no reading of `is_zoomed()` can answer.
    struct RecordingSkin {
        tab_bars: Rc<RefCell<Vec<NodeId>>>,
        drag_bars: Rc<RefCell<Vec<PanelId>>>,
    }

    struct RecordingTabGroup {
        drawn: Rc<RefCell<Vec<NodeId>>>,
    }

    struct RecordingTiles {
        drawn: Rc<RefCell<Vec<PanelId>>>,
    }

    impl DockAreaRenderer for RecordingSkin {
        fn tab_group_renderer(&self) -> Rc<dyn TabGroupRenderer> {
            Rc::new(RecordingTabGroup {
                drawn: self.tab_bars.clone(),
            })
        }

        fn tiles_renderer(&self) -> Rc<dyn TilesRenderer> {
            Rc::new(RecordingTiles {
                drawn: self.drag_bars.clone(),
            })
        }
    }

    impl TabGroupRenderer for RecordingTabGroup {
        fn render_tab_bar(
            &self,
            group: &TabGroupContext,
            _: &mut Window,
            _: &mut App,
        ) -> AnyElement {
            self.drawn.borrow_mut().push(group.node());
            Empty.into_any_element()
        }
    }

    impl TilesRenderer for RecordingTiles {
        fn render_drag_bar(&self, tile: &TileContext, _: &mut Window, _: &mut App) -> AnyElement {
            self.drawn.borrow_mut().push(tile.panel_id());
            Empty.into_any_element()
        }
    }

    type DrawLog = (Rc<RefCell<Vec<NodeId>>>, Rc<RefCell<Vec<PanelId>>>);

    /// [`setup`], with a skin that records the tab bars and drag bars drawn.
    fn setup_recording(
        cx: &mut TestAppContext,
    ) -> (Entity<DockArea>, DrawLog, &mut VisualTestContext) {
        cx.update(|cx| {
            let _ = crate::Theme::global_mut(cx);
        });
        let tab_bars: Rc<RefCell<Vec<NodeId>>> = Rc::default();
        let drag_bars: Rc<RefCell<Vec<PanelId>>> = Rc::default();
        let skin = Rc::new(RecordingSkin {
            tab_bars: tab_bars.clone(),
            drag_bars: drag_bars.clone(),
        });
        let (area, cx) = cx.add_window_view(|window, cx| {
            DockArea::new("test-dock", None, window, cx).with_renderer(skin)
        });
        (area, (tab_bars, drag_bars), cx)
    }

    fn zoom_signals(log: &Log) -> Vec<(&'static str, PanelSignal)> {
        drain(log)
            .into_iter()
            .filter(|(_, signal)| matches!(signal, PanelSignal::Zoomed(_)))
            .collect()
    }

    /// The regression this exists for: zooming shows the *group*, tab bar and
    /// all, not the panel inside it.
    ///
    /// The old dock zoomed the whole `TabPanel` — every `subscribe_panel` call
    /// site handed it one — so the tab bar, the toolbar and the panel menu
    /// stayed on screen, and that is where the control that zooms back out
    /// lives. A zoom rendering the bare panel would still fill the area and
    /// still answer `is_zoomed()`; only the tab bar tells the two apart.
    #[gpui::test]
    fn a_zoomed_group_is_drawn_whole_rather_than_as_its_bare_panel(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, (tab_bars, _), cx) = setup_recording(cx);
        cx.update(|window, cx| {
            let alpha = TestPanel::logging("Alpha", &log, cx);
            let beta = TestPanel::logging("Beta", &log, cx);
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::h_split()
                        .child(DockLayout::tabs().panel(alpha), None)
                        .child(DockLayout::tabs().panel(beta), None),
                    window,
                    cx,
                );
            });
        });
        cx.run_until_parked();

        let zoomed = child_node(&area, 0, cx);
        let other = child_node(&area, 1, cx);
        assert!(
            tab_bars.borrow().contains(&zoomed) && tab_bars.borrow().contains(&other),
            "both groups draw their own tab bar while nothing is zoomed"
        );

        tab_bars.borrow_mut().clear();
        let group = group_of(&area, 0, cx);
        cx.update(|window, cx| group.update(cx, |group, cx| group.toggle_zoom(window, cx)));
        cx.run_until_parked();

        assert!(
            tab_bars.borrow().contains(&zoomed),
            "a zoomed group is rendered whole: its own tab bar is still drawn, \
             which is exactly what the bare panel does not carry"
        );
        assert!(
            !tab_bars.borrow().contains(&other),
            "and it is the only thing on screen"
        );
    }

    /// Zooming a tile shows its canvas drawing that one tile with its chrome.
    ///
    /// A tile was a `TabPanel` in the old dock, so it zoomed with its own bar
    /// too. The canvas is what draws a tile's chrome, so the canvas is what
    /// the area renders.
    #[gpui::test]
    fn a_zoomed_tile_is_drawn_by_its_canvas_with_its_chrome(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, (_, drag_bars), cx) = setup_recording(cx);
        let bounds = Bounds {
            origin: gpui::point(px(40.), px(40.)),
            size: gpui::size(px(200.), px(150.)),
        };
        let (alpha, beta) = cx.update(|window, cx| {
            let alpha = TestPanel::logging("Alpha", &log, cx);
            let beta = TestPanel::logging("Beta", &log, cx);
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::tiles()
                        .tile(alpha.clone(), bounds)
                        .tile(beta.clone(), bounds),
                    window,
                    cx,
                );
            });
            (alpha, beta)
        });
        cx.run_until_parked();
        drain(&log);

        let canvas_node = child_node(&area, 0, cx);
        let canvas = cx.read(|cx| {
            area.read(cx)
                .tiles
                .get(&canvas_node)
                .unwrap()
                .entity
                .clone()
        });
        assert!(
            drag_bars.borrow().contains(&panel_id_of(&alpha))
                && drag_bars.borrow().contains(&panel_id_of(&beta)),
            "both tiles draw their own drag bar while nothing is zoomed"
        );

        drag_bars.borrow_mut().clear();
        cx.update(|window, cx| {
            let tile = canvas.read(cx).tiles(cx)[0].clone();
            assert!(tile.is_zoomable());
            tile.toggle_zoom(window, cx);
        });
        cx.run_until_parked();

        assert_eq!(
            cx.read(|cx| area.read(cx).zoomed_tile()),
            Some(panel_id_of(&alpha))
        );
        assert!(
            drag_bars.borrow().contains(&panel_id_of(&alpha)),
            "the zoomed tile keeps the chrome the bare panel does not carry"
        );
        assert!(
            !drag_bars.borrow().contains(&panel_id_of(&beta)),
            "and the tiles beside it are no longer drawn"
        );
        assert_eq!(
            zoom_signals(&log),
            vec![("Alpha", PanelSignal::Zoomed(true))],
            "the panel is told it was zoomed, as its group would have told it"
        );

        // A zoomed tile is no longer at its stored bounds, so there is
        // nothing for a move to mean — the tiles counterpart of a zoomed
        // group reporting itself locked.
        cx.update(|window, cx| {
            let tile = canvas.read(cx).tiles(cx)[0].clone();
            tile.begin_move(gpui::point(px(100.), px(100.)), window, cx);
        });
        assert!(!cx.read(|cx| canvas.read(cx).tiles(cx)[0].is_moving()));
    }

    /// The area's zoom and the container's own flag are written together, so
    /// neither can be left believing something the other does not.
    ///
    /// A group left flagged zoomed reports itself locked for good, and a
    /// locked group refuses every drop.
    #[gpui::test]
    fn clearing_the_zoom_from_outside_puts_the_groups_own_flag_back(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, _alpha, cx) = two_groups(&log, cx);
        cx.run_until_parked();
        drain(&log);

        let node = child_node(&area, 0, cx);
        let group = group_of(&area, 0, cx);
        cx.update(|window, cx| group.update(cx, |group, cx| group.toggle_zoom(window, cx)));
        cx.run_until_parked();
        assert_eq!(cx.read(|cx| area.read(cx).zoomed_group()), Some(node));
        assert!(cx.read(|cx| group.read(cx).is_zoomed()));
        assert_eq!(
            zoom_signals(&log),
            vec![("Alpha", PanelSignal::Zoomed(true))]
        );

        cx.update(|window, cx| area.update(cx, |area, cx| area.set_zoomed_out(window, cx)));
        cx.run_until_parked();

        assert!(!cx.read(|cx| area.read(cx).is_zoomed()));
        assert!(
            !cx.read(|cx| group.read(cx).is_zoomed()),
            "a group left flagged zoomed would stay locked and refuse every drop"
        );
        assert!(
            cx.read(|cx| group.read(cx).context(cx).is_droppable()),
            "and the lock the zoom imposed is lifted with it"
        );
        assert_eq!(
            zoom_signals(&log),
            vec![("Alpha", PanelSignal::Zoomed(false))],
            "the panel hears the zoom end too, not just the group"
        );
    }

    /// A group that refuses to zoom must not leave the area showing it as
    /// zoomed: the area records a zoom only once the container agrees.
    #[gpui::test]
    fn a_group_that_refuses_to_zoom_leaves_the_area_unzoomed(cx: &mut TestAppContext) {
        let log = log_of();
        let (area, alpha, cx) = two_groups(&log, cx);
        cx.run_until_parked();
        cx.update(|_, cx| alpha.update(cx, |panel, cx| panel.set_zoomable(false, cx)));

        let node = child_node(&area, 0, cx);
        let group = group_of(&area, 0, cx);
        cx.update(|window, cx| area.update(cx, |area, cx| area.set_zoomed_in(node, window, cx)));
        cx.run_until_parked();

        assert!(!cx.read(|cx| group.read(cx).is_zoomed()));
        assert!(
            !cx.read(|cx| area.read(cx).is_zoomed()),
            "the area must not fill itself with a group that never zoomed"
        );
    }
}