waft-widgets 0.18.0

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
//! `Widget` and its kinds. A widget is an immutable value; the tree holds it as a shared
//! [`WidgetRef`]. Dart's `class Foo extends StatelessWidget` is `impl StatelessWidget for
//! Foo`, and a value becomes a tree node with [`IntoWidget::into_widget`].

use std::any::{Any, TypeId};
use std::fmt::{self, Debug};
use std::hash::{Hash, Hasher};
use std::panic::Location;
use std::rc::Rc;

use waft_foundation::{
    App, DiagnosticPropertiesBuilder, DiagnosticableNode, DiagnosticsTreeStyle, HandleId,
    IntoPropertyName, Key,
};
use waft_rendering::{
    AnyRenderObject, ContainerRenderObjectMixin, ErasedRenderObject, ParentData, RenderHandle,
    RenderObject, RenderObjectWithChildMixin,
};

use super::element::{AnyElement, BuildContext, Element};
use super::elements::{
    InheritedElement, LeafRenderObjectElement, MultiChildRenderObjectElement, ParentDataElement,
    SingleChildRenderObjectElement, StatefulElement, StatelessElement,
};
use super::state::{AnyState, State};
use crate::widgets::inherited_theme::InheritedTheme;
use crate::widgets::preferred_size::PreferredSizeWidget;

/// A widget's key (Dart's `Key?` on a widget): a local key, or a [`GlobalKey`], which is a
/// key the element tree registers.
///
/// Every key type converts into it with `.into()`: a [`GlobalKey`] into
/// [`Global`](Self::Global), any other [`Key`] (including an app's own) into
/// [`Local`](Self::Local).
#[derive(Clone)]
pub enum KeyRef {
    /// A key the element tree does not register (Dart's `LocalKey`).
    Local(Rc<dyn Key>),
    /// A key the element tree registers (Dart's `GlobalKey`).
    Global(GlobalKey),
}

impl KeyRef {
    /// The key that decides how this key compares.
    pub fn key(&self) -> &dyn Key {
        match self {
            KeyRef::Local(key) => &**key,
            KeyRef::Global(global) => global.key(),
        }
    }
}

impl PartialEq for KeyRef {
    fn eq(&self, other: &KeyRef) -> bool {
        match (self, other) {
            (KeyRef::Local(a), KeyRef::Local(b)) => **a == **b,
            (KeyRef::Global(a), KeyRef::Global(b)) => a == b,
            _ => false,
        }
    }
}

impl Eq for KeyRef {}

impl Hash for KeyRef {
    fn hash<H: Hasher>(&self, state: &mut H) {
        std::mem::discriminant(self).hash(state);
        self.key().hash(state);
    }
}

impl Debug for KeyRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            KeyRef::Local(key) => key.fmt(f),
            KeyRef::Global(global) => global.fmt(f),
        }
    }
}

impl<K: Key> From<K> for KeyRef {
    fn from(key: K) -> KeyRef {
        KeyRef::Local(Rc::new(key))
    }
}

impl From<GlobalKey> for KeyRef {
    fn from(key: GlobalKey) -> KeyRef {
        KeyRef::Global(key)
    }
}

/// A shared, immutable widget (Dart's `Widget` reference).
pub type WidgetRef = Rc<dyn Widget>;

/// Dart's `Widget.==`, which no widget can override: identity.
impl PartialEq for dyn Widget {
    fn eq(&self, other: &dyn Widget) -> bool {
        std::ptr::addr_eq(self as *const dyn Widget, other as *const dyn Widget)
    }
}

/// Describes the configuration for an `Element`.
///
/// Widgets are the central class hierarchy in the Flutter framework. A widget is an immutable
/// description of part of a user interface. Widgets can be inflated into elements, which
/// manage the underlying render tree.
///
/// This is the erased object every kind of widget becomes ([`IntoWidget`]); user code
/// implements a kind ([`StatelessWidget`], [`StatefulWidget`], …) rather than this trait.
pub trait Widget: Any + Debug {
    /// Controls how one widget replaces another widget in the tree.
    ///
    /// If the [`key`](Self::key) of the widget is the same as the key of the widget it is
    /// replacing (and the types are the same), the framework updates the existing element
    /// instead of creating a new one.
    fn key(&self) -> Option<&KeyRef>;

    /// Where the widget was made, in a debug build: Dart's creation location, which the widget
    /// inspector shows and its summary tree keeps the app's own widgets by.
    fn creation_location(&self) -> Option<&'static Location<'static>> {
        None
    }

    /// Keeps where the widget was made, for [`creation_location`](Self::creation_location) to
    /// answer: what `into_widget` calls on a widget that is its own tree node, which has no
    /// wrapper to keep it in. Such a widget keeps it in a field
    /// (`created: Option<CreationLocation>`); the default keeps nothing.
    fn record_creation_location(&mut self, location: CreationLocation) {
        let _ = location;
    }

    /// Dart's `toStringShort`: the type, then the key when there is one, as
    /// `Text-[<'title'>]`.
    fn to_string_short(&self) -> String {
        describe_widget(self.type_name(), self.key())
    }

    /// Dart's `debugFillProperties`: the properties a dump shows for this widget, in Dart's
    /// order. Dart's `Widget` base only sets the dense tree style, which
    /// [`to_diagnostics_node`](<dyn Widget>::to_diagnostics_node) does before calling this.
    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        let _ = properties;
    }

    /// Inflates this configuration to a concrete instance. `this` is this widget's shared
    /// reference, which the element keeps.
    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement;

    /// The concrete widget, for Dart's `widget as Foo`.
    fn as_any(&self) -> &dyn Any;

    /// The concrete widget's type, Dart's `runtimeType`.
    fn widget_type(&self) -> TypeId;

    /// The concrete widget's type name, as Dart's `runtimeType` prints in a message: the
    /// type's own name without its module path.
    ///
    /// The default names `Self`, so an erased form overrides it with
    /// [`short_type_name`]`::<W>()` of the widget it wraps.
    fn type_name(&self) -> &'static str {
        short_type_name::<Self>()
    }

    /// The kind of element this widget inflates to, for `Element.updateChild`'s superclass
    /// check.
    fn kind(&self) -> WidgetKind;

    /// Dart's `widget is InheritedTheme`: this widget as an [`InheritedTheme`], when it is one.
    ///
    /// Only the erased form of an inherited widget forwards it, from
    /// [`InheritedWidget::as_inherited_theme`]; `InheritedTheme::capture` also checks that the
    /// ancestor is an inherited element, as Dart's pattern does.
    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
        None
    }

    /// This widget as a [`RenderObjectWidget`], when it is one of the three kinds the framework
    /// makes elements for (leaf, single-child, multi-child): what those elements create and
    /// update their render object through, so they are not copied per widget type.
    fn as_render_object(&self) -> Option<&dyn AnyRenderObjectWidget> {
        None
    }

    /// This widget as a [`SingleChildRenderObjectWidget`], when it is one.
    fn as_single_child_render_object(&self) -> Option<&dyn AnySingleChildRenderObjectWidget> {
        None
    }

    /// This widget as a [`MultiChildRenderObjectWidget`], when it is one.
    fn as_multi_child_render_object(&self) -> Option<&dyn AnyMultiChildRenderObjectWidget> {
        None
    }

    /// This widget as a [`ParentDataWidget`], when it is one: what the one
    /// [`ParentDataElement`] reads, so that element is not copied per widget type.
    fn as_parent_data(&self) -> Option<&dyn AnyParentDataWidget> {
        None
    }

    /// This widget as a [`StatefulWidget`], when it is one: what the one [`StatefulElement`]
    /// creates its state through, so that element is not copied per widget type.
    fn as_stateful(&self) -> Option<&dyn AnyStatefulWidget> {
        None
    }

    /// This widget as an [`InheritedWidget`], when it is one: what the one
    /// [`InheritedElement`] reads, so that element is not copied per widget type.
    fn as_inherited(&self) -> Option<&dyn AnyInheritedWidget> {
        None
    }

    /// This widget as a [`StatelessWidget`], when it is one: what the one
    /// [`StatelessElement`] builds from, so that element is not copied per widget type.
    fn as_stateless(&self) -> Option<&dyn StatelessWidget> {
        None
    }

    /// Dart's `widget is PreferredSizeWidget`: this widget as a [`PreferredSizeWidget`], when
    /// it is one.
    ///
    /// The erased forms of a stateless and a stateful widget forward it, from
    /// [`StatelessWidget::as_preferred_size_widget`] and
    /// [`StatefulWidget::as_preferred_size_widget`].
    fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
        None
    }
}

impl dyn Widget {
    /// Dart's `Widget.toDiagnosticsNode(name:, style:)`: a snapshot of this widget's properties,
    /// in the dense style unless `style` says otherwise.
    pub fn to_diagnostics_node(
        &self,
        app: &App,
        name: impl IntoPropertyName,
        style: Option<DiagnosticsTreeStyle>,
    ) -> DiagnosticableNode {
        let mut properties = DiagnosticPropertiesBuilder::new();
        properties.default_diagnostics_tree_style = DiagnosticsTreeStyle::Dense;
        self.debug_fill_properties(app, &mut properties);
        let node = DiagnosticableNode::from_parts(name, self.to_string_short(), properties);
        match style {
            Some(style) => node.with_style(style),
            None => node,
        }
    }
}

/// Dart's `Widget.toStringShort`: `type_name`, then `-` and the key when there is one.
pub fn describe_widget(type_name: &str, key: Option<&KeyRef>) -> String {
    match key {
        Some(key) => format!("{type_name}-{key:?}"),
        None => type_name.to_string(),
    }
}

/// Dart's `Widget._debugConcreteSubtype` classes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WidgetKind {
    Stateful,
    Stateless,
    Other,
}

/// Whether the `new_widget` can be used to update an `Element` that currently has the
/// `old_widget` as its configuration.
///
/// An element that uses a given widget as its configuration can be updated to use another
/// widget as its configuration if, and only if, the two widgets have `runtimeType` and
/// [`Widget::key`] properties that are equal.
///
/// If the widgets have no key (their key is null), then they are considered a match if they
/// have the same type, even if their children are completely different.
pub fn can_update(old_widget: &dyn Widget, new_widget: &dyn Widget) -> bool {
    old_widget.widget_type() == new_widget.widget_type()
        && keys_equal(old_widget.key(), new_widget.key())
}

/// Dart's `oldWidget.key == newWidget.key`.
pub fn keys_equal(a: Option<&KeyRef>, b: Option<&KeyRef>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(a), Some(b)) => a == b,
        _ => false,
    }
}

/// Dart's `identical(a, b)` on two widget references: `Widget.==` is identity.
pub fn same_widget(a: &WidgetRef, b: &WidgetRef) -> bool {
    Rc::ptr_eq(a, b)
}

/// Dart's `widget as W`: the concrete widget behind a [`WidgetRef`], when it is a `W`.
pub fn downcast_widget<W: 'static>(widget: &dyn Widget) -> Option<&W> {
    widget.as_any().downcast_ref::<W>()
}

/// `W`'s name as Dart's `runtimeType` prints it, for [`Widget::type_name`]: the module path
/// before the type's own name is cut, and the type arguments are kept as Rust writes them.
pub fn short_type_name<W: ?Sized>() -> &'static str {
    without_module_path(std::any::type_name::<W>())
}

/// [`short_type_name`]'s cut, one body for every type.
fn without_module_path(name: &'static str) -> &'static str {
    let type_arguments = name.find('<').unwrap_or(name.len());
    let own_name = name[..type_arguments]
        .rfind("::")
        .map_or(0, |path_end| path_end + 2);
    &name[own_name..]
}

/// Where a widget was made, in a debug build: the line of the call that turned it into a
/// [`WidgetRef`], which a setter taking a child passes on from its own caller. Dart's
/// `--track-widget-creation` location, which is also kept in a debug build alone; a release build
/// keeps nothing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CreationLocation {
    #[cfg(debug_assertions)]
    location: &'static Location<'static>,
}

impl CreationLocation {
    /// The location of the call this one's caller was called from, as `#[track_caller]` carries
    /// it.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn of_caller() -> CreationLocation {
        CreationLocation {
            #[cfg(debug_assertions)]
            location: Location::caller(),
        }
    }

    /// The location, in a debug build.
    pub fn location(self) -> Option<&'static Location<'static>> {
        #[cfg(debug_assertions)]
        return Some(self.location);
        #[cfg(not(debug_assertions))]
        return None;
    }
}

/// The conversion of a widget value into a tree node.
///
/// Every widget kind gets a blanket implementation, told apart by the phantom `Kind` so the
/// implementations do not overlap; a call site infers it. A [`WidgetRef`] converts to itself, and
/// a widget that is its own tree node converts as itself ([`TreeNodeKind`]).
pub trait IntoWidget<Kind> {
    /// The widget as a tree node, made where this is called: its
    /// [`creation_location`](Widget::creation_location).
    #[cfg_attr(debug_assertions, track_caller)]
    fn into_widget(self) -> WidgetRef;
}

/// The kind tag of [`IntoWidget`] for a [`WidgetRef`].
pub struct WidgetRefKind;

impl IntoWidget<WidgetRefKind> for WidgetRef {
    fn into_widget(self) -> WidgetRef {
        self
    }
}

/// The kind tag of [`IntoWidget`] for a widget that is its own tree node: one implementing
/// [`Widget`] directly, whose element is its own rather than a wrapper's — a render object
/// widget that builds a child during layout (`LayoutBuilder`), a table (`Table`), a proxy widget
/// (`NotificationListener`), a collection of views (`ViewCollection`). It converts to itself,
/// which is what its inherent `into_widget` answers.
pub struct TreeNodeKind;

impl<W: Widget> IntoWidget<TreeNodeKind> for W {
    #[cfg_attr(debug_assertions, track_caller)]
    fn into_widget(mut self) -> WidgetRef {
        self.record_creation_location(CreationLocation::of_caller());
        Rc::new(self)
    }
}

// ---------------------------------------------------------------------------------------------
// StatelessWidget

/// A widget that does not require mutable state.
///
/// A stateless widget is a widget that describes part of the user interface by building a
/// constellation of other widgets that describe the user interface more concretely. The
/// building process continues recursively until the description of the user interface is
/// fully concrete (e.g., consists entirely of `RenderObjectWidget`s, which describe concrete
/// `RenderObject`s).
pub trait StatelessWidget: Debug + 'static {
    /// See [`Widget::key`].
    fn key(&self) -> Option<&KeyRef> {
        None
    }

    /// Dart's `debugFillProperties`: the properties a dump shows for this widget, in Dart's
    /// order. Dart's `Widget` base only sets the dense tree style, which the framework does.
    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        let _ = properties;
    }

    /// Dart's constructor asserts that relate two or more arguments.
    ///
    /// A fluent chain of setters has seen every argument only once it ends, so the framework
    /// calls this in a debug build when the widget is turned into a [`WidgetRef`]
    /// (`into_widget`), and a bad combination panics where the widget is handed to the tree.
    /// An assert on one argument stays in that argument's setter.
    fn debug_check_constructor(&self) {}

    /// Dart's `this is PreferredSizeWidget`: a widget that implements [`PreferredSizeWidget`]
    /// answers with itself, which is what a parent asking an erased child for its preferred
    /// size reads.
    fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
        None
    }

    /// Describes the part of the user interface represented by this widget.
    ///
    /// The framework calls this method when this widget is inserted into the tree in a given
    /// [`BuildContext`] and when the dependencies of this widget change (e.g., an
    /// `InheritedWidget` referenced by this widget changes). This method can potentially be
    /// called in every frame and should not have any side effects beyond building a widget.
    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef;
}

/// The kind tag of [`IntoWidget`] for a [`StatelessWidget`].
pub struct StatelessKind;

/// The erased form of a [`StatelessWidget`].
pub struct Stateless<W: StatelessWidget>(pub W, pub(crate) CreationLocation);

impl<W: StatelessWidget> IntoWidget<StatelessKind> for W {
    #[cfg_attr(debug_assertions, track_caller)]
    fn into_widget(self) -> WidgetRef {
        if cfg!(debug_assertions) {
            self.debug_check_constructor();
        }
        Rc::new(Stateless(self, CreationLocation::of_caller()))
    }
}

impl<W: StatelessWidget> Widget for Stateless<W> {
    fn key(&self) -> Option<&KeyRef> {
        self.0.key()
    }

    fn creation_location(&self) -> Option<&'static Location<'static>> {
        self.1.location()
    }

    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        self.0.debug_fill_properties(app, properties);
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        StatelessElement::new(app, this).as_element()
    }

    fn as_any(&self) -> &dyn Any {
        &self.0
    }

    fn widget_type(&self) -> TypeId {
        TypeId::of::<W>()
    }

    fn type_name(&self) -> &'static str {
        short_type_name::<W>()
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::Stateless
    }

    fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
        self.0.as_preferred_size_widget()
    }

    fn as_stateless(&self) -> Option<&dyn StatelessWidget> {
        Some(&self.0)
    }
}

impl<W: StatelessWidget> Debug for Stateless<W> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

// ---------------------------------------------------------------------------------------------
// StatefulWidget

/// A widget that has mutable state.
///
/// State is information that (1) can be read synchronously when the widget is built and (2)
/// might change during the lifetime of the widget. It is the responsibility of the widget
/// implementer to ensure that the [`State`] is promptly notified when such state changes,
/// using `State::set_state`.
///
/// A stateful widget is a widget that describes part of the user interface by building a
/// constellation of other widgets that describe the user interface more concretely.
///
/// Dart's `createState` returns any `State<Foo>`; here the state class is the associated
/// type [`State`](Self::State), which is what `State<T>`'s type argument already fixed.
///
/// Make one when the widget owns a Flutter object between builds — a
/// [`TextEditingController`](crate::TextEditingController), a [`FocusNode`](crate::FocusNode),
/// an [`AnimationController`](crate::AnimationController). The app's data lives in an
/// [`Entity`](waft_foundation::Entity), which a [`StatelessWidget`] reads in `build` and is
/// rebuilt by when it notifies; see [`State`].
pub trait StatefulWidget: Debug + 'static {
    /// The state this widget creates.
    type State: State<Widget = Self>;

    /// See [`Widget::key`].
    fn key(&self) -> Option<&KeyRef> {
        None
    }

    /// Dart's `debugFillProperties`: the properties a dump shows for this widget, in Dart's
    /// order. Dart's `Widget` base only sets the dense tree style, which the framework does.
    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        let _ = properties;
    }

    /// See [`StatelessWidget::debug_check_constructor`].
    fn debug_check_constructor(&self) {}

    /// See [`StatelessWidget::as_preferred_size_widget`].
    fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
        None
    }

    /// See [`Widget::type_name`]. A stateful form another widget kind becomes (an animated or
    /// status transition widget) names the widget it wraps.
    fn type_name(&self) -> &'static str {
        short_type_name::<Self>()
    }

    /// Creates the mutable state for this widget at a given location in the tree.
    ///
    /// The framework can call this method multiple times over the lifetime of a
    /// [`StatefulWidget`]. For example, if the widget is inserted into the tree in multiple
    /// locations, the framework will create a separate [`State`] object for each location.
    /// Similarly, if the widget is removed from the tree and later inserted in to the tree
    /// again, the framework will call [`create_state`](Self::create_state) again to create a
    /// fresh [`State`] object, simplifying the lifecycle of [`State`] objects.
    fn create_state(&self) -> Self::State;
}

/// The kind tag of [`IntoWidget`] for a [`StatefulWidget`].
pub struct StatefulKind;

/// The erased form of a [`StatefulWidget`].
pub struct Stateful<W: StatefulWidget>(pub W, pub(crate) CreationLocation);

impl<W: StatefulWidget> IntoWidget<StatefulKind> for W {
    #[cfg_attr(debug_assertions, track_caller)]
    fn into_widget(self) -> WidgetRef {
        if cfg!(debug_assertions) {
            self.debug_check_constructor();
        }
        Rc::new(Stateful(self, CreationLocation::of_caller()))
    }
}

impl<W: StatefulWidget> Widget for Stateful<W> {
    fn key(&self) -> Option<&KeyRef> {
        self.0.key()
    }

    fn creation_location(&self) -> Option<&'static Location<'static>> {
        self.1.location()
    }

    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        self.0.debug_fill_properties(app, properties);
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        StatefulElement::new(app, this).as_element()
    }

    fn as_any(&self) -> &dyn Any {
        &self.0
    }

    fn widget_type(&self) -> TypeId {
        TypeId::of::<W>()
    }

    fn type_name(&self) -> &'static str {
        StatefulWidget::type_name(&self.0)
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::Stateful
    }

    fn as_stateful(&self) -> Option<&dyn AnyStatefulWidget> {
        Some(self)
    }

    fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
        self.0.as_preferred_size_widget()
    }
}

impl<W: StatefulWidget> AnyStatefulWidget for Stateful<W> {
    fn create_state(&self, app: &mut App) -> AnyState {
        let state = app.create(self.0.create_state()).into_tree_node(app);
        AnyState::of(state)
    }
}

/// A [`StatefulWidget`] of any type, as the one [`StatefulElement`] reaches it.
pub trait AnyStatefulWidget {
    /// [`StatefulWidget::create_state`], with the state put in the arena for its element.
    fn create_state(&self, app: &mut App) -> AnyState;
}

impl<W: StatefulWidget> Debug for Stateful<W> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

// ---------------------------------------------------------------------------------------------
// ProxyWidget: ParentDataWidget, InheritedWidget

/// Base class for widgets that efficiently propagate information down the tree.
///
/// To obtain the nearest instance of a particular type of inherited widget from a build
/// context, use `BuildContext::depend_on_inherited_widget_of_exact_type`.
///
/// Inherited widgets, when referenced in this way, will cause the consumer to rebuild when
/// the inherited widget itself changes state.
pub trait InheritedWidget: Debug + 'static {
    /// See [`Widget::key`].
    fn key(&self) -> Option<&KeyRef> {
        None
    }

    /// Dart's `debugFillProperties`: the properties a dump shows for this widget, in Dart's
    /// order. Dart's `Widget` base only sets the dense tree style, which the framework does.
    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        let _ = properties;
    }

    /// See [`StatelessWidget::debug_check_constructor`].
    fn debug_check_constructor(&self) {}

    /// The widget below this widget in the tree.
    fn child(&self) -> &WidgetRef;

    /// Whether the framework should notify widgets that inherit from this widget.
    ///
    /// When this widget is rebuilt, sometimes we need to rebuild the widgets that inherit
    /// from this widget but sometimes we do not. For example, if the data held by this widget
    /// is the same as the data held by `old_widget`, then we do not need to rebuild the
    /// widgets that inherited the data held by `old_widget`.
    ///
    /// The framework distinguishes these cases by calling this function with the widget that
    /// previously occupied this location in the tree as an argument. The given widget is
    /// guaranteed to have the same `runtimeType` as this object.
    fn update_should_notify(&self, old_widget: &Self) -> bool;

    /// Dart's `this is InheritedTheme`: an inherited widget that is an [`InheritedTheme`]
    /// answers with itself, which is what `InheritedTheme::capture` collects.
    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
        None
    }
}

/// The kind tag of [`IntoWidget`] for an [`InheritedWidget`].
pub struct InheritedKind;

/// The erased form of an [`InheritedWidget`].
pub struct Inherited<W: InheritedWidget>(pub W, pub(crate) CreationLocation);

impl<W: InheritedWidget> IntoWidget<InheritedKind> for W {
    #[cfg_attr(debug_assertions, track_caller)]
    fn into_widget(self) -> WidgetRef {
        if cfg!(debug_assertions) {
            self.debug_check_constructor();
        }
        Rc::new(Inherited(self, CreationLocation::of_caller()))
    }
}

impl<W: InheritedWidget> Widget for Inherited<W> {
    fn key(&self) -> Option<&KeyRef> {
        self.0.key()
    }

    fn creation_location(&self) -> Option<&'static Location<'static>> {
        self.1.location()
    }

    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        self.0.debug_fill_properties(app, properties);
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        InheritedElement::new(app, this).as_element()
    }

    fn as_any(&self) -> &dyn Any {
        &self.0
    }

    fn widget_type(&self) -> TypeId {
        TypeId::of::<W>()
    }

    fn type_name(&self) -> &'static str {
        short_type_name::<W>()
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::Other
    }

    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
        self.0.as_inherited_theme()
    }

    fn as_inherited(&self) -> Option<&dyn AnyInheritedWidget> {
        Some(self)
    }
}

impl<W: InheritedWidget> AnyInheritedWidget for Inherited<W> {
    fn child(&self) -> &WidgetRef {
        self.0.child()
    }

    fn update_should_notify(&self, old_widget: &dyn Widget) -> bool {
        let old_widget =
            downcast_widget::<W>(old_widget).expect("the old widget has the same type");
        self.0.update_should_notify(old_widget)
    }
}

/// An [`InheritedWidget`] of any type, as the one [`InheritedElement`] reads it.
pub trait AnyInheritedWidget {
    /// See [`InheritedWidget::child`].
    fn child(&self) -> &WidgetRef;

    /// [`InheritedWidget::update_should_notify`] against an `old_widget` of the same type.
    fn update_should_notify(&self, old_widget: &dyn Widget) -> bool;
}

impl<W: InheritedWidget> Debug for Inherited<W> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// Base class for widgets that hook `ParentData` information for children of
/// `RenderObjectWidget`s.
///
/// This can be used to provide per-child configuration for `RenderObjectWidget`s with more
/// than one child. For example, `Stack` uses the `Positioned` parent data widget to position
/// each child.
pub trait ParentDataWidget: Debug + 'static {
    /// The parent data this widget writes; Dart's `T extends ParentData`.
    type ParentData: ParentData + 'static;

    /// See [`Widget::key`].
    fn key(&self) -> Option<&KeyRef> {
        None
    }

    /// Dart's `debugFillProperties`: the properties a dump shows for this widget, in Dart's
    /// order. Dart's `Widget` base only sets the dense tree style, which the framework does.
    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        let _ = properties;
    }

    /// See [`StatelessWidget::debug_check_constructor`].
    fn debug_check_constructor(&self) {}

    /// The widget below this widget in the tree.
    fn child(&self) -> &WidgetRef;

    /// Write the data from this widget into the given render object's parent data.
    ///
    /// The framework calls this function whenever it detects that the `RenderObject`
    /// associated with the [`child`](Self::child) has outdated `parent_data`. The parent data
    /// is the data that the parent of the render object uses when laying out and painting the
    /// render object.
    ///
    /// This function is responsible for calling `mark_needs_layout` on the render object as
    /// appropriate.
    fn apply_parent_data(&self, app: &mut App, render_object: AnyRenderObject);

    /// Dart's `debugIsValidRenderObject`: whether `render_object`'s parent data is the one
    /// this widget writes.
    ///
    /// The default answers `render_object.parent_data_is::<Self::ParentData>(app)`. A widget
    /// whose Dart counterpart also accepts a subclass of its `ParentData` — `Positioned` on a
    /// `_TheaterParentData` — overrides this to accept that type too.
    fn debug_is_valid_render_object(
        &self,
        app: &App,
        render_object: ::waft_rendering::AnyRenderObject,
    ) -> bool {
        render_object.parent_data_is::<Self::ParentData>(app)
    }

    /// Whether the `ParentDataElement::apply_widget_out_of_turn` method will be allowed
    /// with this widget.
    ///
    /// This should only return true if this widget represents a `ParentData` configuration
    /// that will have no impact on the layout or paint phase.
    fn debug_can_apply_out_of_turn(&self) -> bool {
        false
    }
}

/// The kind tag of [`IntoWidget`] for a [`ParentDataWidget`].
pub struct ParentDataKind;

/// The erased form of a [`ParentDataWidget`].
pub struct ParentDataWrapper<W: ParentDataWidget>(pub W, pub(crate) CreationLocation);

impl<W: ParentDataWidget> IntoWidget<ParentDataKind> for W {
    #[cfg_attr(debug_assertions, track_caller)]
    fn into_widget(self) -> WidgetRef {
        if cfg!(debug_assertions) {
            self.debug_check_constructor();
        }
        Rc::new(ParentDataWrapper(self, CreationLocation::of_caller()))
    }
}

impl<W: ParentDataWidget> Widget for ParentDataWrapper<W> {
    fn key(&self) -> Option<&KeyRef> {
        self.0.key()
    }

    fn creation_location(&self) -> Option<&'static Location<'static>> {
        self.1.location()
    }

    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        self.0.debug_fill_properties(app, properties);
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        ParentDataElement::new(app, this).as_element()
    }

    fn as_any(&self) -> &dyn Any {
        &self.0
    }

    fn widget_type(&self) -> TypeId {
        TypeId::of::<W>()
    }

    fn type_name(&self) -> &'static str {
        short_type_name::<W>()
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::Other
    }

    fn as_parent_data(&self) -> Option<&dyn AnyParentDataWidget> {
        Some(self)
    }
}

impl<W: ParentDataWidget> AnyParentDataWidget for ParentDataWrapper<W> {
    fn child(&self) -> &WidgetRef {
        self.0.child()
    }

    fn apply_parent_data(&self, app: &mut App, render_object: AnyRenderObject) {
        self.0.apply_parent_data(app, render_object);
    }

    fn debug_is_valid_render_object(&self, app: &App, render_object: AnyRenderObject) -> bool {
        self.0.debug_is_valid_render_object(app, render_object)
    }

    fn parent_data_type_name(&self) -> &'static str {
        std::any::type_name::<W::ParentData>()
    }
}

/// A [`ParentDataWidget`] of any type, as the one [`ParentDataElement`] reads it.
pub trait AnyParentDataWidget: Debug {
    /// See [`ParentDataWidget::child`].
    fn child(&self) -> &WidgetRef;

    /// See [`ParentDataWidget::apply_parent_data`].
    fn apply_parent_data(&self, app: &mut App, render_object: AnyRenderObject);

    /// See [`ParentDataWidget::debug_is_valid_render_object`].
    fn debug_is_valid_render_object(&self, app: &App, render_object: AnyRenderObject) -> bool;

    /// The name of [`ParentDataWidget::ParentData`], for the message of an invalid use.
    fn parent_data_type_name(&self) -> &'static str;
}

impl<W: ParentDataWidget> Debug for ParentDataWrapper<W> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

// ---------------------------------------------------------------------------------------------
// RenderObjectWidget

/// The parts of a `RenderObjectWidget` every kind shares: the render object it creates and
/// updates. Dart's `covariant RenderObject renderObject` parameters are typed through
/// [`RenderObject`](Self::RenderObject).
pub trait RenderObjectWidget: Debug + 'static {
    /// The render object this widget creates; Dart's `covariant RenderObject` parameter type.
    type RenderObject: RenderObject;

    /// See [`Widget::key`].
    fn key(&self) -> Option<&KeyRef> {
        None
    }

    /// Dart's `debugFillProperties`: the properties a dump shows for this widget, in Dart's
    /// order. Dart's `Widget` base only sets the dense tree style, which the framework does.
    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        let _ = properties;
    }

    /// Dart's `toStringShort`, for a widget that names itself apart from its type, as
    /// `SizedBox.expand` does; see [`Widget::to_string_short`].
    fn to_string_short(&self) -> String {
        describe_widget(short_type_name::<Self>(), self.key())
    }

    /// See [`StatelessWidget::debug_check_constructor`].
    fn debug_check_constructor(&self) {}

    /// Dart's `debugVisitOnstageChildren` of the element this widget makes, for a widget whose
    /// Dart element subclass overrides it only to hide children (`_OffstageElement`,
    /// `_IndexedStackElement`): calls `visitor` for each of `children`, in order, that is
    /// onstage. Waft's generic single- and multi-child elements stand in for those subclasses
    /// and ask their widget here; an element of a widget's own overrides
    /// [`Element::debug_visit_onstage_children`] instead.
    fn debug_visit_onstage_children(
        &self,
        app: &App,
        children: &[AnyElement],
        visitor: &mut dyn FnMut(AnyElement),
    ) {
        let _ = app;
        children.iter().for_each(|child| visitor(*child));
    }

    /// Creates an instance of the `RenderObject` class that this widget represents, using the
    /// configuration described by this widget.
    ///
    /// This method should not do anything with the children of the render object. That
    /// should instead be handled by the method that overrides `RenderObjectElement.mount`
    /// in the object rendered by this object's `create_element` method.
    ///
    /// Returns the type-erased handle (`handle.as_object()`), which is what the element tree holds;
    /// [`update_render_object`](Self::update_render_object) gets the typed handle back.
    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject;

    /// Copies the configuration described by this widget to the given render object, which
    /// will be of the same type as returned by this object's
    /// [`create_render_object`](Self::create_render_object).
    ///
    /// This method should not do anything to update the children of the render object. That
    /// should instead be handled by the method that overrides `RenderObjectElement.update`
    /// in the object rendered by this object's `create_element` method.
    fn update_render_object(
        &self,
        app: &mut App,
        context: BuildContext,
        render_object: RenderHandle<Self::RenderObject>,
    ) {
        let _ = (app, context, render_object);
    }

    /// A render object previously associated with this widget has been removed from the tree.
    /// The given `RenderObject` will be of the same type as returned by this object's
    /// [`create_render_object`](Self::create_render_object).
    fn did_unmount_render_object(
        &self,
        app: &mut App,
        render_object: RenderHandle<Self::RenderObject>,
    ) {
        let _ = (app, render_object);
    }
}

/// A superclass for `RenderObjectWidget`s that configure `RenderObject` subclasses that have
/// no children.
pub trait LeafRenderObjectWidget: RenderObjectWidget {}

/// The kind tag of [`IntoWidget`] for a [`LeafRenderObjectWidget`].
pub struct LeafRenderObjectKind;

/// The erased form of a [`LeafRenderObjectWidget`].
pub struct LeafRenderObject<W: LeafRenderObjectWidget>(pub W, pub(crate) CreationLocation);

impl<W: LeafRenderObjectWidget> IntoWidget<LeafRenderObjectKind> for W {
    #[cfg_attr(debug_assertions, track_caller)]
    fn into_widget(self) -> WidgetRef {
        if cfg!(debug_assertions) {
            RenderObjectWidget::debug_check_constructor(&self);
        }
        Rc::new(LeafRenderObject(self, CreationLocation::of_caller()))
    }
}

impl<W: LeafRenderObjectWidget> Widget for LeafRenderObject<W> {
    fn key(&self) -> Option<&KeyRef> {
        self.0.key()
    }

    fn creation_location(&self) -> Option<&'static Location<'static>> {
        self.1.location()
    }

    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        self.0.debug_fill_properties(app, properties);
    }

    fn to_string_short(&self) -> String {
        self.0.to_string_short()
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        LeafRenderObjectElement::new(app, this).as_element()
    }

    fn as_any(&self) -> &dyn Any {
        &self.0
    }

    fn widget_type(&self) -> TypeId {
        TypeId::of::<W>()
    }

    fn type_name(&self) -> &'static str {
        short_type_name::<W>()
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::Other
    }

    fn as_render_object(&self) -> Option<&dyn AnyRenderObjectWidget> {
        Some(self)
    }
}

impl<W: LeafRenderObjectWidget> Debug for LeafRenderObject<W> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// A superclass for `RenderObjectWidget`s that configure `RenderObject` subclasses that have
/// a single child slot.
///
/// The render object assigned to this widget should make use of
/// `RenderObjectWithChildMixin` to implement a single child model.
pub trait SingleChildRenderObjectWidget: RenderObjectWidget
where
    Self::RenderObject: RenderObjectWithChildMixin,
{
    /// The widget below this widget in the tree.
    fn child(&self) -> Option<&WidgetRef>;

    /// Creates the element that manages this widget's child.
    ///
    /// Dart's `createElement`; a widget whose element has bodies of its own
    /// (`SingleChildScrollView`'s viewport) overrides it with an element that implements
    /// `SingleChildRenderObjectElementBase`.
    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement
    where
        Self: Sized,
    {
        SingleChildRenderObjectElement::new(app, this).as_element()
    }
}

/// The kind tag of [`IntoWidget`] for a [`SingleChildRenderObjectWidget`].
pub struct SingleChildRenderObjectKind;

/// The erased form of a [`SingleChildRenderObjectWidget`].
pub struct SingleChildRenderObject<W: SingleChildRenderObjectWidget>(
    pub W,
    pub(crate) CreationLocation,
)
where
    W::RenderObject: RenderObjectWithChildMixin;

impl<W: SingleChildRenderObjectWidget> IntoWidget<SingleChildRenderObjectKind> for W
where
    W::RenderObject: RenderObjectWithChildMixin,
{
    #[cfg_attr(debug_assertions, track_caller)]
    fn into_widget(self) -> WidgetRef {
        if cfg!(debug_assertions) {
            RenderObjectWidget::debug_check_constructor(&self);
        }
        Rc::new(SingleChildRenderObject(self, CreationLocation::of_caller()))
    }
}

impl<W: SingleChildRenderObjectWidget> Widget for SingleChildRenderObject<W>
where
    W::RenderObject: RenderObjectWithChildMixin,
{
    fn key(&self) -> Option<&KeyRef> {
        self.0.key()
    }

    fn creation_location(&self) -> Option<&'static Location<'static>> {
        self.1.location()
    }

    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        self.0.debug_fill_properties(app, properties);
    }

    fn to_string_short(&self) -> String {
        self.0.to_string_short()
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        SingleChildRenderObjectWidget::create_element(&self.0, app, this)
    }

    fn as_any(&self) -> &dyn Any {
        &self.0
    }

    fn widget_type(&self) -> TypeId {
        TypeId::of::<W>()
    }

    fn type_name(&self) -> &'static str {
        short_type_name::<W>()
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::Other
    }

    fn as_render_object(&self) -> Option<&dyn AnyRenderObjectWidget> {
        Some(self)
    }

    fn as_single_child_render_object(&self) -> Option<&dyn AnySingleChildRenderObjectWidget> {
        Some(self)
    }
}

impl<W: SingleChildRenderObjectWidget> Debug for SingleChildRenderObject<W>
where
    W::RenderObject: RenderObjectWithChildMixin,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// A superclass for `RenderObjectWidget`s that configure `RenderObject` subclasses that have a
/// single list of children. (This superclass only provides the storage for that child list, it
/// doesn't actually provide the updating logic.)
///
/// The render object assigned to this widget must use `ContainerRenderObjectMixin`, which
/// provides the necessary functionality to visit the children of the container render object
/// (the render object belonging to the [`children`](Self::children) widgets).
///
/// See also:
///
///  * `Stack`, which uses [`MultiChildRenderObjectWidget`].
///  * `RenderStack`, for an example implementation of the associated render object.
pub trait MultiChildRenderObjectWidget: RenderObjectWidget
where
    Self::RenderObject: ContainerRenderObjectMixin,
{
    /// The widgets below this widget in the tree.
    ///
    /// If this list is going to be mutated, it is usually wise to put a [`Key`] on each of the
    /// child widgets, so that the framework can match old configurations to new configurations
    /// and maintain the underlying render objects.
    ///
    /// Also, a widget is immutable, so directly modifying the [`children`](Self::children) of a
    /// widget already in the tree results in incorrect behaviour. Whenever the children list is
    /// modified, a new list should be provided.
    fn children(&self) -> &[WidgetRef];

    /// Creates the element that manages this widget's children.
    ///
    /// Dart's `createElement`; a widget whose element has bodies of its own (`Viewport`)
    /// overrides it with an element that implements `MultiChildRenderObjectElementBase`.
    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement
    where
        Self: Sized,
    {
        MultiChildRenderObjectElement::new(app, this).as_element()
    }
}

/// The kind tag of [`IntoWidget`] for a [`MultiChildRenderObjectWidget`].
pub struct MultiChildRenderObjectKind;

/// The erased form of a [`MultiChildRenderObjectWidget`].
pub struct MultiChildRenderObject<W: MultiChildRenderObjectWidget>(
    pub W,
    pub(crate) CreationLocation,
)
where
    W::RenderObject: ContainerRenderObjectMixin;

impl<W: MultiChildRenderObjectWidget> IntoWidget<MultiChildRenderObjectKind> for W
where
    W::RenderObject: ContainerRenderObjectMixin,
{
    #[cfg_attr(debug_assertions, track_caller)]
    fn into_widget(self) -> WidgetRef {
        if cfg!(debug_assertions) {
            RenderObjectWidget::debug_check_constructor(&self);
        }
        Rc::new(MultiChildRenderObject(self, CreationLocation::of_caller()))
    }
}

impl<W: MultiChildRenderObjectWidget> Widget for MultiChildRenderObject<W>
where
    W::RenderObject: ContainerRenderObjectMixin,
{
    fn key(&self) -> Option<&KeyRef> {
        self.0.key()
    }

    fn creation_location(&self) -> Option<&'static Location<'static>> {
        self.1.location()
    }

    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        self.0.debug_fill_properties(app, properties);
    }

    fn to_string_short(&self) -> String {
        self.0.to_string_short()
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        MultiChildRenderObjectWidget::create_element(&self.0, app, this)
    }

    fn as_any(&self) -> &dyn Any {
        &self.0
    }

    fn widget_type(&self) -> TypeId {
        TypeId::of::<W>()
    }

    fn type_name(&self) -> &'static str {
        short_type_name::<W>()
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::Other
    }

    fn as_render_object(&self) -> Option<&dyn AnyRenderObjectWidget> {
        Some(self)
    }

    fn as_multi_child_render_object(&self) -> Option<&dyn AnyMultiChildRenderObjectWidget> {
        Some(self)
    }
}

impl<W: MultiChildRenderObjectWidget> Debug for MultiChildRenderObject<W>
where
    W::RenderObject: ContainerRenderObjectMixin,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// A [`RenderObjectWidget`] of any type, as the framework's render object elements reach it:
/// its render object calls with the render object erased, so those elements are not copied per
/// widget type.
pub trait AnyRenderObjectWidget {
    /// See [`RenderObjectWidget::create_render_object`].
    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject;

    /// [`RenderObjectWidget::update_render_object`] on the render object this widget's type
    /// creates.
    fn update_render_object(
        &self,
        app: &mut App,
        context: BuildContext,
        render_object: AnyRenderObject,
    );

    /// [`RenderObjectWidget::did_unmount_render_object`] on the render object this widget's type
    /// creates.
    fn did_unmount_render_object(&self, app: &mut App, render_object: AnyRenderObject);

    /// See [`RenderObjectWidget::debug_visit_onstage_children`].
    fn debug_visit_onstage_children(
        &self,
        app: &App,
        children: &[AnyElement],
        visitor: &mut dyn FnMut(AnyElement),
    );
}

/// A [`SingleChildRenderObjectWidget`] of any type: its child, and its render object's child
/// slot (`RenderObjectWithChildMixin`) with the render objects erased.
pub trait AnySingleChildRenderObjectWidget: AnyRenderObjectWidget {
    /// See [`SingleChildRenderObjectWidget::child`].
    fn child(&self) -> Option<&WidgetRef>;

    /// The child of `render_object`, which this widget's type created.
    fn render_object_child(
        &self,
        app: &App,
        render_object: AnyRenderObject,
    ) -> Option<AnyRenderObject>;

    /// Sets the child of `render_object`, which this widget's type created.
    fn set_render_object_child(
        &self,
        app: &mut App,
        render_object: AnyRenderObject,
        child: Option<AnyRenderObject>,
    );
}

/// A [`MultiChildRenderObjectWidget`] of any type: its children, and its render object's child
/// list (`ContainerRenderObjectMixin`) with the render objects erased.
pub trait AnyMultiChildRenderObjectWidget: AnyRenderObjectWidget {
    /// See [`MultiChildRenderObjectWidget::children`].
    fn children(&self) -> &[WidgetRef];

    /// Inserts `child` into `render_object`'s child list after `after`, or first.
    fn insert_render_object_child(
        &self,
        app: &mut App,
        render_object: AnyRenderObject,
        child: AnyRenderObject,
        after: Option<AnyRenderObject>,
    );

    /// Moves `child` in `render_object`'s child list to after `after`, or first.
    fn move_render_object_child(
        &self,
        app: &mut App,
        render_object: AnyRenderObject,
        child: AnyRenderObject,
        after: Option<AnyRenderObject>,
    );

    /// Removes `child` from `render_object`'s child list.
    fn remove_render_object_child(
        &self,
        app: &mut App,
        render_object: AnyRenderObject,
        child: AnyRenderObject,
    );
}

/// The [`AnyRenderObjectWidget`] calls of an erased render object widget `$wrapper<W>`.
macro_rules! any_render_object_widget_calls {
    () => {
        fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
            self.0.create_render_object(app, context)
        }

        fn update_render_object(
            &self,
            app: &mut App,
            context: BuildContext,
            render_object: AnyRenderObject,
        ) {
            let render_object = typed_render_object::<W>(app, render_object);
            self.0.update_render_object(app, context, render_object);
        }

        fn did_unmount_render_object(&self, app: &mut App, render_object: AnyRenderObject) {
            let render_object = typed_render_object::<W>(app, render_object);
            self.0.did_unmount_render_object(app, render_object);
        }

        fn debug_visit_onstage_children(
            &self,
            app: &App,
            children: &[AnyElement],
            visitor: &mut dyn FnMut(AnyElement),
        ) {
            self.0.debug_visit_onstage_children(app, children, visitor);
        }
    };
}

/// `render_object` as the render object `W` creates.
fn typed_render_object<W: RenderObjectWidget>(
    app: &App,
    render_object: AnyRenderObject,
) -> RenderHandle<W::RenderObject> {
    render_object
        .downcast(app)
        .expect("the render object this widget created")
}

impl<W: LeafRenderObjectWidget> AnyRenderObjectWidget for LeafRenderObject<W> {
    any_render_object_widget_calls!();
}

impl<W: SingleChildRenderObjectWidget> AnyRenderObjectWidget for SingleChildRenderObject<W>
where
    W::RenderObject: RenderObjectWithChildMixin,
{
    any_render_object_widget_calls!();
}

impl<W: SingleChildRenderObjectWidget> AnySingleChildRenderObjectWidget
    for SingleChildRenderObject<W>
where
    W::RenderObject: RenderObjectWithChildMixin,
{
    fn child(&self) -> Option<&WidgetRef> {
        self.0.child()
    }

    fn render_object_child(
        &self,
        app: &App,
        render_object: AnyRenderObject,
    ) -> Option<AnyRenderObject> {
        typed_render_object::<W>(app, render_object)
            .child(app)
            .map(ErasedRenderObject::as_object)
    }

    fn set_render_object_child(
        &self,
        app: &mut App,
        render_object: AnyRenderObject,
        child: Option<AnyRenderObject>,
    ) {
        typed_render_object::<W>(app, render_object)
            .set_child(app, child.map(ErasedRenderObject::from_object));
    }
}

impl<W: MultiChildRenderObjectWidget> AnyRenderObjectWidget for MultiChildRenderObject<W>
where
    W::RenderObject: ContainerRenderObjectMixin,
{
    any_render_object_widget_calls!();
}

impl<W: MultiChildRenderObjectWidget> AnyMultiChildRenderObjectWidget for MultiChildRenderObject<W>
where
    W::RenderObject: ContainerRenderObjectMixin,
{
    fn children(&self) -> &[WidgetRef] {
        self.0.children()
    }

    fn insert_render_object_child(
        &self,
        app: &mut App,
        render_object: AnyRenderObject,
        child: AnyRenderObject,
        after: Option<AnyRenderObject>,
    ) {
        typed_render_object::<W>(app, render_object).insert(
            app,
            ErasedRenderObject::from_object(child),
            after.map(ErasedRenderObject::from_object),
        );
    }

    fn move_render_object_child(
        &self,
        app: &mut App,
        render_object: AnyRenderObject,
        child: AnyRenderObject,
        after: Option<AnyRenderObject>,
    ) {
        typed_render_object::<W>(app, render_object).move_child(
            app,
            ErasedRenderObject::from_object(child),
            after.map(ErasedRenderObject::from_object),
        );
    }

    fn remove_render_object_child(
        &self,
        app: &mut App,
        render_object: AnyRenderObject,
        child: AnyRenderObject,
    ) {
        typed_render_object::<W>(app, render_object)
            .remove(app, ErasedRenderObject::from_object(child));
    }
}

// ---------------------------------------------------------------------------------------------
// GlobalKey

/// A key that is unique across the entire app.
///
/// Global keys uniquely identify elements. Global keys provide access to other objects that
/// are associated with those elements, such as `BuildContext`. For [`StatefulWidget`]s,
/// global keys also provide access to [`State`].
///
/// Widgets that have global keys reparent their subtrees when they are moved from one
/// location in the tree to another location in the tree. In order to reparent its subtree, a
/// widget must arrive at its new location in the tree in the same animation frame in which
/// it was removed from its old location in the tree.
///
/// Reparenting an `Element` using a global key is relatively expensive, as this operation
/// will trigger a call to `State::deactivate` on the associated [`State`] and all of its
/// descendants; then force all widgets that depends on an `InheritedWidget` to rebuild.
///
/// A global key is a key the element tree registers: it compares and hashes as the [`Key`] it
/// wraps, and the registry maps it to its element as Dart's `Map<GlobalKey, Element>` does.
/// [`new`](Self::new) and [`labeled`](Self::labeled) compare by themselves (Dart's
/// `LabeledGlobalKey`), [`object`](Self::object) by an object (Dart's `GlobalObjectKey`), and
/// [`wrapping`](Self::wrapping) as the key it is given (Dart's subclasses that override `==`).
/// Cloning shares the key. Dart's type argument names the state; here
/// [`current_state`](Self::current_state) does.
#[derive(Clone)]
pub struct GlobalKey {
    key: Rc<dyn Key>,
}

impl GlobalKey {
    /// Creates a global key that is equal only to itself and its clones; Dart's factory
    /// `GlobalKey()`, a `LabeledGlobalKey` without a label.
    #[expect(
        clippy::new_without_default,
        reason = "each call creates a distinct key; Default would suggest a neutral value"
    )]
    pub fn new() -> GlobalKey {
        GlobalKey::wrapping(Rc::new(LabeledGlobalKeyValue::new(None)))
    }

    /// Creates a global key with a debugging label (Dart's `LabeledGlobalKey`).
    ///
    /// The label does not affect the key's identity.
    pub fn labeled(debug_label: impl Into<String>) -> GlobalKey {
        GlobalKey::wrapping(Rc::new(LabeledGlobalKeyValue::new(Some(
            debug_label.into(),
        ))))
    }

    /// Creates a global key that uses the identity of `value` for its `==` (Dart's
    /// `GlobalObjectKey`).
    ///
    /// An object's identity is its [`Handle`](waft_foundation::Handle): Dart's
    /// `GlobalObjectKey(this)` in a `State` is `GlobalKey::object(self.id())`.
    pub fn object(value: impl Into<HandleId>) -> GlobalKey {
        GlobalKey::wrapping(Rc::new(GlobalObjectKeyValue {
            value: value.into(),
        }))
    }

    /// Creates a global key that compares and hashes as `key`: Dart's `GlobalKey` subclasses
    /// that override `==` and `hashCode`, such as `_ReorderableItemGlobalKey`.
    ///
    /// Two global keys wrapping equal keys name the same element.
    pub fn wrapping(key: Rc<dyn Key>) -> GlobalKey {
        GlobalKey { key }
    }

    /// The key this global key compares and hashes as.
    pub fn key(&self) -> &dyn Key {
        &*self.key
    }

    /// The build context in which the widget with this key builds.
    ///
    /// The current context is `None` if there is no widget in the tree that matches this
    /// global key.
    pub fn current_context(&self, app: &App) -> Option<BuildContext> {
        self.current_element(app)
    }

    /// The widget in the tree that currently has this global key.
    ///
    /// The current widget is `None` if there is no widget in the tree that matches this
    /// global key.
    pub fn current_widget(&self, app: &App) -> Option<WidgetRef> {
        let element = self.current_element(app)?;
        Some(element.widget(app).clone())
    }

    /// The [`State`] for the widget in the tree that currently has this global key.
    ///
    /// The current state is `None` if (1) there is no widget in the tree that matches this
    /// global key, (2) that widget is not a [`StatefulWidget`], or the associated [`State`]
    /// object is not an `S`.
    pub fn current_state<S: State>(&self, app: &App) -> Option<waft_foundation::Handle<S>> {
        let element = self.current_element(app)?;
        element.state_handle::<S>(app)
    }

    fn current_element(&self, app: &App) -> Option<AnyElement> {
        let owner = crate::binding::current_build_owner(app)?;
        owner.global_key_element(app, self)
    }
}

impl PartialEq for GlobalKey {
    fn eq(&self, other: &GlobalKey) -> bool {
        *self.key == *other.key
    }
}

impl Eq for GlobalKey {}

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

impl Debug for GlobalKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.key.fmt(f)
    }
}

/// What a [`GlobalKey::new`] or [`GlobalKey::labeled`] key compares by: itself (Dart's
/// `LabeledGlobalKey`).
struct LabeledGlobalKeyValue {
    unique: waft_foundation::UniqueKey,
    debug_label: Option<String>,
}

impl LabeledGlobalKeyValue {
    fn new(debug_label: Option<String>) -> LabeledGlobalKeyValue {
        LabeledGlobalKeyValue {
            unique: waft_foundation::UniqueKey::new(),
            debug_label,
        }
    }
}

impl Key for LabeledGlobalKeyValue {
    fn eq_key(&self, other: &dyn Key) -> bool {
        (other as &dyn Any)
            .downcast_ref::<LabeledGlobalKeyValue>()
            .is_some_and(|other| other.unique == self.unique)
    }

    fn hash_key(&self, mut state: &mut dyn Hasher) {
        TypeId::of::<LabeledGlobalKeyValue>().hash(&mut state);
        self.unique.hash(&mut state);
    }
}

impl Debug for LabeledGlobalKeyValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let id = std::ptr::from_ref(self) as usize & 0xF_FFFF;
        match &self.debug_label {
            Some(label) => write!(f, "[GlobalKey#{id:05x} {label}]"),
            None => write!(f, "[GlobalKey#{id:05x}]"),
        }
    }
}

/// What a [`GlobalKey::object`] key compares by: an object's identity (Dart's
/// `GlobalObjectKey`).
struct GlobalObjectKeyValue {
    value: HandleId,
}

impl Key for GlobalObjectKeyValue {
    fn eq_key(&self, other: &dyn Key) -> bool {
        (other as &dyn Any)
            .downcast_ref::<GlobalObjectKeyValue>()
            .is_some_and(|other| other.value == self.value)
    }

    fn hash_key(&self, mut state: &mut dyn Hasher) {
        TypeId::of::<GlobalObjectKeyValue>().hash(&mut state);
        self.value.hash(&mut state);
    }
}

impl Debug for GlobalObjectKeyValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[GlobalObjectKey {:?}]", self.value)
    }
}

/// A key that uses the identity of an object as its value (Dart's `ObjectKey`).
///
/// Used to tie the identity of a widget to the identity of an object used to generate that
/// widget. An object's identity is its [`Handle`](waft_foundation::Handle): pass
/// `Some(handle.id())`.
///
/// See also:
///
///  * [`waft_foundation::Key`], the base trait for all keys.
///  * The discussion at `Widget.key` for more information about how widgets use keys.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ObjectKey {
    /// The object whose identity is used by this key's `==`. The key names it without keeping
    /// it.
    pub value: Option<HandleId>,
}

impl ObjectKey {
    /// Creates a key that uses the identity of `value` for its `==`.
    pub const fn new(value: Option<HandleId>) -> ObjectKey {
        ObjectKey { value }
    }
}

impl Key for ObjectKey {
    fn eq_key(&self, other: &dyn Key) -> bool {
        (other as &dyn Any)
            .downcast_ref::<ObjectKey>()
            .is_some_and(|other| other.value == self.value)
    }

    fn hash_key(&self, mut state: &mut dyn Hasher) {
        TypeId::of::<ObjectKey>().hash(&mut state);
        self.value.hash(&mut state);
    }
}

impl waft_foundation::LocalKey for ObjectKey {}

impl Debug for ObjectKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.value {
            Some(value) => write!(f, "[{value:?}]"),
            None => f.write_str("[null]"),
        }
    }
}