waft-widgets 0.6.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
//! `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::rc::Rc;

use waft_foundation::{App, HandleId, Key};
use waft_rendering::{
    AnyRenderObject, ContainerRenderObjectMixin, ParentData, RenderHandle, RenderObject,
    RenderObjectWithChildMixin,
};

use super::element::{AnyElement, BuildContext, Element};
use super::elements::{
    InheritedElement, LeafRenderObjectElement, MultiChildRenderObjectElement, ParentDataElement,
    SingleChildRenderObjectElement, StatefulElement, StatelessElement,
};
use super::state::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>;

    /// 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
    }

    /// 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
    }
}

/// 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 {
    let name = std::any::type_name::<W>();
    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..]
}

/// 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.
pub trait IntoWidget<Kind> {
    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
    }
}

// ---------------------------------------------------------------------------------------------
// 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 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);

impl<W: StatelessWidget> IntoWidget<StatelessKind> for W {
    fn into_widget(self) -> WidgetRef {
        if cfg!(debug_assertions) {
            self.debug_check_constructor();
        }
        Rc::new(Stateless(self))
    }
}

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

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        StatelessElement::<W>::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()
    }
}

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.
pub trait StatefulWidget: Debug + 'static {
    /// The state this widget creates.
    type State: State<Widget = Self>;

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

    /// 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);

impl<W: StatefulWidget> IntoWidget<StatefulKind> for W {
    fn into_widget(self) -> WidgetRef {
        if cfg!(debug_assertions) {
            self.debug_check_constructor();
        }
        Rc::new(Stateful(self))
    }
}

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

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        StatefulElement::<W>::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_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
        self.0.as_preferred_size_widget()
    }
}

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
    }

    /// 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);

impl<W: InheritedWidget> IntoWidget<InheritedKind> for W {
    fn into_widget(self) -> WidgetRef {
        if cfg!(debug_assertions) {
            self.debug_check_constructor();
        }
        Rc::new(Inherited(self))
    }
}

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

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        InheritedElement::<W>::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()
    }
}

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
    }

    /// 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);

impl<W: ParentDataWidget> IntoWidget<ParentDataKind> for W {
    fn into_widget(self) -> WidgetRef {
        if cfg!(debug_assertions) {
            self.debug_check_constructor();
        }
        Rc::new(ParentDataWrapper(self))
    }
}

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

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        ParentDataElement::<W>::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
    }
}

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
    }

    /// 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);

impl<W: LeafRenderObjectWidget> IntoWidget<LeafRenderObjectKind> for W {
    fn into_widget(self) -> WidgetRef {
        if cfg!(debug_assertions) {
            RenderObjectWidget::debug_check_constructor(&self);
        }
        Rc::new(LeafRenderObject(self))
    }
}

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

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        LeafRenderObjectElement::<W>::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
    }
}

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::<Self>::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)
where
    W::RenderObject: RenderObjectWithChildMixin;

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

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

    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
    }
}

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::<Self>::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)
where
    W::RenderObject: ContainerRenderObjectMixin;

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

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

    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
    }
}

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

// ---------------------------------------------------------------------------------------------
// 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]"),
        }
    }
}