waft-widgets 0.18.1

Widget framework and widgets for Waft
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
//! Flutter counterpart: `widgets/radio_group.dart`.
//!
//! A [`RadioGroup`] treats every [`RadioClient`] of the same value type below it as one group:
//! it holds the group value, hands a selection change back through
//! [`RadioGroup::on_changed`], and moves the selection with the arrow keys.

use std::fmt::{self, Debug};
use std::rc::Rc;

use waft_embedder::SemanticsRole;
use waft_foundation::{
    App, ChangeNotifier, ChangeNotifierData, Handle, HandleId, Listener, OptionRetained, Ref,
    Retained, ValueChanged,
};
use waft_services::{KeyEvent, LogicalKeyboardKey};

use crate::framework::{
    BuildContext, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
};
use crate::widgets::actions::{IntentRef, VoidCallbackIntent};
use crate::widgets::basic::Semantics;
use crate::widgets::focus_manager::{AnyFocusNode, KeyEventResult};
use crate::widgets::focus_traversal::{
    DirectionalFocusTraversalPolicyMixin, DirectionalFocusTraversalPolicyMixinData,
    FocusTraversalGroup, FocusTraversalPolicy, FocusTraversalPolicyData, FocusTraversalPolicyRef,
    ReadingOrderTraversalPolicy,
};
use crate::widgets::shortcuts::{
    ShortcutActivatorRef, ShortcutManagerBase, ShortcutManagerData, ShortcutManagerKeypress,
    ShortcutManagerRef, ShortcutMap, Shortcuts, SingleActivator,
};

// ---------------------------------------------------------------------------------------------
// RadioGroupRegistry

/// The vtable of an erased [`AnyRadioGroupRegistry`]: one `&'static` table per leaf type.
struct RadioGroupRegistryVTable<T: Clone + PartialEq + 'static> {
    type_name: fn() -> &'static str,
    group_value: fn(&App, HandleId) -> Option<T>,
    register_client: fn(&mut App, HandleId, AnyRadioClient<T>),
    unregister_client: fn(&mut App, HandleId, AnyRadioClient<T>),
    on_changed: fn(&mut App, HandleId, Option<T>),
}

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

impl<T: Clone + PartialEq + 'static> RadioGroupRegistryVTable<T> {
    const fn of<L: RadioGroupRegistry<T>>() -> RadioGroupRegistryVTable<T> {
        RadioGroupRegistryVTable {
            type_name: std::any::type_name::<L>,
            group_value: |app, id| L::group_value(resolve(id), app),
            register_client: |app, id, radio| L::register_client(resolve(id), app, radio),
            unregister_client: |app, id, radio| L::unregister_client(resolve(id), app, radio),
            on_changed: |app, id, value| L::on_changed(resolve(id), app, value),
        }
    }
}

/// An abstract interface for registering a group of radios.
///
/// Use [`register_client`](Self::register_client) or
/// [`unregister_client`](Self::unregister_client) to handle registrations of radios.
///
/// The registry manages the group value for the radios. The radio needs to call
/// [`on_changed`](Self::on_changed) to notify the group value needs to be changed.
pub trait RadioGroupRegistry<T: Clone + PartialEq + 'static>: Sized + 'static {
    /// This registry as the erased [`AnyRadioGroupRegistry`] — what to pass where a Dart API
    /// takes a `RadioGroupRegistry<T>`.
    fn as_radio_group_registry(self: Handle<Self>) -> AnyRadioGroupRegistry<T> {
        AnyRadioGroupRegistry {
            id: self.id(),
            vtable: const { &RadioGroupRegistryVTable::<T>::of::<Self>() },
        }
    }

    /// The group value for the group.
    fn group_value(self: Handle<Self>, app: &App) -> Option<T>;

    /// Registers a radio client.
    ///
    /// The implementor provides additional features, such as keyboard navigation for the
    /// registered clients.
    fn register_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<T>);

    /// Unregisters a radio client.
    fn unregister_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<T>);

    /// Notifies the registry that a radio is selected or unselected.
    fn on_changed(self: Handle<Self>, app: &mut App, value: Option<T>);
}

/// Erased `RadioGroupRegistry<T>`: one identity and a static vtable.
///
/// This is what a parameter Dart types as `RadioGroupRegistry<T>` becomes, and what a field
/// holding one for the length of a call holds; a field Dart keeps is
/// [`RadioGroupRegistryRef<T>`].
pub struct AnyRadioGroupRegistry<T: Clone + PartialEq + 'static> {
    id: HandleId,
    vtable: &'static RadioGroupRegistryVTable<T>,
}

impl<T: Clone + PartialEq + 'static> Clone for AnyRadioGroupRegistry<T> {
    fn clone(&self) -> AnyRadioGroupRegistry<T> {
        *self
    }
}

impl<T: Clone + PartialEq + 'static> From<AnyRadioGroupRegistry<T>> for HandleId {
    fn from(registry: AnyRadioGroupRegistry<T>) -> HandleId {
        registry.id
    }
}

impl<T: Clone + PartialEq + 'static, Leaf: RadioGroupRegistry<T>> From<Handle<Leaf>>
    for AnyRadioGroupRegistry<T>
{
    fn from(handle: Handle<Leaf>) -> AnyRadioGroupRegistry<T> {
        handle.as_radio_group_registry()
    }
}

/// A field or parameter Dart types as `RadioGroupRegistry<T>`, kept: the erased registry with
/// its count.
pub type RadioGroupRegistryRef<T> = Retained<AnyRadioGroupRegistry<T>>;

impl<T: Clone + PartialEq + 'static> Copy for AnyRadioGroupRegistry<T> {}

impl<T: Clone + PartialEq + 'static> PartialEq for AnyRadioGroupRegistry<T> {
    fn eq(&self, other: &AnyRadioGroupRegistry<T>) -> bool {
        self.id == other.id
    }
}

impl<T: Clone + PartialEq + 'static> Eq for AnyRadioGroupRegistry<T> {}

impl<T: Clone + PartialEq + 'static> Debug for AnyRadioGroupRegistry<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
    }
}

impl<T: Clone + PartialEq + 'static> AnyRadioGroupRegistry<T> {
    /// The arena id behind this handle.
    pub fn id(self) -> HandleId {
        self.id
    }

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

    /// See [`RadioGroupRegistry::register_client`].
    pub fn register_client(self, app: &mut App, radio: AnyRadioClient<T>) {
        (self.vtable.register_client)(app, self.id, radio);
    }

    /// See [`RadioGroupRegistry::unregister_client`].
    pub fn unregister_client(self, app: &mut App, radio: AnyRadioClient<T>) {
        (self.vtable.unregister_client)(app, self.id, radio);
    }

    /// See [`RadioGroupRegistry::on_changed`].
    pub fn on_changed(self, app: &mut App, value: Option<T>) {
        (self.vtable.on_changed)(app, self.id, value);
    }

    /// A reference while something still keeps the registry, `None` once it is freed or its
    /// last keeper has let go; see [`Handle::upgrade`](waft_foundation::Handle::upgrade).
    pub fn upgrade(self, app: &App) -> Option<RadioGroupRegistryRef<T>> {
        Retained::upgrade(app, self)
    }

    /// A reference to a registry something is known to keep; see
    /// [`Handle::keep`](waft_foundation::Handle::keep).
    #[track_caller]
    pub fn keep(self, app: &App) -> RadioGroupRegistryRef<T> {
        Retained::keep(app, self)
    }
}

// ---------------------------------------------------------------------------------------------
// RadioClient

/// The vtable of an erased [`AnyRadioClient`]: one `&'static` table per leaf type.
struct RadioClientVTable<T: Clone + PartialEq + 'static> {
    type_name: fn() -> &'static str,
    tristate: fn(&App, HandleId) -> bool,
    radio_value: fn(&App, HandleId) -> T,
    enabled: fn(&App, HandleId) -> bool,
    focus_node: fn(&App, HandleId) -> AnyFocusNode,
}

impl<T: Clone + PartialEq + 'static> RadioClientVTable<T> {
    const fn of<L: RadioClient<T>>() -> RadioClientVTable<T> {
        RadioClientVTable {
            type_name: std::any::type_name::<L>,
            tristate: |app, id| L::tristate(resolve(id), app),
            radio_value: |app, id| L::radio_value(resolve(id), app),
            enabled: |app, id| L::enabled(resolve(id), app),
            focus_node: |app, id| L::focus_node(resolve(id), app),
        }
    }
}

/// The field Dart's `RadioClient` mixin declares; a client carries this bag under the field
/// `radio_client` ([`radio_client_accessors!`](crate::radio_client_accessors)).
pub struct RadioClientData<T: Clone + PartialEq + 'static> {
    registry: Option<RadioGroupRegistryRef<T>>,
}

impl<T: Clone + PartialEq + 'static> RadioClientData<T> {
    /// The bag of a freshly created client.
    pub fn new() -> RadioClientData<T> {
        RadioClientData { registry: None }
    }
}

impl<T: Clone + PartialEq + 'static> Default for RadioClientData<T> {
    fn default() -> RadioClientData<T> {
        RadioClientData::new()
    }
}

/// The accessors [`RadioClient`] asks for, for a struct whose bag is the field `radio_client`.
///
/// Takes the radio's value type, which the trait's own type parameter names.
#[macro_export]
macro_rules! radio_client_accessors {
    ($value:ty) => {
        fn radio_client_data(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> &$crate::RadioClientData<$value> {
            &app.get(self).radio_client
        }

        fn radio_client_data_mut(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) -> &mut $crate::RadioClientData<$value> {
            &mut app.get_mut(self).radio_client
        }
    };
}

/// A client for a [`RadioGroupRegistry`].
///
/// This is typically mixed into a [`State`].
///
/// To register to a [`RadioGroupRegistry`], assign the registry with
/// [`set_registry`](Self::set_registry).
///
/// To unregister from the previous [`RadioGroupRegistry`], either assign a different value or
/// set it to `None`.
pub trait RadioClient<T: Clone + PartialEq + 'static>: Sized + 'static {
    /// Dart's `RadioClient` field, held under the field `radio_client`
    /// ([`radio_client_accessors!`](crate::radio_client_accessors)).
    fn radio_client_data(self: Handle<Self>, app: &App) -> &RadioClientData<T>;

    /// See [`radio_client_data`](Self::radio_client_data).
    fn radio_client_data_mut(self: Handle<Self>, app: &mut App) -> &mut RadioClientData<T>;

    /// This client as the erased [`AnyRadioClient`] — what to pass where a Dart API takes a
    /// `RadioClient<T>`.
    fn as_radio_client(self: Handle<Self>) -> AnyRadioClient<T> {
        AnyRadioClient {
            id: self.id(),
            vtable: const { &RadioClientVTable::<T>::of::<Self>() },
        }
    }

    /// Whether this radio supports toggles.
    ///
    /// Used by the registry to provide additional features such as keyboard support.
    fn tristate(self: Handle<Self>, app: &App) -> bool;

    /// The value this radio represents.
    ///
    /// Used by the registry to provide additional features such as keyboard support.
    fn radio_value(self: Handle<Self>, app: &App) -> T;

    /// Whether this radio is enabled.
    ///
    /// If false, the registry skips this client when handling keyboard navigation.
    fn enabled(self: Handle<Self>, app: &App) -> bool;

    /// Focus node for this radio.
    ///
    /// Used by the registry to provide additional features such as keyboard support.
    fn focus_node(self: Handle<Self>, app: &App) -> AnyFocusNode;

    /// The [`RadioGroupRegistry`] this client is registered to.
    fn registry(self: Handle<Self>, app: &App) -> Option<AnyRadioGroupRegistry<T>> {
        self.radio_client_data(app).registry.handle()
    }

    /// See [`registry`](Self::registry).
    ///
    /// Setting this property automatically registers with the new value and unregisters the old
    /// one. This should be set to `None` on dispose.
    fn set_registry(
        self: Handle<Self>,
        app: &mut App,
        new_registry: Option<RadioGroupRegistryRef<T>>,
    ) {
        let registry = self.radio_client_data(app).registry.handle();
        let new = new_registry.handle();
        if registry != new
            && let Some(registry) = registry
        {
            registry.unregister_client(app, self.as_radio_client());
        }
        self.radio_client_data_mut(app).registry = new_registry;
        if let Some(new_registry) = new {
            new_registry.register_client(app, self.as_radio_client());
        }
    }
}

/// Erased `RadioClient<T>`: one identity and a static vtable.
///
/// This is what a field or parameter Dart types as `RadioClient<T>` becomes.
pub struct AnyRadioClient<T: Clone + PartialEq + 'static> {
    id: HandleId,
    vtable: &'static RadioClientVTable<T>,
}

impl<T: Clone + PartialEq + 'static> Clone for AnyRadioClient<T> {
    fn clone(&self) -> AnyRadioClient<T> {
        *self
    }
}

impl<T: Clone + PartialEq + 'static> Copy for AnyRadioClient<T> {}

impl<T: Clone + PartialEq + 'static> PartialEq for AnyRadioClient<T> {
    fn eq(&self, other: &AnyRadioClient<T>) -> bool {
        self.id == other.id
    }
}

impl<T: Clone + PartialEq + 'static> Eq for AnyRadioClient<T> {}

impl<T: Clone + PartialEq + 'static> Debug for AnyRadioClient<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
    }
}

impl<T: Clone + PartialEq + 'static> AnyRadioClient<T> {
    /// The arena id behind this handle.
    pub fn id(self) -> HandleId {
        self.id
    }

    /// See [`RadioClient::tristate`].
    pub fn tristate(self, app: &App) -> bool {
        (self.vtable.tristate)(app, self.id)
    }

    /// See [`RadioClient::radio_value`].
    pub fn radio_value(self, app: &App) -> T {
        (self.vtable.radio_value)(app, self.id)
    }

    /// See [`RadioClient::enabled`].
    pub fn enabled(self, app: &App) -> bool {
        (self.vtable.enabled)(app, self.id)
    }

    /// See [`RadioClient::focus_node`].
    pub fn focus_node(self, app: &App) -> AnyFocusNode {
        (self.vtable.focus_node)(app, self.id)
    }
}

// ---------------------------------------------------------------------------------------------
// RadioGroup

/// A group for radios.
///
/// This widget treats all radios in the subtree with the same type `T` as a group. Radios with
/// different types are not included in the group.
///
/// This widget handles the group value for the radios in the subtree with the same value type.
///
/// Using this widget also provides keyboard navigation for the radio buttons that matches
/// [APG](https://www.w3.org/WAI/ARIA/apg/patterns/radio/).
///
/// The keyboard behaviors are:
/// * Tab and Shift+Tab: moves focus into and out of the radio group. When focus moves into a
///   radio group and a radio button is selected, focus is set on the selected button.
///   Otherwise, it focuses the first radio button in reading order.
/// * Space: toggle the selection on the focused radio button.
/// * Right and down arrow key: move selection to the next radio button in the group in reading
///   order.
/// * Left and up arrow key: move selection to the previous radio button in the group in reading
///   order.
///
/// Arrow keys will wrap around if they reach the first or last radio in the group.
pub struct RadioGroup<T: Clone + PartialEq + 'static> {
    /// See [`Widget::key`](crate::Widget::key).
    pub key: Option<KeyRef>,

    /// The selected value under this radio group.
    ///
    /// A radio under this radio group whose value equals this value will be selected.
    pub group_value: Option<T>,

    /// Called when selection has changed.
    ///
    /// The value can be `None` when unselecting a radio with `tristate` set to true.
    pub on_changed: ValueChanged<Option<T>>,

    /// The widget below this widget in the tree.
    pub child: WidgetRef,
}

impl<T: Clone + PartialEq + 'static> RadioGroup<T> {
    /// Creates a radio group; Dart's optional `groupValue` argument is the setter.
    ///
    /// The `on_changed` callback is called when the selection has changed in the subtree
    /// radios.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn new<K>(on_changed: ValueChanged<Option<T>>, child: impl IntoWidget<K>) -> RadioGroup<T> {
        RadioGroup {
            key: None,
            group_value: None,
            on_changed,
            child: child.into_widget(),
        }
    }

    /// Dart `RadioGroup(key:)`.
    pub fn key(mut self, key: KeyRef) -> RadioGroup<T> {
        self.key = Some(key);
        self
    }

    /// Dart `RadioGroup(groupValue:)`.
    pub fn group_value(mut self, group_value: T) -> RadioGroup<T> {
        self.group_value = Some(group_value);
        self
    }

    /// Gets the [`RadioGroupRegistry`] from above the context.
    ///
    /// This registers a dependency on the context so that it rebuilds if the registry has
    /// changed or its [`RadioGroupRegistry::group_value`] has changed.
    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<RadioGroupRegistryRef<T>> {
        let state = context
            .depend_on_inherited_widget_of_exact_type::<RadioGroupStateScope<T>>(app)
            .map(|scope| scope.state)?;
        state.as_radio_group_registry().upgrade(app)
    }
}

impl<T: Clone + PartialEq + 'static> Debug for RadioGroup<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RadioGroup").finish_non_exhaustive()
    }
}

impl<T: Clone + PartialEq + 'static> StatefulWidget for RadioGroup<T> {
    type State = RadioGroupState<T>;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn create_state(&self) -> RadioGroupState<T> {
        RadioGroupState {
            state: StateData::new(),
            radio_group_shortcut_manager: None,
            policy: None,
            radios: Vec::new(),
        }
    }
}

/// Dart's `_RadioGroupState`.
pub struct RadioGroupState<T: Clone + PartialEq + 'static> {
    state: StateData<RadioGroup<T>>,
    radio_group_shortcut_manager: Option<Ref<RadioGroupShortcutManager<T>>>,
    policy: Option<Ref<SkipUnselectedRadioPolicy<T>>>,
    radios: Vec<AnyRadioClient<T>>,
}

impl<T: Clone + PartialEq + 'static> RadioGroupState<T> {
    /// Dart's `_radioGroupShortcuts`, built once the state has an `App`.
    fn radio_group_shortcuts(self: Handle<Self>) -> ShortcutMap {
        let select_previous = || {
            Rc::new(VoidCallbackIntent::new(Listener::handle_method(
                self,
                RadioGroupState::<T>::select_previous_radio,
            ))) as IntentRef
        };
        let select_next = || {
            Rc::new(VoidCallbackIntent::new(Listener::handle_method(
                self,
                RadioGroupState::<T>::select_next_radio,
            ))) as IntentRef
        };
        vec![
            (
                Rc::new(SingleActivator::new(LogicalKeyboardKey::ARROW_LEFT))
                    as ShortcutActivatorRef,
                select_previous(),
            ),
            (
                Rc::new(SingleActivator::new(LogicalKeyboardKey::ARROW_RIGHT))
                    as ShortcutActivatorRef,
                select_next(),
            ),
            (
                Rc::new(SingleActivator::new(LogicalKeyboardKey::ARROW_DOWN))
                    as ShortcutActivatorRef,
                select_next(),
            ),
            (
                Rc::new(SingleActivator::new(LogicalKeyboardKey::ARROW_UP)) as ShortcutActivatorRef,
                select_previous(),
            ),
            (
                Rc::new(SingleActivator::new(LogicalKeyboardKey::SPACE)) as ShortcutActivatorRef,
                Rc::new(VoidCallbackIntent::new(Listener::handle_method(
                    self,
                    RadioGroupState::<T>::toggle_focused_radio,
                ))) as IntentRef,
            ),
        ]
    }

    /// The radios registered with this group, in registration order.
    pub fn radios(self: Handle<Self>, app: &App) -> Vec<AnyRadioClient<T>> {
        app.get(self).radios.clone()
    }

    /// The first registered radio whose focus node has focus, if any.
    fn focused_radio(self: Handle<Self>, app: &mut App) -> Option<AnyRadioClient<T>> {
        self.radios(app)
            .into_iter()
            .find(|radio| radio.focus_node(app).has_focus(app))
    }

    fn toggle_focused_radio(self: Handle<Self>, app: &mut App) {
        let Some(radio) = self.focused_radio(app) else {
            return;
        };
        let value = radio.radio_value(app);
        if Some(&value) != self.widget(app).group_value.as_ref() {
            self.on_changed(app, Some(value));
            return;
        }

        if radio.tristate(app) {
            self.on_changed(app, None);
        }
    }

    fn select_next_radio(self: Handle<Self>, app: &mut App) {
        self.select_radio_in_direction(app, true);
    }

    fn select_previous_radio(self: Handle<Self>, app: &mut App) {
        self.select_radio_in_direction(app, false);
    }

    fn select_radio_in_direction(self: Handle<Self>, app: &mut App, forward: bool) {
        if self.radios(app).len() < 2 {
            return;
        }
        let Some(current_focus) = self.focused_radio(app).map(|radio| radio.focus_node(app)) else {
            // The focused node is either a non-interactive radio or another control.
            return;
        };
        let enabled: Vec<AnyFocusNode> = self
            .radios(app)
            .into_iter()
            .filter(|radio| radio.enabled(app))
            .map(|radio| radio.focus_node(app))
            .collect();
        let sorted = ReadingOrderTraversalPolicy::sort(app, enabled);
        debug_assert!(!sorted.is_empty());
        let nodes_in_effective_order: Vec<AnyFocusNode> = if forward {
            sorted
        } else {
            sorted.into_iter().rev().collect()
        };

        let next_focus = nodes_in_effective_order
            .iter()
            .position(|node| *node == current_focus)
            .and_then(|index| nodes_in_effective_order.get(index + 1))
            .copied()
            // Current focus is at the end, the next focus should wrap around.
            .or_else(|| nodes_in_effective_order.first().copied())
            .expect("the sorted list is not empty");
        let radio_to_select = self
            .radios(app)
            .into_iter()
            .find(|radio| radio.focus_node(app) == next_focus)
            .expect("the next node belongs to a registered radio");
        let value = radio_to_select.radio_value(app);
        self.on_changed(app, Some(value));
        next_focus.request_focus(app, None);
    }
}

impl<T: Clone + PartialEq + 'static> RadioGroupRegistry<T> for RadioGroupState<T> {
    fn group_value(self: Handle<Self>, app: &App) -> Option<T> {
        self.widget(app).group_value.clone()
    }

    fn register_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<T>) {
        let radios = &mut app.get_mut(self).radios;
        if !radios.contains(&radio) {
            radios.push(radio);
        }
    }

    fn unregister_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<T>) {
        app.get_mut(self).radios.retain(|entry| *entry != radio);
    }

    fn on_changed(self: Handle<Self>, app: &mut App, value: Option<T>) {
        let on_changed = Rc::clone(&self.widget(app).on_changed);
        on_changed(app, value);
    }
}

impl<T: Clone + PartialEq + 'static> State for RadioGroupState<T> {
    type Widget = RadioGroup<T>;
    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        let shortcuts = self.radio_group_shortcuts();
        let manager = RadioGroupShortcutManager::new(app, self);
        manager.set_shortcuts(app, shortcuts);
        let policy = SkipUnselectedRadioPolicy::new(app, self);
        let this = app.get_mut(self);
        this.radio_group_shortcut_manager = Some(manager);
        this.policy = Some(policy);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        if let Some(manager) = app.get(self).radio_group_shortcut_manager.handle() {
            ChangeNotifierData::dispose(app, manager);
        }
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        let manager: ShortcutManagerRef = app
            .get(self)
            .radio_group_shortcut_manager
            .as_ref()
            .expect("created in init_state")
            .erase();
        let policy: FocusTraversalPolicyRef = app
            .get(self)
            .policy
            .as_ref()
            .expect("created in init_state")
            .erase();
        let typed_policy = app
            .get(self)
            .policy
            .handle()
            .expect("created in init_state");
        let group_value = self.widget(app).group_value.clone();
        typed_policy.set_group_value(app, group_value.clone());
        let child = self.widget(app).child.clone();
        Semantics::new()
            .container(true)
            .role(SemanticsRole::RadioGroup)
            .child(Shortcuts::manager(
                manager,
                FocusTraversalGroup::new(RadioGroupStateScope {
                    state: self,
                    group_value,
                    child,
                })
                .policy(policy),
            ))
            .into_widget()
    }
}

/// Dart's `_RadioGroupShortcutManager`: a [`ShortcutManagerBase`] that ignores a key event
/// while no radio in its group has focus.
pub struct RadioGroupShortcutManager<T: Clone + PartialEq + 'static> {
    change_notifier: ChangeNotifierData,
    shortcut_manager: ShortcutManagerData,
    state: Handle<RadioGroupState<T>>,
}

impl<T: Clone + PartialEq + 'static> RadioGroupShortcutManager<T> {
    fn new(app: &mut App, state: Handle<RadioGroupState<T>>) -> Ref<RadioGroupShortcutManager<T>> {
        app.create(RadioGroupShortcutManager {
            change_notifier: ChangeNotifierData::new(),
            shortcut_manager: ShortcutManagerData::new(),
            state,
        })
    }
}

impl<T: Clone + PartialEq + 'static> ShortcutManagerBase for RadioGroupShortcutManager<T> {
    crate::shortcut_manager_accessors!();

    fn handle_keypress(
        self: Handle<Self>,
        app: &mut App,
        context: BuildContext,
        event: &KeyEvent,
    ) -> KeyEventResult {
        let state = app.get(self).state;
        let radio_has_focus = state
            .radios(app)
            .into_iter()
            .any(|radio| radio.focus_node(app).has_focus(app));
        if !radio_has_focus {
            // Ignore the event if no radio is focused. This prevents this handler from
            // unintentionally consuming an event meant for a non-radio widget that currently
            // has focus.
            return KeyEventResult::Ignored;
        }
        ShortcutManagerKeypress::handle_keypress(self, app, context, event)
    }
}

impl<T: Clone + PartialEq + 'static> ChangeNotifier for RadioGroupShortcutManager<T> {
    fn change_notifier_data(&self) -> &ChangeNotifierData {
        &self.change_notifier
    }

    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
        &mut self.change_notifier
    }
}

/// Dart's `_RadioGroupStateScope`.
pub struct RadioGroupStateScope<T: Clone + PartialEq + 'static> {
    state: Handle<RadioGroupState<T>>,
    /// The group value is part of the scope so that dependents are notified when it changes.
    group_value: Option<T>,
    child: WidgetRef,
}

impl<T: Clone + PartialEq + 'static> Debug for RadioGroupStateScope<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RadioGroupStateScope")
            .field("state", &self.state)
            .finish_non_exhaustive()
    }
}

impl<T: Clone + PartialEq + 'static> InheritedWidget for RadioGroupStateScope<T> {
    fn child(&self) -> &WidgetRef {
        &self.child
    }

    fn update_should_notify(&self, old_widget: &RadioGroupStateScope<T>) -> bool {
        self.state != old_widget.state || self.group_value != old_widget.group_value
    }
}

/// A traversal policy that is the same as [`ReadingOrderTraversalPolicy`] except that it skips
/// the nodes of unselected radio buttons if there is a selected radio button.
///
/// If none of the radios is selected, this defaults to [`ReadingOrderTraversalPolicy`] for all
/// nodes.
///
/// This policy ensures that tabbing into a radio group only focuses the currently selected
/// radio button and prevents focus from reaching unselected ones.
pub struct SkipUnselectedRadioPolicy<T: Clone + PartialEq + 'static> {
    policy: FocusTraversalPolicyData,
    directional: DirectionalFocusTraversalPolicyMixinData,
    state: Handle<RadioGroupState<T>>,
    group_value: Option<T>,
}

impl<T: Clone + PartialEq + 'static> SkipUnselectedRadioPolicy<T> {
    fn new(app: &mut App, state: Handle<RadioGroupState<T>>) -> Ref<SkipUnselectedRadioPolicy<T>> {
        app.create(SkipUnselectedRadioPolicy {
            policy: FocusTraversalPolicyData::new(),
            directional: DirectionalFocusTraversalPolicyMixinData::new(),
            state,
            group_value: None,
        })
    }

    /// The group value the policy compares each radio against; Dart passes it to the
    /// constructor of the policy it builds every frame.
    fn set_group_value(self: Handle<Self>, app: &mut App, group_value: Option<T>) {
        app.get_mut(self).group_value = group_value;
    }

    fn radio_selected(self: Handle<Self>, app: &App, radio: AnyRadioClient<T>) -> bool {
        Some(&radio.radio_value(app)) == app.get(self).group_value.as_ref()
    }
}

impl<T: Clone + PartialEq + 'static> FocusTraversalPolicy for SkipUnselectedRadioPolicy<T> {
    crate::focus_traversal_policy_accessors!();
    crate::directional_focus_traversal_policy_overrides!();

    fn sort_descendants(
        self: Handle<Self>,
        app: &mut App,
        descendants: Vec<AnyFocusNode>,
        current_node: AnyFocusNode,
    ) -> Vec<AnyFocusNode> {
        let nodes_in_read_order = ReadingOrderTraversalPolicy::sort(app, descendants.clone());
        let radios = app.get(self).state.radios(app);
        let mut selected = radios
            .iter()
            .copied()
            .find(|radio| self.radio_selected(app, *radio));

        if selected.is_none() {
            // None of the radios is selected. Select the first radio in read order.
            for node in &nodes_in_read_order {
                selected = radios
                    .iter()
                    .copied()
                    .find(|radio| radio.focus_node(app) == *node);
                if selected.is_some() {
                    break;
                }
            }
        }

        let Some(selected) = selected else {
            // None of the radios is selected or focusable, defaults to reading order.
            return nodes_in_read_order;
        };

        // Nodes that are not selected AND not currently focused, since we can't remove the
        // focused node from the sorted result.
        let node_to_skip: Vec<AnyFocusNode> = radios
            .iter()
            .copied()
            .filter(|radio| selected != *radio && radio.focus_node(app) != current_node)
            .map(|radio| radio.focus_node(app))
            .collect();
        let skips_non_selected: Vec<AnyFocusNode> = descendants
            .into_iter()
            .filter(|node| !node_to_skip.contains(node))
            .collect();
        ReadingOrderTraversalPolicy::sort(app, skips_non_selected)
    }
}

impl<T: Clone + PartialEq + 'static> DirectionalFocusTraversalPolicyMixin
    for SkipUnselectedRadioPolicy<T>
{
    fn directional_data(
        self: Handle<Self>,
        app: &App,
    ) -> &DirectionalFocusTraversalPolicyMixinData {
        &app.get(self).directional
    }

    fn directional_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut DirectionalFocusTraversalPolicyMixinData {
        &mut app.get_mut(self).directional
    }
}

#[cfg(test)]
mod tests {
    use std::any::TypeId;
    use std::cell::RefCell;
    use std::collections::HashMap;
    use std::time::Duration;

    use waft_embedder::{Rect, TextDirection};
    use waft_services::{HardwareKeyboard, KeyDownEvent, LogicalKeyboardKey, PhysicalKeyboardKey};

    use super::*;
    use crate::testing::{WidgetTester, test_widgets};
    use crate::widgets::actions::{Actions, VoidCallbackAction};
    use crate::widgets::basic::{Directionality, Positioned, SizedBox, Stack};
    use crate::widgets::focus_manager::{FocusNode, FocusNodeLeaf, primary_focus};
    use crate::widgets::focus_scope::Focus;

    /// A radio that only registers with the group: enough to drive the registry and the arrow
    /// keys, standing in for `RawRadio`.
    #[derive(Debug)]
    struct TestRadio {
        value: u32,
        enabled: bool,
        rect: Rect,
    }

    impl StatefulWidget for TestRadio {
        type State = TestRadioState;

        fn create_state(&self) -> TestRadioState {
            TestRadioState {
                state: StateData::new(),
                radio_client: RadioClientData::new(),
                focus_node: None,
            }
        }
    }

    struct TestRadioState {
        state: StateData<TestRadio>,
        radio_client: RadioClientData<u32>,
        focus_node: Option<Ref<FocusNode>>,
    }

    impl TestRadioState {
        fn node(self: Handle<Self>, app: &App) -> Handle<FocusNode> {
            app.get(self)
                .focus_node
                .handle()
                .expect("created in init_state")
        }
    }

    impl RadioClient<u32> for TestRadioState {
        crate::radio_client_accessors!(u32);

        fn tristate(self: Handle<Self>, _app: &App) -> bool {
            false
        }

        fn radio_value(self: Handle<Self>, app: &App) -> u32 {
            self.widget(app).value
        }

        fn enabled(self: Handle<Self>, app: &App) -> bool {
            self.widget(app).enabled
        }

        fn focus_node(self: Handle<Self>, app: &App) -> AnyFocusNode {
            self.node(app).as_node()
        }
    }

    impl State for TestRadioState {
        type Widget = TestRadio;
        crate::state_accessors!();

        fn init_state(self: Handle<Self>, app: &mut App) {
            let node = FocusNode::new(app);
            let label = format!("radio {}", self.widget(app).value);
            node.as_node().set_debug_label(app, Some(label));
            app.get_mut(self).focus_node = Some(node);
        }

        fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
            let context = self.context(app);
            let registry = if self.widget(app).enabled {
                RadioGroup::<u32>::maybe_of(app, context)
            } else {
                None
            };
            self.set_registry(app, registry);
        }

        fn dispose(self: Handle<Self>, app: &mut App) {
            self.set_registry(app, None);
            self.node(app).as_node().dispose(app);
        }

        fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
            let node: crate::widgets::focus_manager::FocusNodeRef = app
                .get(self)
                .focus_node
                .as_ref()
                .expect("created in init_state")
                .erase();
            let enabled = self.widget(app).enabled;
            let rect = self.widget(app).rect;
            Positioned::from_rect(
                rect,
                Focus::new(SizedBox::expand())
                    .focus_node(node)
                    .can_request_focus(enabled),
            )
            .into_widget()
        }
    }

    /// The group's state, reached through a `GlobalKey`, plus what `on_changed` recorded.
    struct GroupHarness {
        state: Handle<RadioGroupState<u32>>,
        changes: Rc<RefCell<Vec<Option<u32>>>>,
    }

    fn radio(value: u32, enabled: bool, rect: Rect) -> WidgetRef {
        TestRadio {
            value,
            enabled,
            rect,
        }
        .into_widget()
    }

    /// Three radios side by side in reading order, under a group with `group_value`.
    fn mount_group(
        tester: &mut WidgetTester,
        group_value: Option<u32>,
        enabled: [bool; 3],
    ) -> GroupHarness {
        let mut app = tester.cell.borrow_mut();
        let changes: Rc<RefCell<Vec<Option<u32>>>> = Rc::default();
        let recorded = Rc::clone(&changes);
        let key = crate::framework::GlobalKey::new();
        let children = vec![
            radio(0, enabled[0], Rect::from_ltwh(0.0, 0.0, 40.0, 20.0)),
            radio(1, enabled[1], Rect::from_ltwh(50.0, 0.0, 40.0, 20.0)),
            radio(2, enabled[2], Rect::from_ltwh(100.0, 0.0, 40.0, 20.0)),
        ];
        let mut group = RadioGroup::<u32>::new(
            Rc::new(move |_app, value| recorded.borrow_mut().push(value)),
            Stack::new().children(children),
        )
        .key(key.clone().into());
        if let Some(value) = group_value {
            group = group.group_value(value);
        }
        let void_callback_action = VoidCallbackAction::new(&mut app);
        drop(app);
        tester.pump_widget(
            Directionality::new(
                TextDirection::Ltr,
                Actions::new(
                    HashMap::from([(
                        TypeId::of::<VoidCallbackIntent>(),
                        void_callback_action.erase(),
                    )]),
                    group,
                ),
            )
            .into_widget(),
        );
        let app = tester.cell.borrow();
        let state = key
            .current_state::<RadioGroupState<u32>>(&app)
            .expect("the group is mounted");
        drop(app);
        GroupHarness { state, changes }
    }

    fn arrow_down(app: &mut App) -> bool {
        let keyboard = HardwareKeyboard::instance(app);
        let event = KeyEvent::Down(KeyDownEvent::new(
            PhysicalKeyboardKey::ARROW_DOWN,
            LogicalKeyboardKey::ARROW_DOWN,
            Duration::ZERO,
        ));
        keyboard.handle_key_event(app, &event)
    }

    #[test]
    fn a_radio_group_registers_every_client_below_it() {
        test_widgets(|tester| {
            let harness = mount_group(tester, None, [true, true, true]);
            let values: Vec<u32> = harness
                .state
                .radios(&tester.cell.borrow())
                .into_iter()
                .map(|radio| radio.radio_value(&tester.cell.borrow()))
                .collect();
            assert_eq!(values, [0, 1, 2]);
            assert_eq!(harness.state.group_value(&tester.cell.borrow()), None);

            // Reported selections reach the widget's callback.
            let registry = harness.state.as_radio_group_registry();
            registry.on_changed(&mut tester.cell.borrow_mut(), Some(2));
            assert_eq!(*harness.changes.borrow(), [Some(2)]);
        });

        // A disabled radio does not register.
        test_widgets(|tester| {
            let disabled = mount_group(tester, Some(1), [true, false, true]);
            let values: Vec<u32> = disabled
                .state
                .radios(&tester.cell.borrow())
                .into_iter()
                .map(|radio| radio.radio_value(&tester.cell.borrow()))
                .collect();
            assert_eq!(values, [0, 2]);
            assert_eq!(disabled.state.group_value(&tester.cell.borrow()), Some(1));
        });
    }

    #[test]
    fn an_arrow_key_moves_the_selection_to_the_next_radio() {
        test_widgets(|tester| {
            let harness = mount_group(tester, Some(0), [true, true, true]);
            let first =
                harness.state.radios(&tester.cell.borrow())[0].focus_node(&tester.cell.borrow());
            first.request_focus(&mut tester.cell.borrow_mut(), None);
            tester.cell.borrow_mut().drain_microtasks();
            assert_eq!(primary_focus(&mut tester.cell.borrow_mut()), Some(first));

            assert!(
                arrow_down(&mut tester.cell.borrow_mut()),
                "the group handled the key"
            );
            tester.cell.borrow_mut().drain_microtasks();
            assert_eq!(*harness.changes.borrow(), [Some(1)]);
            let second =
                harness.state.radios(&tester.cell.borrow())[1].focus_node(&tester.cell.borrow());
            assert_eq!(primary_focus(&mut tester.cell.borrow_mut()), Some(second));

            // The last radio wraps around to the first.
            let third =
                harness.state.radios(&tester.cell.borrow())[2].focus_node(&tester.cell.borrow());
            third.request_focus(&mut tester.cell.borrow_mut(), None);
            tester.cell.borrow_mut().drain_microtasks();
            assert!(arrow_down(&mut tester.cell.borrow_mut()));
            tester.cell.borrow_mut().drain_microtasks();
            assert_eq!(*harness.changes.borrow(), [Some(1), Some(0)]);
        });
    }

    #[test]
    fn an_arrow_key_is_ignored_while_no_radio_has_focus() {
        test_widgets(|tester| {
            let harness = mount_group(tester, Some(0), [true, true, true]);
            assert!(
                !arrow_down(&mut tester.cell.borrow_mut()),
                "the manager ignores the event when the focus is elsewhere"
            );
            assert!(harness.changes.borrow().is_empty());
        });
    }

    #[test]
    fn the_traversal_policy_skips_the_unselected_radios() {
        test_widgets(|tester| {
            let harness = mount_group(tester, Some(1), [true, true, true]);
            let nodes: Vec<AnyFocusNode> = harness
                .state
                .radios(&tester.cell.borrow())
                .into_iter()
                .map(|radio| radio.focus_node(&tester.cell.borrow()))
                .collect();
            let policy = tester
                .cell
                .borrow()
                .get(harness.state)
                .policy
                .handle()
                .expect("created in init_state");
            let sorted =
                policy.sort_descendants(&mut tester.cell.borrow_mut(), nodes.clone(), nodes[0]);
            assert_eq!(
                sorted,
                vec![nodes[0], nodes[1]],
                "only the selected radio and the currently focused one stay"
            );
        });
    }
}