waft-widgets 0.18.1

Widget framework and widgets for Waft
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
//! `Element`: an instantiation of a `Widget` at a particular location in the tree.
//!
//! An element is one struct in the arena, reached through `Handle<Self>`; Dart's base-class
//! fields are the [`ElementData`] bag the struct holds under the field `element`. A reference
//! to "some element" is the type-erased handle [`AnyElement`], which is also the [`BuildContext`]
//! (Dart's `Element implements BuildContext`).
//!
//! Dart's base bodies are the free functions `base_*`; an override calls the one it would
//! call as `super`.
//!
//! Mounting and rebuilding recurse once per level of the tree, and on the web each wasm call
//! costs Safari's first tier close to a kilobyte of stack however small it is, so a deep tree
//! (the Material gallery's phone layout is about 300 levels) overflows an iPhone's stack when a
//! level costs many calls. A level costs one: the child's vtable entry. Everything between one
//! entry and the next is folded into it with `#[inline(always)]`: each element's `mount`,
//! `update`, `first_build` and `perform_rebuild` and the base bodies they forward to,
//! [`AnyElement::update_child`] and [`AnyElement::inflate_widget`] (which is why it is not an
//! override point). An element of a known type rebuilds through
//! [`ElementBase::rebuild`], which calls its `perform_rebuild` directly rather than through the
//! vtable. Folding `update_child` into every entry is cheap only because the framework's
//! elements are not generic over their widget, so there are a few dozen entries rather than one
//! per widget type. A forwarding method on that path without the attribute, or a call back
//! into `update_child` from what it folds in (see `inflate_inactive_child`), adds a call to
//! every level. The walks over a whole subtree (activate, deactivate, unmount) are loops.

use std::any::{Any, TypeId};
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::fmt::{self, Debug};
use std::hash::{Hash, Hasher};
use std::rc::Rc;

use waft_embedder::Size;
use waft_foundation::{
    App, DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticableTreeNode, DiagnosticsNode,
    DiagnosticsProperty, DiagnosticsTreeStyle, EntityId, FlagProperty, Handle, HandleId,
    IntoPropertyName, ObjectFlagProperty, Subscription, TrackedSet, bare_type_name,
    describe_identity,
};
use waft_rendering::{AnyRenderObject, RenderHandle, RenderObject};

use super::build_owner::{BuildOwner, BuildScope};
use super::element_node::{ElementDiagnosticsNode, ElementFacts};
use super::state::State;
use super::widget::{
    GlobalKey, InheritedWidget, KeyRef, Widget, WidgetKind, WidgetRef, can_update, downcast_widget,
    same_widget,
};
use crate::widgets::notification_listener::LayoutChangedNotification;
use crate::widgets::scroll_notification::ScrollNotification;
use waft_foundation::Ref;

/// A handle to the location of a widget in the widget tree.
///
/// This is Dart's `BuildContext` interface, which `Element` implements: here the type-erased
/// element handle plays both parts.
pub type BuildContext = AnyElement;

/// Dart's `_ElementLifecycle`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ElementLifecycle {
    Initial,
    Active,
    Inactive,
    Failed,
    Defunct,
}

/// A value for `Element.slot` used for children of `MultiChildRenderObjectElement`s.
///
/// A slot for a `MultiChildRenderObjectElement` consists of an [`index`](Self::index)
/// identifying where the child occurring at this slot is located in the
/// `MultiChildRenderObjectElement`'s child list and an arbitrary [`value`](Self::value) that
/// can further define where the child occurring at this slot fits in its parent's child list.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IndexedSlot {
    /// Information to define where the child occurring at this slot fits in its parent's
    /// child list.
    pub value: Option<AnyElement>,
    /// The index of this slot in the parent's child list.
    pub index: usize,
}

/// Dart's `Object? slot` on an element: how the parent tells its children apart.
#[derive(Clone, Debug)]
pub enum Slot {
    /// A child of a multi-child render object element.
    Indexed(IndexedSlot),
    /// The index of a child of a lazily built sliver (`SliverMultiBoxAdaptorElement`).
    Index(i32),
    /// A parent-defined value, compared by identity as an arbitrary Dart object would be.
    Custom(Rc<dyn Any>),
}

impl PartialEq for Slot {
    fn eq(&self, other: &Slot) -> bool {
        match (self, other) {
            (Slot::Indexed(a), Slot::Indexed(b)) => a == b,
            (Slot::Index(a), Slot::Index(b)) => a == b,
            (Slot::Custom(a), Slot::Custom(b)) => Rc::ptr_eq(a, b),
            _ => false,
        }
    }
}

/// The live "is this child forgotten?" check [`AnyElement::update_children`] takes (Dart's
/// `Set<Element> forgottenChildren`).
pub type ForgottenChildren<'a> = &'a dyn Fn(&App, AnyElement) -> bool;

/// A type a `NotificationListener<T>` can listen for: a concrete [`Notification`], or a
/// family of them named by a trait object (`dyn ScrollNotification`).
///
/// Dart's `notification is T`; a family answers it through a vtable slot on
/// [`Notification`], a concrete type through [`Notification::as_any`].
pub trait NotificationTarget: 'static {
    /// The notification as a `T`, when it is one.
    fn cast(notification: &dyn Notification) -> Option<&Self>;
}

impl<T: Notification> NotificationTarget for T {
    fn cast(notification: &dyn Notification) -> Option<&T> {
        notification.as_any().downcast_ref::<T>()
    }
}

/// To send a notification, call [`dispatch`](Self::dispatch) on the notification you wish to
/// send. The notification will be delivered to any `NotificationListener` widgets with the
/// appropriate type parameters that are ancestors of the given [`BuildContext`].
/// A notification that can bubble up the widget tree.
///
/// You can determine the type of a notification using the `is` operator to check the
/// `runtimeType` of the notification; here [`as_any`](Self::as_any) and a downcast.
///
/// To listen for notifications in a subtree, use a `NotificationListener`.
///
pub trait Notification: Any + Debug {
    /// The notification as `Any`, for Dart's `notification is T` check.
    fn as_any(&self) -> &dyn Any;

    /// The depth counter of a notification that mixes in `ViewportNotificationMixin`
    /// (`widgets/scroll_notification.rs`), for the viewport elements that increment it as
    /// the notification bubbles past them; `None` — the default — for every other
    /// notification.
    ///
    /// This is Dart's `notification is ViewportNotificationMixin`: a mixin is an interface,
    /// not a type, so an erased notification answers the check from its own vtable rather
    /// than through [`as_any`](Self::as_any). The counter is a [`Cell`] because a
    /// notification bubbles as `&dyn Notification`.
    fn viewport_depth(&self) -> Option<&Cell<u32>> {
        None
    }

    /// The notification as a `ScrollNotification` (`widgets/scroll_notification.rs`), for a
    /// `NotificationListener<dyn ScrollNotification>`; `None` — the default — for every
    /// other notification.
    ///
    /// This is Dart's `notification is ScrollNotification`, answered from the vtable as
    /// [`viewport_depth`](Self::viewport_depth) is, because the family is a trait.
    fn as_scroll_notification(&self) -> Option<&dyn ScrollNotification> {
        None
    }

    /// The notification as a `LayoutChangedNotification`
    /// (`widgets/notification_listener.rs`), for a
    /// `NotificationListener<dyn LayoutChangedNotification>`; `None` — the default — for every
    /// other notification.
    ///
    /// This is Dart's `notification is LayoutChangedNotification`, answered from the vtable as
    /// [`as_scroll_notification`](Self::as_scroll_notification) is: every notification Dart
    /// derives from `LayoutChangedNotification` answers it, scroll notifications included.
    fn as_layout_changed_notification(&self) -> Option<&dyn LayoutChangedNotification> {
        None
    }

    /// Start bubbling this notification at the given build context.
    ///
    /// The notification will be delivered to any `NotificationListener` widgets with the
    /// appropriate type parameters that are ancestors of the given [`BuildContext`]. If the
    /// [`BuildContext`] is null, the notification is not dispatched.
    fn dispatch(&self, app: &mut App, target: Option<BuildContext>)
    where
        Self: Sized,
    {
        if let Some(target) = target {
            target.dispatch_notification(app, self);
        }
    }
}

/// Dart's `_NotificationNode`: one notifiable element and the chain above it.
pub struct NotificationNode {
    parent: Option<Rc<NotificationNode>>,
    current: AnyElement,
}

impl NotificationNode {
    /// A node for `current`, chained under its nearest notifiable ancestor.
    pub fn new(parent: Option<Rc<NotificationNode>>, current: AnyElement) -> NotificationNode {
        NotificationNode { parent, current }
    }

    fn dispatch_notification(&self, app: &mut App, notification: &dyn Notification) {
        if self.current.on_notification(app, notification) {
            return;
        }
        if let Some(parent) = &self.parent {
            parent.dispatch_notification(app, notification);
        }
    }
}

/// The fields of Dart's `Element` base class.
pub struct ElementData {
    parent: Option<AnyElement>,
    slot: Option<Slot>,
    depth: u32,
    widget: Option<WidgetRef>,
    owner: Option<Handle<BuildOwner>>,
    pub(crate) parent_build_scope: Option<Handle<BuildScope>>,
    /// The scope [`assign_owner`](AnyElement::assign_owner) made for a root element, which the
    /// root holds; every other element's `parent_build_scope` names one an ancestor holds.
    root_build_scope: Option<Ref<BuildScope>>,
    lifecycle: ElementLifecycle,
    dirty: bool,
    pub(crate) in_dirty_list: bool,
    inherited_elements: Option<Rc<HashMap<TypeId, AnyElement>>>,
    /// Dart's `_notificationTree`: the nearest notifiable ancestor chain.
    notification_tree: Option<Rc<NotificationNode>>,
    dependencies: Option<HashSet<AnyElement>>,
    had_unsatisfied_dependencies: bool,
    debug_built_once: bool,
    /// Entities this element's last `build` read. Kept across deactivate; dropped on unmount.
    /// Activate rebuilds if this is non-empty, the way `hadDependencies` rebuilds for inherited widgets.
    entity_watches: HashMap<EntityId, Subscription>,
}

impl ElementData {
    /// Creates an element's bookkeeping for the given widget.
    pub fn new(widget: WidgetRef) -> ElementData {
        ElementData {
            parent: None,
            slot: None,
            depth: 0,
            widget: Some(widget),
            owner: None,
            parent_build_scope: None,
            root_build_scope: None,
            lifecycle: ElementLifecycle::Initial,
            dirty: true,
            in_dirty_list: false,
            inherited_elements: None,
            notification_tree: None,
            dependencies: None,
            had_unsatisfied_dependencies: false,
            debug_built_once: false,
            entity_watches: HashMap::new(),
        }
    }

    /// The configuration for this element, as a shared reference.
    pub fn widget_ref(&self) -> &WidgetRef {
        self.widget.as_ref().expect("the element is unmounted")
    }
}

/// The accessors [`Element`] asks for, for a struct whose bag is the field `element`.
#[macro_export]
macro_rules! element_accessors {
    () => {
        fn element_data(
            self: $crate::__private::foundation::Handle<Self>,
            app: &$crate::__private::foundation::App,
        ) -> &$crate::ElementData {
            &app.get(self).element
        }

        fn element_data_mut(
            self: $crate::__private::foundation::Handle<Self>,
            app: &mut $crate::__private::foundation::App,
        ) -> &mut $crate::ElementData {
            &mut app.get_mut(self).element
        }
    };
}

/// An instantiation of a `Widget` at a particular location in the tree.
///
/// Widgets describe how to configure a subtree but the same widget can be used to configure
/// multiple subtrees simultaneously because widgets are immutable. An [`Element`] represents
/// the use of a widget to configure a specific location in the tree. Over time, the widget
/// associated with a given element can change, for example, if the parent widget rebuilds
/// and creates a new widget for this location.
///
/// The overridable methods default to Dart's base bodies; an override that must run the
/// base as well calls it through [`ElementBase`] (`ElementBase::mount(self, ..)`), where
/// Dart calls `super`.
pub trait Element: Sized + 'static {
    /// Dart's base-class fields, held under the field `element`
    /// ([`element_accessors!`](crate::element_accessors)).
    fn element_data(self: Handle<Self>, app: &App) -> &ElementData;

    /// See [`element_data`](Self::element_data).
    fn element_data_mut(self: Handle<Self>, app: &mut App) -> &mut ElementData;

    /// The type-erased handle to this element.
    fn as_element(self: Handle<Self>) -> AnyElement {
        AnyElement {
            id: self.id(),
            vtable: const { &ElementVTable::of::<Self>() },
        }
    }

    /// Calls the argument for each child. Must be overridden by subclasses that support
    /// having children.
    ///
    /// There is no guaranteed order in which the children will be visited, though it should
    /// be consistent over time.
    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
        let _ = (self, app, visitor);
    }

    /// Calls the argument for each child considered onstage.
    ///
    /// Classes like `Offstage` and `Overlay` override this method to hide their children.
    ///
    /// Being onstage affects the element's discoverability during testing when you use
    /// flutter_test's `Finder`. Offstage elements are ignored by finders by default.
    ///
    /// Most widgets are not visible when offstage, but that is not always the case: an element
    /// that is offstage here may still paint.
    fn debug_visit_onstage_children(
        self: Handle<Self>,
        app: &App,
        visitor: &mut dyn FnMut(AnyElement),
    ) {
        self.visit_children(app, visitor);
    }

    /// Returns the child of this [`Element`] that will insert a `RenderObject` into an
    /// ancestor of this Element to construct the render tree.
    ///
    /// Returns `None` if this Element doesn't have any children who need to attach a
    /// `RenderObject` to an ancestor of this [`Element`]. A `RenderObjectElement` will
    /// therefore return `None` because its children insert their `RenderObject`s into the
    /// `RenderObjectElement` itself and not into an ancestor of the `RenderObjectElement`.
    fn render_object_attaching_child(self: Handle<Self>, app: &App) -> Option<AnyElement> {
        ElementBase::render_object_attaching_child(self, app)
    }

    /// Add this element to the tree in the given slot of the given parent.
    ///
    /// The framework calls this function when a newly created element is added to the tree
    /// for the first time. Use this method to initialize state that depends on having a
    /// parent. State that is independent of the parent can more easily be initialized in the
    /// constructor.
    fn mount(
        self: Handle<Self>,
        app: &mut App,
        parent: Option<AnyElement>,
        new_slot: Option<Slot>,
    ) {
        ElementBase::mount(self, app, parent, new_slot);
    }

    /// Change the widget used to configure this element.
    ///
    /// The framework calls this function when the parent wishes to use a different widget to
    /// configure this element. The new widget is guaranteed to have the same `runtimeType` as
    /// the old widget.
    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
        ElementBase::update(self, app, new_widget);
    }

    /// Called by [`AnyElement::update_slot_for_child`] when the slot for a child has changed.
    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        ElementBase::update_slot(self, app, new_slot);
    }

    /// Add [`AnyElement::render_object`] to the render tree at the location specified by
    /// `new_slot`.
    ///
    /// The default implementation of this function calls
    /// [`attach_render_object`](Self::attach_render_object) recursively on each child. The
    /// `RenderObjectElement::attach_render_object` override does the actual work of adding
    /// [`AnyElement::render_object`] to the render tree.
    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        ElementBase::attach_render_object(self, app, new_slot);
    }

    /// Remove [`AnyElement::render_object`] from the render tree.
    ///
    /// The default implementation of this function calls
    /// [`detach_render_object`](Self::detach_render_object) recursively on each child. The
    /// `RenderObjectElement::detach_render_object` override does the actual work of removing
    /// [`AnyElement::render_object`] from the render tree.
    fn detach_render_object(self: Handle<Self>, app: &mut App) {
        ElementBase::detach_render_object(self, app);
    }

    /// Remove the given child from the element's child list, in preparation for the child
    /// being reused elsewhere in the element tree.
    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
        let _ = (self, app, child);
    }

    /// Transition from the "inactive" to the "active" lifecycle state.
    fn activate(self: Handle<Self>, app: &mut App) {
        ElementBase::activate(self, app);
    }

    /// Transition from the "active" to the "inactive" lifecycle state.
    fn deactivate(self: Handle<Self>, app: &mut App) {
        ElementBase::deactivate(self, app);
    }

    /// Called, in debug mode, after children have been deactivated.
    fn debug_deactivated(self: Handle<Self>, app: &mut App) {
        debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Inactive);
    }

    /// Transition from the "inactive" to the "defunct" lifecycle state.
    fn unmount(self: Handle<Self>, app: &mut App) {
        ElementBase::unmount(self, app);
    }

    /// Cause the widget to update itself.
    ///
    /// Called by [`AnyElement::rebuild`] after the appropriate checks have been made.
    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
        ElementBase::perform_rebuild(self, app);
    }

    /// Called when a dependency of this element changes.
    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
        ElementBase::did_change_dependencies(self, app);
    }

    /// Dart's `_updateInheritance`: inherit the parent's inherited-element map.
    fn update_inheritance(self: Handle<Self>, app: &mut App) {
        ElementBase::update_inheritance(self, app);
    }

    /// Called in [`mount`](Self::mount) and [`activate`](Self::activate) to register this
    /// element in the notification tree.
    ///
    /// This method is only exposed so that notifiable elements can be implemented (Dart's
    /// `NotifiableElementMixin`): an element that wishes to respond to notifications
    /// overrides it to insert a node for itself, and [`on_notification`](Self::on_notification)
    /// to handle them.
    ///
    /// See also:
    ///   * `NotificationListener`, a widget that allows listening to notifications.
    fn attach_notification_tree(self: Handle<Self>, app: &mut App) {
        ElementBase::attach_notification_tree(self, app);
    }

    /// The [`BuildScope`] whose dirty list this element is in.
    ///
    /// The [`BuildOwner`] builds the dirty elements of one scope per `build_scope` call;
    /// an element that wants its own (a `LayoutBuilder`, whose subtree is built during
    /// layout) overrides this.
    fn build_scope(self: Handle<Self>, app: &App) -> Handle<BuildScope> {
        ElementBase::build_scope(self, app)
    }

    /// Marks the element as dirty and adds it to the global list of widgets to rebuild in
    /// the next frame.
    ///
    /// Since it is inefficient to build an element twice in one frame, applications and
    /// widgets should be structured so as to only mark widgets dirty during event handlers
    /// before the frame begins, not during the build itself.
    fn mark_needs_build(self: Handle<Self>, app: &mut App) {
        ElementBase::mark_needs_build(self, app);
    }

    /// Called when a notification of the appropriate type arrives at this location in the
    /// tree (Dart's `NotifiableElementMixin.onNotification`).
    ///
    /// Return true to cancel the notification bubbling. Return false to allow the
    /// notification to continue to be dispatched to further ancestors. Only elements that
    /// override [`attach_notification_tree`](Self::attach_notification_tree) are asked.
    fn on_notification(self: Handle<Self>, app: &mut App, notification: &dyn Notification) -> bool {
        let _ = (app, notification);
        false
    }

    /// Whether the child in the provided `slot` (or one of its descendants) must insert a
    /// `RenderObject` into its ancestor `RenderObjectElement` by calling
    /// `RenderObjectElement::insert_render_object_child` on it.
    fn debug_expects_render_object_for_slot(
        self: Handle<Self>,
        app: &App,
        slot: Option<&Slot>,
    ) -> bool {
        let _ = (self, app, slot);
        true
    }

    /// The render object at (or below) this location in the tree.
    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
        ElementBase::render_object(self, app)
    }

    /// Whether this element is in the middle of building.
    fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
        let _ = (self, app);
        false
    }

    // ---- Dart's `is` checks and the members behind them ----

    /// Dart's `this is RenderObjectElement`.
    const IS_RENDER_OBJECT_ELEMENT: bool = false;

    /// `RenderObjectElement.insertRenderObjectChild`.
    fn insert_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        slot: Option<Slot>,
    ) {
        let _ = (self, app, child, slot);
        unreachable!("not a RenderObjectElement");
    }

    /// `RenderObjectElement.moveRenderObjectChild`.
    fn move_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        old_slot: Option<Slot>,
        new_slot: Option<Slot>,
    ) {
        let _ = (self, app, child, old_slot, new_slot);
        unreachable!("not a RenderObjectElement");
    }

    /// `RenderObjectElement.removeRenderObjectChild`.
    fn remove_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        slot: Option<Slot>,
    ) {
        let _ = (self, app, child, slot);
        unreachable!("not a RenderObjectElement");
    }

    /// `RenderObjectElement._updateParentData`: apply a parent-data widget to this element's
    /// render object.
    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
        let _ = (self, app, parent_data_element);
        unreachable!("not a RenderObjectElement");
    }

    /// Dart's `this is ParentDataElement`.
    const IS_PARENT_DATA_ELEMENT: bool = false;

    /// `ParentDataWidget.applyParentData` through the element that holds the widget.
    fn apply_parent_data(
        self: Handle<Self>,
        app: &mut App,
        render_object: AnyRenderObject,
    ) -> bool {
        let _ = (self, app, render_object);
        unreachable!("not a ParentDataElement");
    }

    /// Dart's `this is InheritedElement`.
    const IS_INHERITED_ELEMENT: bool = false;

    /// `InheritedElement.updateDependencies`.
    fn update_dependencies(
        self: Handle<Self>,
        app: &mut App,
        dependent: AnyElement,
        aspect: Option<Rc<dyn Any>>,
    ) {
        let _ = (self, app, dependent, aspect);
        unreachable!("not an InheritedElement");
    }

    /// `InheritedElement.removeDependent`.
    fn remove_dependent(self: Handle<Self>, app: &mut App, dependent: AnyElement) {
        let _ = (self, app, dependent);
        unreachable!("not an InheritedElement");
    }

    /// Dart's `this is StatefulElement && state is T`: the state's type and arena id.
    fn state_handle_id(self: Handle<Self>, app: &App) -> Option<(TypeId, HandleId)> {
        let _ = (self, app);
        None
    }

    /// Dart's `debugFillProperties` as an element class overrides it: the properties it adds
    /// after `Element`'s, and `RenderObjectElement`'s for a render object element, which the
    /// framework adds first since a trait default cannot call `super`.
    fn debug_fill_properties(
        self: Handle<Self>,
        app: &App,
        properties: &mut DiagnosticPropertiesBuilder,
    ) {
        let _ = (self, app, properties);
    }

    /// Dart's `debugDescribeChildren`: the children a dump shows under this element, by
    /// default every child [`visit_children`](Self::visit_children) visits.
    fn debug_describe_children(self: Handle<Self>, app: &App) -> Vec<Rc<dyn DiagnosticsNode>> {
        let mut children: Vec<Rc<dyn DiagnosticsNode>> = Vec::new();
        Self::visit_children(self, app, &mut |child| {
            children.push(Rc::new(child.to_diagnostics_node(app, None)));
        });
        children
    }
}

/// The vtable of an erased [`AnyElement`]: one `&'static` table per element type.
pub(crate) struct ElementVTable {
    pub type_name: fn() -> &'static str,
    pub debug_fill_properties: fn(&App, HandleId, &mut DiagnosticPropertiesBuilder),
    pub debug_describe_children: fn(&App, HandleId) -> Vec<Rc<dyn DiagnosticsNode>>,
    pub element_data: fn(&App, HandleId) -> &ElementData,
    pub element_data_mut: fn(&mut App, HandleId) -> &mut ElementData,
    pub visit_children: fn(&App, HandleId, &mut dyn FnMut(AnyElement)),
    pub debug_visit_onstage_children: fn(&App, HandleId, &mut dyn FnMut(AnyElement)),
    pub render_object_attaching_child: fn(&App, HandleId) -> Option<AnyElement>,
    pub mount: fn(&mut App, HandleId, Option<AnyElement>, Option<Slot>),
    pub update: fn(&mut App, HandleId, WidgetRef),
    pub update_slot: fn(&mut App, HandleId, Option<Slot>),
    pub attach_render_object: fn(&mut App, HandleId, Option<Slot>),
    pub detach_render_object: fn(&mut App, HandleId),
    pub forget_child: fn(&mut App, HandleId, AnyElement),
    pub activate: fn(&mut App, HandleId),
    pub deactivate: fn(&mut App, HandleId),
    pub debug_deactivated: fn(&mut App, HandleId),
    pub unmount: fn(&mut App, HandleId),
    pub perform_rebuild: fn(&mut App, HandleId),
    pub did_change_dependencies: fn(&mut App, HandleId),
    pub update_inheritance: fn(&mut App, HandleId),
    pub attach_notification_tree: fn(&mut App, HandleId),
    pub build_scope: fn(&App, HandleId) -> Handle<BuildScope>,
    pub mark_needs_build: fn(&mut App, HandleId),
    pub on_notification: fn(&mut App, HandleId, &dyn Notification) -> bool,
    pub debug_expects_render_object_for_slot: fn(&App, HandleId, Option<&Slot>) -> bool,
    pub render_object: fn(&App, HandleId) -> Option<AnyRenderObject>,
    pub debug_doing_build: fn(&App, HandleId) -> bool,
    pub is_render_object_element: bool,
    pub insert_render_object_child: fn(&mut App, HandleId, AnyRenderObject, Option<Slot>),
    pub move_render_object_child:
        fn(&mut App, HandleId, AnyRenderObject, Option<Slot>, Option<Slot>),
    pub remove_render_object_child: fn(&mut App, HandleId, AnyRenderObject, Option<Slot>),
    pub update_parent_data: fn(&mut App, HandleId, AnyElement),
    pub is_parent_data_element: bool,
    pub apply_parent_data: fn(&mut App, HandleId, AnyRenderObject) -> bool,
    pub is_inherited_element: bool,
    pub update_dependencies: fn(&mut App, HandleId, AnyElement, Option<Rc<dyn Any>>),
    pub remove_dependent: fn(&mut App, HandleId, AnyElement),
    pub state_handle_id: fn(&App, HandleId) -> Option<(TypeId, HandleId)>,
}

/// The typed handle for an erased id. Free: nothing is looked up; `App::get` checks the slot.
fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
    Handle::from_id(id)
}

impl ElementVTable {
    pub(crate) const fn of<T: Element>() -> ElementVTable {
        ElementVTable {
            type_name: std::any::type_name::<T>,
            debug_fill_properties: |app, id, properties| {
                T::debug_fill_properties(resolve(id), app, properties)
            },
            debug_describe_children: |app, id| T::debug_describe_children(resolve(id), app),
            element_data: |app, id| T::element_data(resolve(id), app),
            element_data_mut: |app, id| T::element_data_mut(resolve(id), app),
            visit_children: |app, id, visitor| T::visit_children(resolve(id), app, visitor),
            debug_visit_onstage_children: |app, id, visitor| {
                T::debug_visit_onstage_children(resolve(id), app, visitor)
            },
            render_object_attaching_child: |app, id| {
                T::render_object_attaching_child(resolve(id), app)
            },
            mount: |app, id, parent, slot| T::mount(resolve(id), app, parent, slot),
            update: |app, id, widget| T::update(resolve(id), app, widget),
            update_slot: |app, id, slot| T::update_slot(resolve(id), app, slot),
            attach_render_object: |app, id, slot| T::attach_render_object(resolve(id), app, slot),
            detach_render_object: |app, id| T::detach_render_object(resolve(id), app),
            forget_child: |app, id, child| T::forget_child(resolve(id), app, child),
            activate: |app, id| T::activate(resolve(id), app),
            deactivate: |app, id| T::deactivate(resolve(id), app),
            debug_deactivated: |app, id| T::debug_deactivated(resolve(id), app),
            unmount: |app, id| T::unmount(resolve(id), app),
            perform_rebuild: |app, id| T::perform_rebuild(resolve(id), app),
            did_change_dependencies: |app, id| T::did_change_dependencies(resolve(id), app),
            update_inheritance: |app, id| T::update_inheritance(resolve(id), app),
            attach_notification_tree: |app, id| T::attach_notification_tree(resolve(id), app),
            build_scope: |app, id| T::build_scope(resolve(id), app),
            mark_needs_build: |app, id| T::mark_needs_build(resolve(id), app),
            on_notification: |app, id, notification| {
                T::on_notification(resolve(id), app, notification)
            },
            debug_expects_render_object_for_slot: |app, id, slot| {
                T::debug_expects_render_object_for_slot(resolve(id), app, slot)
            },
            render_object: |app, id| T::render_object(resolve(id), app),
            debug_doing_build: |app, id| T::debug_doing_build(resolve(id), app),
            is_render_object_element: T::IS_RENDER_OBJECT_ELEMENT,
            insert_render_object_child: |app, id, child, slot| {
                T::insert_render_object_child(resolve(id), app, child, slot)
            },
            move_render_object_child: |app, id, child, old_slot, new_slot| {
                T::move_render_object_child(resolve(id), app, child, old_slot, new_slot)
            },
            remove_render_object_child: |app, id, child, slot| {
                T::remove_render_object_child(resolve(id), app, child, slot)
            },
            update_parent_data: |app, id, element| T::update_parent_data(resolve(id), app, element),
            is_parent_data_element: T::IS_PARENT_DATA_ELEMENT,
            apply_parent_data: |app, id, render_object| {
                T::apply_parent_data(resolve(id), app, render_object)
            },
            is_inherited_element: T::IS_INHERITED_ELEMENT,
            update_dependencies: |app, id, dependent, aspect| {
                T::update_dependencies(resolve(id), app, dependent, aspect)
            },
            remove_dependent: |app, id, dependent| T::remove_dependent(resolve(id), app, dependent),
            state_handle_id: |app, id| T::state_handle_id(resolve(id), app),
        }
    }
}

/// Erased `Element`: one identity and a static vtable, like `AnyRenderObject`.
///
/// Equality is Dart's `==` on an element, which is identity.
#[derive(Clone, Copy)]
pub struct AnyElement {
    id: HandleId,
    vtable: &'static ElementVTable,
}

impl PartialEq for AnyElement {
    fn eq(&self, other: &AnyElement) -> bool {
        self.id == other.id
    }
}

impl Eq for AnyElement {}

impl Hash for AnyElement {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}

impl Debug for AnyElement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Element({:?})", self.id)
    }
}

impl AnyElement {
    /// The arena id behind this handle.
    pub fn id(self) -> HandleId {
        self.id
    }

    /// Dart's `element as T`: the typed handle when this element is a `T`, else `None`.
    pub fn downcast<T: Element>(self, app: &App) -> Option<Handle<T>> {
        app.handle::<T>(self.id)
    }

    pub(crate) fn data(self, app: &App) -> &ElementData {
        (self.vtable.element_data)(app, self.id)
    }

    pub(crate) fn data_mut(self, app: &mut App) -> &mut ElementData {
        (self.vtable.element_data_mut)(app, self.id)
    }

    /// Diffs the entities `build` read and binds [`observe`](App::observe_entity_id) watches.
    pub(crate) fn bind_entity_watches(self, app: &mut App, tracked: TrackedSet) {
        let current: HashSet<EntityId> = self.data(app).entity_watches.keys().copied().collect();
        let tracked: HashSet<EntityId> = tracked.iter().collect();
        for id in current.difference(&tracked) {
            self.data_mut(app).entity_watches.remove(id);
        }
        let added: Vec<EntityId> = tracked.difference(&current).copied().collect();
        for id in added {
            let element = self;
            let subscription = app.observe_entity_id(id, move |app| {
                if element.lifecycle(app) == ElementLifecycle::Active {
                    element.mark_needs_build(app);
                }
                true
            });
            self.data_mut(app).entity_watches.insert(id, subscription);
        }
        app.flush_entity_effects();
    }

    // ---- fields ----

    /// The configuration for this element.
    ///
    /// Avoid overriding this field on `Element` subtypes.
    pub fn widget(self, app: &App) -> &WidgetRef {
        self.data(app).widget_ref()
    }

    /// Returns true if the Element is active.
    ///
    /// A defunct element is freed after its unmount; a handle kept past that, as a callback
    /// keeps its `BuildContext`, answers false.
    pub fn mounted(self, app: &App) -> bool {
        app.contains(self.id) && self.data(app).widget.is_some()
    }

    /// The parent of this element, or `None` at the root.
    pub fn parent(self, app: &App) -> Option<AnyElement> {
        self.data(app).parent
    }

    /// Information set by parent to define where this child fits in its parent's child list.
    pub fn slot(self, app: &App) -> Option<Slot> {
        self.data(app).slot.clone()
    }

    /// An integer that is guaranteed to be greater than the parent's, if any. The element at
    /// the root of the tree must have a depth greater than 0.
    pub fn depth(self, app: &App) -> u32 {
        debug_assert!(
            self.lifecycle(app) != ElementLifecycle::Initial,
            "Depth is only available when element has been mounted."
        );
        self.data(app).depth
    }

    /// The object that manages the lifecycle of this element.
    pub fn owner(self, app: &App) -> Option<Handle<BuildOwner>> {
        self.data(app).owner
    }

    /// The [`BuildScope`] whose dirty list this element is in.
    pub fn build_scope(self, app: &App) -> Handle<BuildScope> {
        (self.vtable.build_scope)(app, self.id)
    }

    /// Where this element is in its lifecycle; a freed element is defunct.
    pub fn lifecycle(self, app: &App) -> ElementLifecycle {
        if !app.contains(self.id) {
            return ElementLifecycle::Defunct;
        }
        self.data(app).lifecycle
    }

    /// Dart's `toStringShort`: the widget's, or the element's identity once it has none.
    pub fn to_string_short(self, app: &App) -> String {
        match &self.data(app).widget {
            Some(widget) => widget.to_string_short(),
            None => format!(
                "{}(DEFUNCT)",
                describe_identity(
                    bare_type_name((self.vtable.type_name)()),
                    self.id.identity_hash()
                )
            ),
        }
    }

    /// Dart's `toDiagnosticsNode(name:)`: a snapshot of this element and its descendants as a
    /// dump shows them, one line each in the dense style.
    pub fn to_diagnostics_node(
        self,
        app: &App,
        name: impl IntoPropertyName,
    ) -> ElementDiagnosticsNode {
        let mut properties = DiagnosticPropertiesBuilder::new();
        self.fill_base_properties(app, &mut properties);
        (self.vtable.debug_fill_properties)(app, self.id, &mut properties);
        let children = (self.vtable.debug_describe_children)(app, self.id);
        let node = DiagnosticableTreeNode::from_parts(
            name,
            self.to_string_short(app),
            properties,
            children,
        )
        .with_value_id(self.id());
        let widget = self.data(app).widget.as_ref();
        let facts = ElementFacts {
            widget_runtime_type: widget.map(|widget| widget.type_name()),
            stateful: widget.is_some_and(|widget| widget.kind() == WidgetKind::Stateful),
            creation_location: widget.and_then(|widget| widget.creation_location()),
        };
        ElementDiagnosticsNode::new(node, facts)
    }

    /// Dart's `Element.toStringDeep`: this element and its descendants, at Dart's default level
    /// (debug) and width.
    pub fn to_string_deep(self, app: &App) -> String {
        self.to_string_deep_with(app, DiagnosticLevel::Debug, 65)
    }

    /// [`to_string_deep`](Self::to_string_deep) showing only properties at `min_level` or
    /// above, wrapping a line at `wrap_width` characters.
    pub fn to_string_deep_with(
        self,
        app: &App,
        min_level: DiagnosticLevel,
        wrap_width: usize,
    ) -> String {
        self.to_diagnostics_node(app, None).to_string_deep_with(
            "",
            Some(""),
            None,
            min_level,
            wrap_width,
        )
    }

    /// The properties `Element.debugFillProperties` adds, with its widget's among them, then
    /// `RenderObjectElement`'s render object.
    fn fill_base_properties(self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        properties.default_diagnostics_tree_style = DiagnosticsTreeStyle::Dense;
        let data = self.data(app);
        if data.lifecycle != ElementLifecycle::Initial {
            properties.add(ObjectFlagProperty::<u32>::new("depth", data.depth).if_null("no depth"));
        }
        properties.add(
            ObjectFlagProperty::<String>::new(
                "widget",
                data.widget.as_ref().map(|widget| widget.to_string_short()),
            )
            .if_null("no widget"),
        );
        let key = data.widget.as_ref().and_then(|widget| widget.key());
        properties.add(
            DiagnosticsProperty::<String>::new("key", key.map(|key| format!("{key:?}")))
                .with_show_name(false)
                .default_value(None)
                .with_level(DiagnosticLevel::Hidden),
        );
        if let Some(widget) = &data.widget {
            widget.debug_fill_properties(app, properties);
        }
        properties.add(FlagProperty::new("dirty", data.dirty).if_true("dirty"));
        if let Some(dependencies) = data.dependencies.as_ref().filter(|set| !set.is_empty()) {
            let mut names: Vec<String> = dependencies
                .iter()
                .map(|dependency| dependency.to_string_short(app))
                .collect();
            names.sort();
            properties.add(DiagnosticsProperty::<String>::new(
                "dependencies",
                format!("[{}]", names.join(", ")),
            ));
        }
        if self.is_render_object_element() {
            properties.add(
                DiagnosticsProperty::<String>::new(
                    "renderObject",
                    self.render_object(app)
                        .map(|render_object| render_object.to_string_short(app)),
                )
                .default_value(None),
            );
        }
    }

    /// Whether the element is active (in the tree).
    pub fn debug_is_active(self, app: &App) -> bool {
        self.lifecycle(app) == ElementLifecycle::Active
    }

    /// Whether the element is defunct (unmounted).
    pub fn debug_is_defunct(self, app: &App) -> bool {
        self.lifecycle(app) == ElementLifecycle::Defunct
    }

    /// Returns true if the element has been marked as needing rebuilding.
    ///
    /// The flag is true when the element is first created and after
    /// [`mark_needs_build`](Self::mark_needs_build) has been called. The flag is reset to
    /// false in the [`perform_rebuild`](Self::perform_rebuild) implementation.
    pub fn dirty(self, app: &App) -> bool {
        self.data(app).dirty
    }

    pub(crate) fn in_dirty_list(self, app: &App) -> bool {
        self.data(app).in_dirty_list
    }

    /// Whether this element is in the middle of building.
    pub fn debug_doing_build(self, app: &App) -> bool {
        (self.vtable.debug_doing_build)(app, self.id)
    }

    /// The children, in visit order.
    pub fn children(self, app: &App) -> Vec<AnyElement> {
        let mut children = Vec::new();
        self.visit_children(app, &mut |child| children.push(child));
        children
    }

    // ---- virtual dispatch ----

    /// See [`Element::visit_children`].
    pub fn visit_children(self, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
        (self.vtable.visit_children)(app, self.id, visitor);
    }

    /// See [`Element::debug_visit_onstage_children`].
    pub fn debug_visit_onstage_children(self, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
        (self.vtable.debug_visit_onstage_children)(app, self.id, visitor);
    }

    /// Every element under this one, depth first with a parent before its children and siblings
    /// in order, without this one, and with `skip_offstage` only those onstage: Dart's
    /// `collectAllElementsFrom`.
    pub fn descendants(self, app: &App, skip_offstage: bool) -> Vec<AnyElement> {
        let children_of = |element: AnyElement| {
            let mut children = Vec::new();
            if skip_offstage {
                element.debug_visit_onstage_children(app, &mut |child| children.push(child));
            } else {
                element.visit_children(app, &mut |child| children.push(child));
            }
            children
        };
        let mut found = Vec::new();
        let mut pending: Vec<AnyElement> = children_of(self).into_iter().rev().collect();
        while let Some(element) = pending.pop() {
            found.push(element);
            pending.extend(children_of(element).into_iter().rev());
        }
        found
    }

    /// See [`Element::render_object_attaching_child`].
    pub fn render_object_attaching_child(self, app: &App) -> Option<AnyElement> {
        (self.vtable.render_object_attaching_child)(app, self.id)
    }

    /// See [`Element::mount`].
    pub fn mount(self, app: &mut App, parent: Option<AnyElement>, new_slot: Option<Slot>) {
        (self.vtable.mount)(app, self.id, parent, new_slot);
    }

    /// See [`Element::update`].
    pub fn update(self, app: &mut App, new_widget: WidgetRef) {
        (self.vtable.update)(app, self.id, new_widget);
    }

    /// See [`Element::update_slot`].
    pub fn update_slot(self, app: &mut App, new_slot: Option<Slot>) {
        (self.vtable.update_slot)(app, self.id, new_slot);
    }

    /// See [`Element::attach_render_object`].
    pub fn attach_render_object(self, app: &mut App, new_slot: Option<Slot>) {
        (self.vtable.attach_render_object)(app, self.id, new_slot);
    }

    /// See [`Element::detach_render_object`].
    pub fn detach_render_object(self, app: &mut App) {
        (self.vtable.detach_render_object)(app, self.id);
    }

    /// See [`Element::forget_child`].
    pub fn forget_child(self, app: &mut App, child: AnyElement) {
        (self.vtable.forget_child)(app, self.id, child);
    }

    /// See [`Element::activate`].
    pub fn activate(self, app: &mut App) {
        (self.vtable.activate)(app, self.id);
    }

    /// See [`Element::deactivate`].
    pub fn deactivate(self, app: &mut App) {
        (self.vtable.deactivate)(app, self.id);
    }

    /// See [`Element::debug_deactivated`].
    pub fn debug_deactivated(self, app: &mut App) {
        (self.vtable.debug_deactivated)(app, self.id);
    }

    /// See [`Element::unmount`].
    pub fn unmount(self, app: &mut App) {
        (self.vtable.unmount)(app, self.id);
    }

    /// See [`Element::perform_rebuild`].
    pub fn perform_rebuild(self, app: &mut App) {
        (self.vtable.perform_rebuild)(app, self.id);
    }

    /// See [`Element::did_change_dependencies`].
    pub fn did_change_dependencies(self, app: &mut App) {
        (self.vtable.did_change_dependencies)(app, self.id);
    }

    /// See [`Element::update_inheritance`].
    pub fn update_inheritance(self, app: &mut App) {
        (self.vtable.update_inheritance)(app, self.id);
    }

    /// See [`Element::attach_notification_tree`].
    pub fn attach_notification_tree(self, app: &mut App) {
        (self.vtable.attach_notification_tree)(app, self.id);
    }

    /// See [`Element::on_notification`].
    pub fn on_notification(self, app: &mut App, notification: &dyn Notification) -> bool {
        (self.vtable.on_notification)(app, self.id, notification)
    }

    /// Start bubbling this notification at the given build context.
    ///
    /// The notification will be delivered to any `NotificationListener` widgets with the
    /// appropriate type parameters that are ancestors of the given [`BuildContext`].
    pub fn dispatch_notification(self, app: &mut App, notification: &dyn Notification) {
        let tree = self.data(app).notification_tree.clone();
        if let Some(tree) = tree {
            tree.dispatch_notification(app, notification);
        }
    }

    /// See [`Element::debug_expects_render_object_for_slot`].
    pub fn debug_expects_render_object_for_slot(self, app: &App, slot: Option<&Slot>) -> bool {
        (self.vtable.debug_expects_render_object_for_slot)(app, self.id, slot)
    }

    /// The render object at (or below) this location in the tree.
    ///
    /// If this object is a `RenderObjectElement`, the render object is the one at this
    /// location in the tree. Otherwise, this getter will walk down the tree until it finds a
    /// `RenderObjectElement`.
    ///
    /// Some locations in the tree are not backed by a render object. In those cases, this
    /// getter returns `None`.
    pub fn render_object(self, app: &App) -> Option<AnyRenderObject> {
        (self.vtable.render_object)(app, self.id)
    }

    /// `Element.inflateWidget`: create an element for the given widget and add it as a child of
    /// this element in the given slot.
    #[inline(always)]
    pub fn inflate_widget(
        self,
        app: &mut App,
        new_widget: WidgetRef,
        new_slot: Option<Slot>,
    ) -> AnyElement {
        let inactive_child = match new_widget.key() {
            Some(KeyRef::Global(key)) => self.retake_inactive_element(app, key, &new_widget),
            _ => None,
        };
        match inactive_child {
            Some(inactive_child) => {
                self.inflate_inactive_child(app, inactive_child, new_widget, new_slot)
            }
            None => {
                let new_child = new_widget.create_element(app, new_widget.clone());
                debug_assert!(debug_check_for_cycles(self, app, new_child));
                new_child.mount(app, Some(self), new_slot);
                debug_assert!(new_child.lifecycle(app) == ElementLifecycle::Active);
                new_child
            }
        }
    }

    /// [`inflate_widget`](Self::inflate_widget) for a child taken back from the inactive
    /// elements by its global key. Out of line so that `inflate_widget` and
    /// [`update_child`](Self::update_child), which this calls, can both fold into the element
    /// that runs them.
    #[inline(never)]
    fn inflate_inactive_child(
        self,
        app: &mut App,
        inactive_child: AnyElement,
        new_widget: WidgetRef,
        new_slot: Option<Slot>,
    ) -> AnyElement {
        debug_assert!(inactive_child.parent(app).is_none());
        inactive_child.activate_with_parent(app, self, new_slot.clone());
        let updated_child =
            self.update_child(app, Some(inactive_child), Some(new_widget), new_slot);
        debug_assert!(updated_child == Some(inactive_child));
        updated_child.expect("a retaken child stays")
    }

    /// Dart's `this is RenderObjectElement`.
    pub fn is_render_object_element(self) -> bool {
        self.vtable.is_render_object_element
    }

    /// See [`Element::insert_render_object_child`].
    pub fn insert_render_object_child(
        self,
        app: &mut App,
        child: AnyRenderObject,
        slot: Option<Slot>,
    ) {
        (self.vtable.insert_render_object_child)(app, self.id, child, slot);
    }

    /// See [`Element::move_render_object_child`].
    pub fn move_render_object_child(
        self,
        app: &mut App,
        child: AnyRenderObject,
        old_slot: Option<Slot>,
        new_slot: Option<Slot>,
    ) {
        (self.vtable.move_render_object_child)(app, self.id, child, old_slot, new_slot);
    }

    /// See [`Element::remove_render_object_child`].
    pub fn remove_render_object_child(
        self,
        app: &mut App,
        child: AnyRenderObject,
        slot: Option<Slot>,
    ) {
        (self.vtable.remove_render_object_child)(app, self.id, child, slot);
    }

    /// See [`Element::update_parent_data`].
    pub fn update_parent_data(self, app: &mut App, parent_data_element: AnyElement) {
        (self.vtable.update_parent_data)(app, self.id, parent_data_element);
    }

    /// Dart's `this is ParentDataElement`.
    pub fn is_parent_data_element(self) -> bool {
        self.vtable.is_parent_data_element
    }

    /// See [`Element::apply_parent_data`].
    pub fn apply_parent_data(self, app: &mut App, render_object: AnyRenderObject) -> bool {
        (self.vtable.apply_parent_data)(app, self.id, render_object)
    }

    /// Dart's `this is InheritedElement`.
    pub fn is_inherited_element(self) -> bool {
        self.vtable.is_inherited_element
    }

    /// See [`Element::update_dependencies`].
    pub fn update_dependencies(
        self,
        app: &mut App,
        dependent: AnyElement,
        aspect: Option<Rc<dyn Any>>,
    ) {
        (self.vtable.update_dependencies)(app, self.id, dependent, aspect);
    }

    /// See [`Element::remove_dependent`].
    pub fn remove_dependent(self, app: &mut App, dependent: AnyElement) {
        (self.vtable.remove_dependent)(app, self.id, dependent);
    }

    /// The typed state handle when this is a `StatefulElement` whose state is an `S`.
    pub fn state_handle<S: State>(self, app: &App) -> Option<Handle<S>> {
        let (type_id, id) = (self.vtable.state_handle_id)(app, self.id)?;
        (type_id == TypeId::of::<S>()).then(|| Handle::from_id(id))
    }

    // ---- Dart's `Element` concrete members ----

    /// Update the given child with the given new configuration.
    ///
    /// This method is the core of the widgets system. It is called each time we are to add,
    /// update, or remove a child based on an updated configuration.
    ///
    /// The `new_slot` argument specifies the new value for this element's
    /// [`slot`](Self::slot).
    ///
    /// If the `child` is `None`, and the `new_widget` is not `None`, then we have a new child
    /// for which we need to create an [`Element`], configured with `new_widget`.
    ///
    /// If the `new_widget` is `None`, and the `child` is not `None`, then we need to remove
    /// it because it no longer has a configuration.
    ///
    /// If neither are `None`, then we need to update the `child`'s configuration to be the
    /// new configuration given by `new_widget`. If `new_widget` can be given to the existing
    /// child (as determined by `can_update`), then it is so given. Otherwise, the old child
    /// needs to be disposed and a new child created for the new configuration.
    ///
    /// If both are `None`, then we don't have a child and won't have a child, so we do
    /// nothing.
    ///
    /// The [`update_child`](Self::update_child) method returns the new child, if it had to
    /// create one, or the child that was passed in, if it just had to update the child, or
    /// `None`, if it removed the child and did not replace it.
    #[inline(always)]
    pub fn update_child(
        self,
        app: &mut App,
        child: Option<AnyElement>,
        new_widget: Option<WidgetRef>,
        new_slot: Option<Slot>,
    ) -> Option<AnyElement> {
        let Some(new_widget) = new_widget else {
            if let Some(child) = child {
                self.deactivate_child(app, child);
            }
            return None;
        };
        let new_child = match child {
            Some(child) => {
                let has_same_superclass = child.widget(app).kind() == new_widget.kind();
                if has_same_superclass && same_widget(child.widget(app), &new_widget) {
                    if child.slot(app) != new_slot {
                        self.update_slot_for_child(app, child, new_slot);
                    }
                    child
                } else if has_same_superclass && can_update(&**child.widget(app), &*new_widget) {
                    if child.slot(app) != new_slot {
                        self.update_slot_for_child(app, child, new_slot);
                    }
                    child.update(app, new_widget.clone());
                    debug_assert!(same_widget(child.widget(app), &new_widget));
                    child
                } else {
                    self.deactivate_child(app, child);
                    debug_assert!(child.parent(app).is_none());
                    self.inflate_widget(app, new_widget, new_slot)
                }
            }
            None => self.inflate_widget(app, new_widget, new_slot),
        };
        Some(new_child)
    }

    /// Updates the children of this element to use new widgets.
    ///
    /// Attempts to update the given old children list using the given new widgets, removing
    /// obsolete elements and introducing new ones as necessary, and then returns the new
    /// child list.
    ///
    /// During this function the `old_children` list must not be modified. If the caller
    /// wishes to remove elements from `old_children` reentrantly while this function is on
    /// the stack, the caller can supply a `forgotten_children` argument, which can be
    /// modified while this function is on the stack. Whenever this function reads from
    /// `old_children`, this function first checks whether the child is in
    /// `forgotten_children`. If it is, the function acts as if the child was not in
    /// `old_children`.
    ///
    /// `forgotten_children` is a predicate so that it reads the caller's set live (in the
    /// arena, where a reentrant `forget_child` writes it) rather than a snapshot.
    ///
    /// This function is a convenience wrapper around [`update_child`](Self::update_child),
    /// which updates each individual child. If `slots` is non-`None`, the value for the
    /// `new_slot` argument of [`update_child`](Self::update_child) is retrieved from that
    /// list using the index that the currently processed `child` corresponds to in the
    /// `new_widgets` list (`new_widgets` and `slots` must have the same length). If `slots`
    /// is `None`, an [`IndexedSlot`] is used as the value for the `new_slot` argument. In
    /// that case, [`IndexedSlot::index`] is set to the index that the currently processed
    /// `child` corresponds to in the `new_widgets` list and [`IndexedSlot::value`] is set to
    /// the [`Element`] of the previous widget in that list (or `None` if it is the first
    /// child).
    pub fn update_children(
        self,
        app: &mut App,
        old_children: &[AnyElement],
        new_widgets: &[WidgetRef],
        forgotten_children: Option<ForgottenChildren<'_>>,
        slots: Option<&[Option<Slot>]>,
    ) -> Vec<AnyElement> {
        debug_assert!(slots.is_none_or(|slots| slots.len() == new_widgets.len()));
        let replace_with_null_if_forgotten = |app: &App, child: AnyElement| -> Option<AnyElement> {
            let forgotten = forgotten_children.is_some_and(|forgotten| forgotten(app, child));
            (!forgotten).then_some(child)
        };
        let slot_for =
            |new_child_index: usize, previous_child: Option<AnyElement>| -> Option<Slot> {
                match slots {
                    Some(slots) => slots[new_child_index].clone(),
                    None => Some(Slot::Indexed(IndexedSlot {
                        index: new_child_index,
                        value: previous_child,
                    })),
                }
            };

        // This attempts to diff the new child list (newWidgets) with
        // the old child list (oldChildren), and produce a new list of elements to
        // be the new list of child elements of this element. The called of this
        // method is expected to update this render object accordingly.

        // The cases it tries to optimize for are:
        //  - the old list is empty
        //  - the lists are identical
        //  - there is an insertion or removal of one or more widgets in
        //    only one place in the list
        // If a widget with a key is in both lists, it will be synced.
        // Widgets without keys might be synced but there is no guarantee.

        // The general approach is to sync the entire new list backwards, as follows:
        // 1. Walk the lists from the top, invoking updateChild on each element.
        // 2. Walk the lists from the bottom, without syncing, and simply track the
        //    number of matching elements at the end.
        // 3. Walk the middle of the old list, and collect the keyed children in a map.
        // 4. Walk the middle of the new list, syncing with the keyed old children when
        //    keys match, otherwise inflating new elements.
        // 5. Walk the bottom of the lists, syncing the elements that matched at the end.
        // 6. Deactivate any old children that were not synced.
        let mut new_children_top = 0usize;
        let mut old_children_top = 0usize;
        let mut new_children_bottom = new_widgets.len() as isize - 1;
        let mut old_children_bottom = old_children.len() as isize - 1;

        let mut new_children: Vec<Option<AnyElement>> = vec![None; new_widgets.len()];
        let mut previous_child: Option<AnyElement> = None;

        // Update the top of the list.
        while (old_children_top as isize <= old_children_bottom)
            && (new_children_top as isize <= new_children_bottom)
        {
            let old_child = replace_with_null_if_forgotten(app, old_children[old_children_top]);
            let new_widget = &new_widgets[new_children_top];
            debug_assert!(
                old_child.is_none_or(|old| old.lifecycle(app) == ElementLifecycle::Active)
            );
            let Some(old_child) = old_child else {
                break;
            };
            if !can_update(&**old_child.widget(app), &**new_widget) {
                break;
            }
            let new_child = self
                .update_child(
                    app,
                    Some(old_child),
                    Some(new_widget.clone()),
                    slot_for(new_children_top, previous_child),
                )
                .expect("a widget yields a child");
            debug_assert!(new_child.lifecycle(app) == ElementLifecycle::Active);
            new_children[new_children_top] = Some(new_child);
            previous_child = Some(new_child);
            new_children_top += 1;
            old_children_top += 1;
        }

        // Scan the bottom of the list.
        while (old_children_top as isize <= old_children_bottom)
            && (new_children_top as isize <= new_children_bottom)
        {
            let old_child =
                replace_with_null_if_forgotten(app, old_children[old_children_bottom as usize]);
            let new_widget = &new_widgets[new_children_bottom as usize];
            debug_assert!(
                old_child.is_none_or(|old| old.lifecycle(app) == ElementLifecycle::Active)
            );
            let Some(old_child) = old_child else {
                break;
            };
            if !can_update(&**old_child.widget(app), &**new_widget) {
                break;
            }
            old_children_bottom -= 1;
            new_children_bottom -= 1;
        }

        // Scan the old children in the middle of the list.
        let have_old_children = old_children_top as isize <= old_children_bottom;
        let mut old_keyed_children: HashMap<KeyRef, AnyElement> = HashMap::new();
        if have_old_children {
            while old_children_top as isize <= old_children_bottom {
                let old_child = replace_with_null_if_forgotten(app, old_children[old_children_top]);
                debug_assert!(
                    old_child.is_none_or(|old| old.lifecycle(app) == ElementLifecycle::Active)
                );
                if let Some(old_child) = old_child {
                    match old_child.widget(app).key().cloned() {
                        Some(key) => {
                            old_keyed_children.insert(key, old_child);
                        }
                        None => self.deactivate_child(app, old_child),
                    }
                }
                old_children_top += 1;
            }
        }

        // Update the middle of the list.
        while new_children_top as isize <= new_children_bottom {
            let new_widget = &new_widgets[new_children_top];
            let mut old_child: Option<AnyElement> = None;
            if have_old_children
                && let Some(key) = new_widget.key()
                && let Some(candidate) = old_keyed_children.get(key).copied()
                && can_update(&**candidate.widget(app), &**new_widget)
            {
                // we found a match!
                // remove it from oldKeyedChildren so we don't unsync it later
                old_keyed_children.remove(key);
                old_child = Some(candidate);
            }
            debug_assert!(
                old_child.is_none_or(|old| can_update(&**old.widget(app), &**new_widget))
            );
            let new_child = self
                .update_child(
                    app,
                    old_child,
                    Some(new_widget.clone()),
                    slot_for(new_children_top, previous_child),
                )
                .expect("a widget yields a child");
            debug_assert!(new_child.lifecycle(app) == ElementLifecycle::Active);
            debug_assert!(old_child.is_none_or(
                |old| old == new_child || old.lifecycle(app) != ElementLifecycle::Active
            ));
            new_children[new_children_top] = Some(new_child);
            previous_child = Some(new_child);
            new_children_top += 1;
        }

        // We've scanned the whole list.
        debug_assert!(old_children_top as isize == old_children_bottom + 1);
        debug_assert!(new_children_top as isize == new_children_bottom + 1);
        debug_assert!(
            new_widgets.len() - new_children_top == old_children.len() - old_children_top
        );
        new_children_bottom = new_widgets.len() as isize - 1;
        old_children_bottom = old_children.len() as isize - 1;

        // Update the bottom of the list.
        while (old_children_top as isize <= old_children_bottom)
            && (new_children_top as isize <= new_children_bottom)
        {
            let old_child = old_children[old_children_top];
            debug_assert!(replace_with_null_if_forgotten(app, old_child).is_some());
            debug_assert!(old_child.lifecycle(app) == ElementLifecycle::Active);
            let new_widget = &new_widgets[new_children_top];
            debug_assert!(can_update(&**old_child.widget(app), &**new_widget));
            let new_child = self
                .update_child(
                    app,
                    Some(old_child),
                    Some(new_widget.clone()),
                    slot_for(new_children_top, previous_child),
                )
                .expect("a widget yields a child");
            debug_assert!(new_child.lifecycle(app) == ElementLifecycle::Active);
            debug_assert!(
                old_child == new_child || old_child.lifecycle(app) != ElementLifecycle::Active
            );
            new_children[new_children_top] = Some(new_child);
            previous_child = Some(new_child);
            new_children_top += 1;
            old_children_top += 1;
        }

        // Clean up any of the remaining middle nodes from the old list.
        if have_old_children {
            for old_child in old_keyed_children.into_values() {
                if replace_with_null_if_forgotten(app, old_child).is_some() {
                    self.deactivate_child(app, old_child);
                }
            }
        }
        new_children
            .into_iter()
            .map(|child| child.expect("every slot was filled"))
            .collect()
    }

    /// Change the slot that the given child occupies in its parent.
    ///
    /// Called by `MultiChildRenderObjectElement`, and other `RenderObjectElement` subclasses
    /// that have multiple children, when child moves from one position to another in this
    /// element's child list.
    pub fn update_slot_for_child(self, app: &mut App, child: AnyElement, new_slot: Option<Slot>) {
        debug_assert!(self.lifecycle(app) == ElementLifecycle::Active);
        debug_assert!(child.parent(app) == Some(self));
        let mut element = Some(child);
        while let Some(current) = element {
            current.update_slot(app, new_slot.clone());
            element = current.render_object_attaching_child(app);
        }
    }

    fn update_depth(self, app: &mut App, parent_depth: u32) {
        let expected_depth = parent_depth + 1;
        if self.data(app).depth < expected_depth {
            self.data_mut(app).depth = expected_depth;
            for child in self.children(app) {
                child.update_depth(app, expected_depth);
            }
        }
    }

    fn update_build_scope_recursively(self, app: &mut App) {
        let parent_scope = self.parent(app).map(|parent| parent.build_scope(app));
        if self.data(app).parent_build_scope == parent_scope {
            return;
        }
        // Unset the _inDirtyList flag so this Element can be added to the dirty list
        // of the new build scope.
        let data = self.data_mut(app);
        data.in_dirty_list = false;
        data.parent_build_scope = parent_scope;
        for child in self.children(app) {
            child.update_build_scope_recursively(app);
        }
    }

    fn retake_inactive_element(
        self,
        app: &mut App,
        key: &GlobalKey,
        new_widget: &WidgetRef,
    ) -> Option<AnyElement> {
        // The "inactivity" of the element being retaken here may be forward-looking: if
        // we are taking an element with a GlobalKey from an element that currently has
        // it as a child, then we know that element will soon no longer have that
        // element as a child. The only way that assumption could be false is if the
        // global key is being duplicated, and we'll try to track that using the
        // _debugTrackElementThatWillNeedToBeRebuiltDueToGlobalKeyShenanigans call below.
        let owner = self.owner(app).expect("a mounted element has an owner");
        let element = owner.global_key_element(app, key)?;
        if !can_update(&**element.widget(app), &**new_widget) {
            return None;
        }
        if let Some(parent) = element.parent(app) {
            assert!(
                parent != self,
                "A GlobalKey was used multiple times inside one widget's child list. A \
                 GlobalKey can only be specified on one widget at a time in the widget tree."
            );
            parent.forget_child(app, element);
            parent.deactivate_child(app, element);
        }
        debug_assert!(element.parent(app).is_none());
        owner.inactive_remove(app, element);
        Some(element)
    }

    /// Move the given element to the list of inactive elements and detach its render object
    /// from the render tree.
    ///
    /// This method stops the given element from being a child of this element by detaching
    /// its render object from the render tree and moving the element to the list of inactive
    /// elements.
    ///
    /// This method (indirectly) calls [`deactivate`](Self::deactivate) on the child.
    ///
    /// The caller is responsible for removing the child from its child model. Typically
    /// [`deactivate_child`](Self::deactivate_child) is called by the element itself while it
    /// is updating its child model; however, during
    /// `GlobalKey` reparenting, the new parent proactively calls the old parent's
    /// [`deactivate_child`](Self::deactivate_child), first using [`forget_child`](Self::forget_child)
    /// to cause the old parent to update its child model.
    pub fn deactivate_child(self, app: &mut App, child: AnyElement) {
        debug_assert!(child.parent(app) == Some(self));
        child.data_mut(app).parent = None;
        child.detach_render_object(app);
        let owner = self.owner(app).expect("a mounted element has an owner");
        owner.inactive_add(app, child); // this eventually calls child.deactivate()
    }

    fn activate_with_parent(self, app: &mut App, parent: AnyElement, new_slot: Option<Slot>) {
        debug_assert!(self.lifecycle(app) == ElementLifecycle::Inactive);
        let parent_owner = parent.owner(app);
        let data = self.data_mut(app);
        data.parent = Some(parent);
        data.owner = parent_owner;
        let parent_depth = parent.depth(app);
        self.update_depth(app, parent_depth);
        self.update_build_scope_recursively(app);
        activate_recursively(app, self);
        self.attach_render_object(app, new_slot);
        debug_assert!(self.lifecycle(app) == ElementLifecycle::Active);
    }

    pub(crate) fn ensure_deactivated(self, app: &mut App) {
        let dependencies: Vec<AnyElement> = self
            .data(app)
            .dependencies
            .iter()
            .flatten()
            .copied()
            .collect();
        for dependency in dependencies {
            dependency.remove_dependent(app, self);
        }
        // For expediency, we don't actually clear the list here, even though it's
        // no longer representative of what we are registered with. If we never
        // get re-used, it doesn't matter. If we do, then we'll clear the list in
        // activate(). The benefit of this is that it allows Element's activate()
        // implementation to decide whether to rebuild based on whether we had
        // dependencies here.
        let data = self.data_mut(app);
        data.inherited_elements = None;
        data.lifecycle = ElementLifecycle::Inactive;
    }

    /// The current `RenderObject` for the widget. If the widget is a `RenderObjectWidget`,
    /// this is the render object that the widget created for itself. Otherwise, it is the
    /// render object of the first descendant `RenderObjectWidget`.
    ///
    /// This method will only return a valid result after the build phase is complete. It is
    /// therefore not valid to call this from a build method. It should only be called from
    /// interaction event handlers (e.g. gesture callbacks) or layout or paint callbacks. It
    /// is also not valid to call if [`mounted`](Self::mounted) is false.
    pub fn find_render_object(self, app: &App) -> Option<AnyRenderObject> {
        debug_assert!(
            self.lifecycle(app) == ElementLifecycle::Active,
            "Cannot get renderObject of inactive element. In order for an element to have a \
             valid renderObject, it must be active, which means it is part of the tree."
        );
        self.render_object(app)
    }

    /// The size of the `RenderBox` returned by [`find_render_object`](Self::find_render_object).
    ///
    /// This getter will only return a valid result after the layout phase is complete. It is
    /// therefore not valid to call this from a build method. It should only be called from
    /// paint callbacks or interaction event handlers (e.g. gesture callbacks).
    ///
    /// This getter will only return a valid result if [`find_render_object`](Self::find_render_object)
    /// actually returns a `RenderBox`. If [`find_render_object`](Self::find_render_object)
    /// returns a render object that is not a subtype of `RenderBox` (e.g., `RenderView`),
    /// this getter will return `None`.
    pub fn size(self, app: &App) -> Option<Size> {
        debug_assert!(
            self.lifecycle(app) == ElementLifecycle::Active,
            "Cannot get size of inactive element."
        );
        debug_assert!(
            !self
                .owner(app)
                .is_some_and(|owner| owner.debug_building(app)),
            "Cannot get size during build."
        );
        let render_object = self.find_render_object(app)?;
        let render_box = render_object.as_box()?;
        debug_assert!(
            render_box.has_size(app),
            "Cannot get size from a render object that has not been through layout."
        );
        debug_assert!(
            !render_object.debug_needs_layout(app),
            "Cannot get size from a render object that has been marked dirty for layout."
        );
        Some(render_box.size(app))
    }

    /// Returns `true` if `ancestor` is a dependency of this element.
    pub fn does_depend_on_inherited_element(self, app: &App, ancestor: AnyElement) -> bool {
        self.data(app)
            .dependencies
            .as_ref()
            .is_some_and(|dependencies| dependencies.contains(&ancestor))
    }

    /// Registers this build context with `ancestor` such that when `ancestor`'s widget
    /// changes this build context is rebuilt.
    ///
    /// Returns `ancestor.widget`.
    ///
    /// This method is rarely called directly. Most applications should use
    /// [`depend_on_inherited_widget_of_exact_type`](Self::depend_on_inherited_widget_of_exact_type),
    /// which calls this method after finding the appropriate `InheritedElement` ancestor.
    pub fn depend_on_inherited_element(
        self,
        app: &mut App,
        ancestor: AnyElement,
        aspect: Option<Rc<dyn Any>>,
    ) -> WidgetRef {
        self.data_mut(app)
            .dependencies
            .get_or_insert_with(HashSet::new)
            .insert(ancestor);
        ancestor.update_dependencies(app, self, aspect);
        ancestor.widget(app).clone()
    }

    /// Returns the nearest widget of the given type `W` and creates a dependency on it, or
    /// `None` if no appropriate widget is found.
    ///
    /// The widget found will be a concrete [`InheritedWidget`] subclass, and calling this
    /// method registers this build context with the returned widget. When that widget
    /// changes (or a new widget of that type is introduced, or the widget goes away), this
    /// build context is rebuilt so that it can obtain new values from that widget.
    ///
    /// This is typically called implicitly from `of()` static methods, e.g. `Theme.of`.
    ///
    /// This method should not be called from widget constructors or from
    /// `State::init_state` methods, because those methods would not get called again if the
    /// inherited value were to change. To ensure that the widget correctly updates itself
    /// when the inherited value changes, only call this (directly or indirectly) from build
    /// methods, layout and paint callbacks, or from `State::did_change_dependencies`.
    pub fn depend_on_inherited_widget_of_exact_type<W: InheritedWidget>(
        self,
        app: &mut App,
    ) -> Option<&W> {
        self.depend_on_inherited_widget_of_exact_type_with_aspect::<W>(app, None)
    }

    /// [`depend_on_inherited_widget_of_exact_type`](Self::depend_on_inherited_widget_of_exact_type)
    /// with Dart's `aspect` argument, for `InheritedModel`.
    pub fn depend_on_inherited_widget_of_exact_type_with_aspect<W: InheritedWidget>(
        self,
        app: &mut App,
        aspect: Option<Rc<dyn Any>>,
    ) -> Option<&W> {
        debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
        let ancestor = self
            .data(app)
            .inherited_elements
            .as_ref()
            .and_then(|elements| elements.get(&TypeId::of::<W>()).copied());
        let Some(ancestor) = ancestor else {
            self.data_mut(app).had_unsatisfied_dependencies = true;
            return None;
        };
        self.depend_on_inherited_element(app, ancestor, aspect);
        let widget: &WidgetRef = ancestor.widget(app);
        downcast_widget::<W>(&**widget)
    }

    /// Returns the nearest widget of the given [`InheritedWidget`] subclass `W` or `None` if
    /// an appropriate ancestor is not found.
    ///
    /// This method does not introduce a dependency the way that the more typical
    /// [`depend_on_inherited_widget_of_exact_type`](Self::depend_on_inherited_widget_of_exact_type)
    /// does, so this context will not be rebuilt if the [`InheritedWidget`] changes. This
    /// function is meant for those uncommon use cases where a dependency is undesirable.
    pub fn get_inherited_widget_of_exact_type<W: InheritedWidget>(self, app: &App) -> Option<&W> {
        let element = self.get_element_for_inherited_widget_of_exact_type::<W>(app)?;
        let widget: &WidgetRef = element.widget(app);
        downcast_widget::<W>(&**widget)
    }

    /// Obtains the element corresponding to the nearest widget of the given type `W`, which
    /// must be the type of a concrete [`InheritedWidget`] subclass.
    ///
    /// Returns `None` if no such element is found.
    ///
    /// Calling this method is O(1) with a small constant factor.
    ///
    /// This method does not establish a relationship with the target in the way that
    /// [`depend_on_inherited_widget_of_exact_type`](Self::depend_on_inherited_widget_of_exact_type)
    /// does.
    pub fn get_element_for_inherited_widget_of_exact_type<W: InheritedWidget>(
        self,
        app: &App,
    ) -> Option<AnyElement> {
        debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
        self.data(app)
            .inherited_elements
            .as_ref()
            .and_then(|elements| elements.get(&TypeId::of::<W>()).copied())
    }

    fn debug_check_state_is_active_for_ancestor_lookup(self, app: &App) -> bool {
        assert!(
            self.lifecycle(app) == ElementLifecycle::Active,
            "Looking up a deactivated widget's ancestor is unsafe. At this point the state of \
             the widget's element tree is no longer stable. To safely refer to a widget's \
             ancestor in its dispose() method, save a reference to the ancestor by calling \
             dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() \
             method."
        );
        true
    }

    /// Returns the nearest ancestor widget of the given type `W`, which must be the type of
    /// a concrete `Widget` subclass.
    ///
    /// In general, [`depend_on_inherited_widget_of_exact_type`](Self::depend_on_inherited_widget_of_exact_type)
    /// is more useful, since inherited widgets will trigger consumers to rebuild when they
    /// change. This method is appropriate when used in interaction event handlers (e.g.
    /// gesture callbacks) or for performing one-off tasks such as asserting that you have or
    /// don't have a widget of a specific type as an ancestor. The return value of a Widget's
    /// build method should not depend on the value returned by this method, because the
    /// build context will not rebuild if the return value of this method changes. This could
    /// lead to a situation where data used in the build method changes, but the widget is
    /// not rebuilt.
    ///
    /// Calling this method is relatively expensive (O(N) in the depth of the tree). Only
    /// call this method if the distance from this widget to the desired ancestor is known to
    /// be small and bounded.
    pub fn find_ancestor_widget_of_exact_type<W: 'static>(self, app: &App) -> Option<&W> {
        debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
        let mut ancestor = self.parent(app);
        while let Some(current) = ancestor {
            if current.widget(app).widget_type() == TypeId::of::<W>() {
                return downcast_widget::<W>(&**current.widget(app));
            }
            ancestor = current.parent(app);
        }
        None
    }

    /// Returns the [`State`] object of the nearest ancestor `StatefulWidget` widget that is
    /// an instance of the given type `S`.
    ///
    /// This should not be used from build methods, because the build context will not be
    /// rebuilt if the value that would be returned by this method changes. In general,
    /// [`depend_on_inherited_widget_of_exact_type`](Self::depend_on_inherited_widget_of_exact_type)
    /// is more appropriate for such cases. This method is useful for changing the state of an
    /// ancestor widget in a one-off manner, for example, to cause an ancestor scrolling list
    /// to scroll this build context's widget into view, or to move the focus in response to
    /// user interaction.
    ///
    /// Calling this method is relatively expensive (O(N) in the depth of the tree). Only
    /// call this method if the distance from this widget to the desired ancestor is known to
    /// be small and bounded.
    pub fn find_ancestor_state_of_type<S: State>(self, app: &App) -> Option<Handle<S>> {
        debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
        let mut ancestor = self.parent(app);
        while let Some(current) = ancestor {
            if let Some(state) = current.state_handle::<S>(app) {
                return Some(state);
            }
            ancestor = current.parent(app);
        }
        None
    }

    /// Returns the [`State`] object of the furthest ancestor `StatefulWidget` widget that is
    /// an instance of the given type `S`.
    ///
    /// Functions the same way as [`find_ancestor_state_of_type`](Self::find_ancestor_state_of_type)
    /// but keeps visiting subsequent ancestors until there are none of the type instance of
    /// `S` remaining. Then returns the last one found.
    ///
    /// This operation is O(N) as well though N is the entire widget tree rather than a
    /// subtree.
    pub fn find_root_ancestor_state_of_type<S: State>(self, app: &App) -> Option<Handle<S>> {
        debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
        let mut ancestor = self.parent(app);
        let mut stateful_ancestor = None;
        while let Some(current) = ancestor {
            if let Some(state) = current.state_handle::<S>(app) {
                stateful_ancestor = Some(state);
            }
            ancestor = current.parent(app);
        }
        stateful_ancestor
    }

    /// Returns the `RenderObject` object of the nearest ancestor `RenderObjectWidget` widget
    /// that is an instance of the given type `R`.
    ///
    /// This should not be used from build methods, because the build context will not be
    /// rebuilt if the value that would be returned by this method changes. In general,
    /// [`depend_on_inherited_widget_of_exact_type`](Self::depend_on_inherited_widget_of_exact_type)
    /// is more appropriate for such cases. This method is useful only in esoteric cases where
    /// a widget needs to cause an ancestor to change its layout or paint behavior. For
    /// example, it is used by `Material` so that `InkWell` widgets can trigger the ink splash
    /// on the `Material`'s actual render object.
    ///
    /// Calling this method is relatively expensive (O(N) in the depth of the tree). Only
    /// call this method if the distance from this widget to the desired ancestor is known to
    /// be small and bounded.
    pub fn find_ancestor_render_object_of_type<R: RenderObject>(
        self,
        app: &App,
    ) -> Option<RenderHandle<R>> {
        debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
        let mut ancestor = self.parent(app);
        while let Some(current) = ancestor {
            if current.is_render_object_element()
                && let Some(render_object) = current.render_object(app)
                && let Some(typed) = render_object.downcast::<R>(app)
            {
                return Some(typed);
            }
            ancestor = current.parent(app);
        }
        None
    }

    /// Walks the ancestor chain, starting with the parent of this build context's widget,
    /// invoking the argument for each ancestor.
    ///
    /// The callback is given a reference to the ancestor widget's corresponding [`Element`]
    /// object. The walk stops when it reaches the root widget or when the callback returns
    /// false. The callback must not return `None`.
    ///
    /// This is useful for inspecting the widget tree.
    ///
    /// Calling this method is relatively expensive (O(N) in the depth of the tree).
    pub fn visit_ancestor_elements(self, app: &App, visitor: &mut dyn FnMut(AnyElement) -> bool) {
        debug_assert!(self.debug_check_state_is_active_for_ancestor_lookup(app));
        let mut ancestor = self.parent(app);
        while let Some(current) = ancestor {
            if !visitor(current) {
                break;
            }
            ancestor = current.parent(app);
        }
    }

    /// Walks the children of this widget.
    ///
    /// This is useful for applying changes to children after they are built without waiting
    /// for the next frame, especially if the children are known, and especially if there is
    /// exactly one child (as is always the case for `StatefulWidget`s or `StatelessWidget`s).
    ///
    /// Calling this method is very cheap for build contexts that correspond to
    /// `StatefulWidget`s or `StatelessWidget`s (O(1), since there's only one child).
    ///
    /// Calling this method is potentially expensive for build contexts that correspond to
    /// `RenderObjectWidget`s (O(N) in the number of children).
    ///
    /// Calling this method recursively is extremely expensive (O(N) in the number of
    /// descendants), and should be avoided if possible. Generally it is significantly cheaper
    /// to use an `InheritedWidget` and have the descendants pull data down than it is to use
    /// [`visit_child_elements`](Self::visit_child_elements) recursively to push data down to
    /// them.
    pub fn visit_child_elements(self, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
        debug_assert!(
            !self
                .owner(app)
                .is_some_and(|owner| owner.debug_state_locked(app)),
            "visitChildElements() called during build."
        );
        self.visit_children(app, visitor);
    }

    /// Dart's `_debugIsDescendantOf`.
    pub fn debug_is_descendant_of(self, app: &App, target: AnyElement) -> bool {
        let mut element = Some(self);
        while let Some(current) = element
            && current.depth(app) > target.depth(app)
        {
            element = current.parent(app);
        }
        element == Some(target)
    }

    /// Marks the element as dirty and adds it to the global list of widgets to rebuild in the
    /// next frame.
    ///
    /// Since it is inefficient to build an element twice in one frame, applications and
    /// widgets should be structured so as to only mark widgets dirty during event handlers
    /// before the frame begins, not during the build itself.
    pub fn mark_needs_build(self, app: &mut App) {
        (self.vtable.mark_needs_build)(app, self.id);
    }

    /// Cause the widget to update itself. In debug builds, also verify various invariants.
    ///
    /// Called by the [`BuildOwner`] when `BuildOwner::schedule_build_for` has been called to
    /// mark this element dirty, by [`mount`](Self::mount) when the element is first built,
    /// and by [`update`](Self::update) when the widget has changed.
    ///
    /// The method will only rebuild if [`dirty`](Self::dirty) is true. To rebuild
    /// irrespective of the [`dirty`](Self::dirty) flag, set `force` to true. Forcing a
    /// rebuild is convenient when [`update`](Self::update) is called, during which
    /// [`dirty`](Self::dirty) is false.
    pub fn rebuild(self, app: &mut App, force: bool) {
        if let Some(rebuilding) = self.begin_rebuild(app, force) {
            self.perform_rebuild(app);
            self.end_rebuild(app, rebuilding);
        }
    }

    /// What [`rebuild`](Self::rebuild) checks and records before `perform_rebuild`, or `None`
    /// when the element needs no rebuild. Apart from `rebuild` itself so that an element of a
    /// known type can call its own `perform_rebuild` in between (see [`ElementBase::rebuild`]).
    #[inline(always)]
    pub(crate) fn begin_rebuild(self, app: &mut App, force: bool) -> Option<Rebuilding> {
        debug_assert!(self.lifecycle(app) != ElementLifecycle::Initial);
        if self.lifecycle(app) != ElementLifecycle::Active || (!self.dirty(app) && !force) {
            return None;
        }
        let owner = self.owner(app).expect("an active element has an owner");
        debug_assert!(owner.debug_state_locked(app));
        let debug_previous_build_target = owner.debug_current_build_target(app);
        if cfg!(debug_assertions) {
            owner.set_debug_current_build_target(app, Some(self));
            self.data_mut(app).debug_built_once = true;
        }
        Some(Rebuilding {
            owner,
            debug_previous_build_target,
        })
    }

    /// What [`rebuild`](Self::rebuild) restores and checks after `perform_rebuild`.
    #[inline(always)]
    pub(crate) fn end_rebuild(self, app: &mut App, rebuilding: Rebuilding) {
        if cfg!(debug_assertions) {
            let owner = rebuilding.owner;
            debug_assert!(owner.debug_current_build_target(app) == Some(self));
            owner.set_debug_current_build_target(app, rebuilding.debug_previous_build_target);
        }
        debug_assert!(!self.dirty(app));
    }

    pub(crate) fn had_dependencies(self, app: &App) -> bool {
        let data = self.data(app);
        data.dependencies
            .as_ref()
            .is_some_and(|dependencies| !dependencies.is_empty())
            || data.had_unsatisfied_dependencies
    }

    /// The notification chain this element dispatches into.
    pub fn notification_tree(self, app: &App) -> Option<Rc<NotificationNode>> {
        self.data(app).notification_tree.clone()
    }

    /// Sets the notification chain: a notifiable element chains a node for itself here.
    pub fn set_notification_tree(self, app: &mut App, tree: Option<Rc<NotificationNode>>) {
        self.data_mut(app).notification_tree = tree;
    }

    pub(crate) fn inherited_elements(self, app: &App) -> Option<Rc<HashMap<TypeId, AnyElement>>> {
        self.data(app).inherited_elements.clone()
    }

    pub(crate) fn set_inherited_elements(
        self,
        app: &mut App,
        elements: Option<Rc<HashMap<TypeId, AnyElement>>>,
    ) {
        self.data_mut(app).inherited_elements = elements;
    }

    pub(crate) fn set_slot(self, app: &mut App, slot: Option<Slot>) {
        self.data_mut(app).slot = slot;
    }

    pub(crate) fn set_dirty(self, app: &mut App, dirty: bool) {
        self.data_mut(app).dirty = dirty;
    }

    /// `RootElementMixin.assignOwner`: set the owner of the element and its build scope.
    ///
    /// The owner of an element is determined at mount, so this should only be called on a
    /// root element that is about to be mounted without a parent.
    pub fn assign_owner(self, app: &mut App, owner: Handle<BuildOwner>) {
        let scope = BuildScope::new(app, None);
        let data = self.data_mut(app);
        data.owner = Some(owner);
        data.parent_build_scope = Some(scope.handle());
        data.root_build_scope = Some(scope);
    }
}

/// Dart's `_activateRecursively`: activates `element`, then its children, in a loop rather than
/// recursion so a deep subtree costs no stack per level.
fn activate_recursively(app: &mut App, element: AnyElement) {
    let mut stack = vec![element];
    while let Some(element) = stack.pop() {
        debug_assert!(element.lifecycle(app) == ElementLifecycle::Inactive);
        element.activate(app);
        debug_assert!(element.lifecycle(app) == ElementLifecycle::Active);
        stack.extend(element.children(app).into_iter().rev());
    }
}

// ---------------------------------------------------------------------------------------------
// Dart's `Element` base bodies. An override calls the one it would call as `super`.

/// The build owner and earlier build target an element's rebuild restores once it is done.
pub(crate) struct Rebuilding {
    owner: Handle<BuildOwner>,
    debug_previous_build_target: Option<AnyElement>,
}

/// Dart's `Element` bodies, reachable from an override the way `super.mount(..)` is.
///
/// Every [`Element`] implements it. An override that must run the inherited body calls it
/// trait-qualified, `ElementBase::mount(self, app, parent, new_slot)`, at the position Dart
/// calls `super`; the [`Element`] defaults run the same bodies.
pub trait ElementBase: Element {
    /// `Element.rebuild` for an element whose type is known: calls its
    /// [`perform_rebuild`](Element::perform_rebuild) directly rather than through the vtable,
    /// so a first build adds no frame on the way down the tree.
    #[inline(always)]
    fn rebuild(self: Handle<Self>, app: &mut App, force: bool) {
        let this = self.as_element();
        if let Some(rebuilding) = this.begin_rebuild(app, force) {
            Element::perform_rebuild(self, app);
            this.end_rebuild(app, rebuilding);
        }
    }

    /// `Element.renderObjectAttachingChild`: the single child, if any.
    fn render_object_attaching_child(self: Handle<Self>, app: &App) -> Option<AnyElement> {
        let this = self.as_element();
        let mut next = None;
        this.visit_children(app, &mut |child| {
            debug_assert!(next.is_none()); // This verifies that there's only one child.
            next = Some(child);
        });
        next
    }

    /// `Element.mount`.
    fn mount(
        self: Handle<Self>,
        app: &mut App,
        parent: Option<AnyElement>,
        new_slot: Option<Slot>,
    ) {
        let this = self.as_element();
        debug_assert!(
            this.lifecycle(app) == ElementLifecycle::Initial,
            "This element is no longer in its initial state ({:?})",
            this.lifecycle(app)
        );
        debug_assert!(
            this.parent(app).is_none(),
            "This element already has a parent and it shouldn't have one yet."
        );
        debug_assert!(
            parent.is_none_or(|parent| parent.lifecycle(app) == ElementLifecycle::Active),
            "Parent should be null or in the active state"
        );
        debug_assert!(
            this.slot(app).is_none(),
            "This element already has a slot and it shouldn't"
        );
        let parent_depth = parent.map_or(0, |parent| parent.depth(app));
        let parent_owner = parent.and_then(|parent| parent.owner(app));
        let parent_scope = parent.map(|parent| parent.build_scope(app));
        let data = this.data_mut(app);
        data.parent = parent;
        data.slot = new_slot;
        data.lifecycle = ElementLifecycle::Active;
        data.depth = 1 + parent_depth;
        if parent.is_some() {
            // Only assign ownership if the parent is non-null. If parent is null
            // (the root node), the owner should have already been assigned.
            // See RootRenderObjectElement.assignOwner().
            data.owner = parent_owner;
            data.parent_build_scope = parent_scope;
        }
        let owner = this.owner(app).expect("a mounted element has an owner");
        if let Some(KeyRef::Global(key)) = this.widget(app).key().cloned() {
            owner.register_global_key(app, &key, this);
        }
        this.update_inheritance(app);
        this.attach_notification_tree(app);
    }

    /// `Element.update`.
    #[inline(always)]
    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
        let this = self.as_element();
        // This code is hot when hot reloading, so we try to
        // only call _AssertionError._evaluateAssertion once.
        debug_assert!(
            this.lifecycle(app) == ElementLifecycle::Active
                && !same_widget(this.widget(app), &new_widget)
                && can_update(&**this.widget(app), &*new_widget)
        );
        this.data_mut(app).widget = Some(new_widget);
    }

    /// `Element.updateSlot`.
    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        let this = self.as_element();
        debug_assert!(this.lifecycle(app) == ElementLifecycle::Active);
        debug_assert!(this.parent(app).is_some());
        debug_assert!(
            this.parent(app)
                .is_some_and(|parent| parent.lifecycle(app) == ElementLifecycle::Active)
        );
        this.set_slot(app, new_slot);
    }

    /// `Element.attachRenderObject`.
    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        let this = self.as_element();
        debug_assert!(this.slot(app).is_none());
        for child in this.children(app) {
            child.attach_render_object(app, new_slot.clone());
        }
        this.set_slot(app, new_slot);
    }

    /// `Element.detachRenderObject`.
    fn detach_render_object(self: Handle<Self>, app: &mut App) {
        let this = self.as_element();
        for child in this.children(app) {
            child.detach_render_object(app);
        }
        this.set_slot(app, None);
    }

    /// `Element.activate`.
    fn activate(self: Handle<Self>, app: &mut App) {
        let this = self.as_element();
        debug_assert!(this.lifecycle(app) == ElementLifecycle::Inactive);
        let owner = this
            .owner(app)
            .expect("an inactive element keeps its owner");
        let had_dependencies = this.had_dependencies(app);
        let had_entity_watches = !this.data(app).entity_watches.is_empty();
        let data = this.data_mut(app);
        data.lifecycle = ElementLifecycle::Active;
        // We unregistered our dependencies in deactivate, but never cleared the list.
        // Since we're going to be reused, let's clear our list now.
        if let Some(dependencies) = &mut data.dependencies {
            dependencies.clear();
        }
        data.had_unsatisfied_dependencies = false;
        this.update_inheritance(app);
        this.attach_notification_tree(app);
        if this.dirty(app) {
            owner.schedule_build_for(app, this);
        }
        if had_dependencies {
            this.did_change_dependencies(app);
        } else if had_entity_watches {
            this.mark_needs_build(app);
        }
    }

    /// `Element.deactivate`.
    fn deactivate(self: Handle<Self>, app: &mut App) {
        let this = self.as_element();
        debug_assert!(this.lifecycle(app) == ElementLifecycle::Active);
        debug_assert!(this.mounted(app));
        this.ensure_deactivated(app);
    }

    /// `Element.unmount`.
    fn unmount(self: Handle<Self>, app: &mut App) {
        let this = self.as_element();
        debug_assert!(this.lifecycle(app) == ElementLifecycle::Inactive);
        debug_assert!(this.mounted(app));
        let owner = this
            .owner(app)
            .expect("an inactive element keeps its owner");
        if let Some(KeyRef::Global(key)) = this.widget(app).key().cloned() {
            owner.unregister_global_key(app, &key, this);
        }
        // Release resources to reduce the severity of memory leaks caused by
        // defunct, but accidentally retained Elements.
        let data = this.data_mut(app);
        data.widget = None;
        data.dependencies = None;
        data.entity_watches.clear();
        data.lifecycle = ElementLifecycle::Defunct;
    }

    /// `Element.performRebuild`: clears the dirty flag.
    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
        let this = self.as_element();
        this.set_dirty(app, false);
    }

    /// `Element.didChangeDependencies`.
    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
        let this = self.as_element();
        debug_assert!(this.lifecycle(app) == ElementLifecycle::Active); // otherwise markNeedsBuild is a no-op
        debug_assert!(debug_check_owner_build_target_exists(
            this,
            app,
            "didChangeDependencies"
        ));
        this.mark_needs_build(app);
    }

    /// `Element.attachNotificationTree`: inherit the parent's notification chain.
    fn attach_notification_tree(self: Handle<Self>, app: &mut App) {
        let this = self.as_element();
        let tree = this
            .parent(app)
            .and_then(|parent| parent.data(app).notification_tree.clone());
        this.data_mut(app).notification_tree = tree;
    }

    /// `Element.buildScope`: the scope inherited from the parent at mount.
    fn build_scope(self: Handle<Self>, app: &App) -> Handle<BuildScope> {
        self.as_element()
            .data(app)
            .parent_build_scope
            .expect("an element in a tree has a build scope")
    }

    /// `Element.markNeedsBuild`.
    fn mark_needs_build(self: Handle<Self>, app: &mut App) {
        let this = self.as_element();
        debug_assert!(this.lifecycle(app) != ElementLifecycle::Defunct);
        if this.lifecycle(app) != ElementLifecycle::Active {
            return;
        }
        let owner = this.owner(app).expect("an active element has an owner");
        if cfg!(debug_assertions) {
            if owner.debug_building(app) {
                let target = owner
                    .debug_current_build_target(app)
                    .expect("building has a target");
                debug_assert!(owner.debug_state_locked(app));
                assert!(
                    this.debug_is_descendant_of(app, target),
                    "setState() or markNeedsBuild() called during build. This widget cannot \
                     be marked as needing to build because the framework is already in the \
                     process of building widgets. A widget can be marked as needing to be \
                     built during the build phase only if one of its ancestors is currently \
                     building."
                );
            } else {
                assert!(
                    !owner.debug_state_locked(app),
                    "setState() or markNeedsBuild() called when widget tree was locked."
                );
            }
        }
        if this.dirty(app) {
            return;
        }
        this.data_mut(app).dirty = true;
        owner.schedule_build_for(app, this);
    }

    /// `Element._updateInheritance`.
    fn update_inheritance(self: Handle<Self>, app: &mut App) {
        let this = self.as_element();
        debug_assert!(this.lifecycle(app) == ElementLifecycle::Active);
        let inherited = this
            .parent(app)
            .and_then(|parent| parent.inherited_elements(app));
        this.set_inherited_elements(app, inherited);
    }

    /// `Element.renderObject`: walk down through the attaching children.
    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
        let this = self.as_element();
        let mut current = Some(this);
        while let Some(element) = current {
            if element.lifecycle(app) == ElementLifecycle::Defunct {
                break;
            } else if element.is_render_object_element() {
                return element.render_object(app);
            } else {
                current = element.render_object_attaching_child(app);
            }
        }
        None
    }
}
impl<T: Element> ElementBase for T {}

/// Dart's `_debugCheckOwnerBuildTargetExists`.
pub(crate) fn debug_check_owner_build_target_exists(
    this: AnyElement,
    app: &App,
    method_name: &str,
) -> bool {
    let owner = this.owner(app).expect("an active element has an owner");
    assert!(
        owner.debug_current_build_target(app).is_some(),
        "{method_name} for {:?} was called at an inappropriate time. It may only be called \
         while the widgets are being built.",
        this.widget(app)
    );
    true
}

fn debug_check_for_cycles(this: AnyElement, app: &App, new_child: AnyElement) -> bool {
    debug_assert!(new_child.parent(app).is_none());
    let mut node = this;
    while let Some(parent) = node.parent(app) {
        node = parent;
    }
    assert!(
        node != new_child,
        "about to create a cycle in the element tree"
    );
    true
}

/// The widget kinds the superclass check compares.
pub fn widget_kind(widget: &dyn Widget) -> WidgetKind {
    widget.kind()
}