1use std::fmt::{self, Debug};
9use std::rc::Rc;
10
11use waft_embedder::TargetPlatform;
12use waft_foundation::{App, Handle, Ref, ValueChanged};
13use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
14use waft_services::MouseCursorRef;
15
16use crate::framework::{
17 BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
18};
19use crate::widgets::basic::Semantics;
20use crate::widgets::focus_manager::{AnyFocusNode, FocusNodeRef};
21use crate::widgets::localizations::WidgetsLocalizations;
22use crate::widgets::radio_group::{RadioClient, RadioClientData, RadioGroupRegistryRef};
23use crate::widgets::ticker_provider::{TickerProviderStateMixin, TickerProviderStateMixinData};
24use crate::widgets::toggleable::{
25 AnyToggleableState, ToggleableStateMixin, ToggleableStateMixinData,
26};
27use crate::widgets::widget_state::WidgetStatePropertyRef;
28
29pub type RadioBuilder = Rc<dyn Fn(&mut App, BuildContext, AnyToggleableState) -> WidgetRef>;
36
37#[derive(Clone)]
59pub struct RawRadio<T: Clone + PartialEq + 'static> {
60 pub key: Option<KeyRef>,
61 pub value: T,
63 pub mouse_cursor: WidgetStatePropertyRef<MouseCursorRef>,
74 pub toggleable: bool,
91 pub focus_node: FocusNodeRef,
93 pub autofocus: bool,
96 pub builder: RadioBuilder,
102 pub enabled: bool,
104 pub group_registry: Option<RadioGroupRegistryRef<T>>,
110}
111
112impl<T: Clone + PartialEq + 'static> RawRadio<T> {
113 #[allow(clippy::too_many_arguments)]
118 pub fn new(
119 value: T,
120 mouse_cursor: WidgetStatePropertyRef<MouseCursorRef>,
121 toggleable: bool,
122 focus_node: FocusNodeRef,
123 autofocus: bool,
124 group_registry: Option<RadioGroupRegistryRef<T>>,
125 enabled: bool,
126 builder: RadioBuilder,
127 ) -> RawRadio<T> {
128 debug_assert!(
129 !enabled || group_registry.is_some(),
130 "an enabled raw radio must have a registry"
131 );
132 RawRadio {
133 key: None,
134 value,
135 mouse_cursor,
136 toggleable,
137 focus_node,
138 autofocus,
139 builder,
140 enabled,
141 group_registry,
142 }
143 }
144
145 pub fn key(mut self, key: KeyRef) -> RawRadio<T> {
147 self.key = Some(key);
148 self
149 }
150}
151
152impl<T: Clone + PartialEq + 'static> Debug for RawRadio<T> {
153 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154 f.debug_struct("RawRadio")
155 .field("enabled", &self.enabled)
156 .field("toggleable", &self.toggleable)
157 .field("autofocus", &self.autofocus)
158 .field("group_registry", &self.group_registry)
159 .finish_non_exhaustive()
160 }
161}
162
163impl<T: Clone + PartialEq + 'static> StatefulWidget for RawRadio<T> {
164 type State = RawRadioState<T>;
165
166 fn key(&self) -> Option<&KeyRef> {
167 self.key.as_ref()
168 }
169
170 fn create_state(&self) -> RawRadioState<T> {
171 RawRadioState {
172 state: StateData::new(),
173 ticker_provider: TickerProviderStateMixinData::new(),
174 toggleable: ToggleableStateMixinData::new(),
175 radio_client: RadioClientData::new(),
176 }
177 }
178}
179
180pub struct RawRadioState<T: Clone + PartialEq + 'static> {
182 state: StateData<RawRadio<T>>,
183 ticker_provider: TickerProviderStateMixinData,
184 toggleable: ToggleableStateMixinData,
185 radio_client: RadioClientData<T>,
186}
187
188impl<T: Clone + PartialEq + 'static> RawRadioState<T> {
189 fn handle_changed(self: Handle<Self>, app: &mut App, selected: Option<bool>) {
200 let registry = RadioClient::registry(self, app);
201 debug_assert!(registry.is_some());
202 let Some(registry) = registry else {
203 return;
204 };
205 if !selected.unwrap_or(true) {
206 return;
207 }
208 if selected.unwrap_or(false) {
209 let value = self.widget(app).value.clone();
210 registry.on_changed(app, Some(value));
211 } else {
212 registry.on_changed(app, None);
213 }
214 }
215}
216
217impl<T: Clone + PartialEq + 'static> TickerProviderStateMixin for RawRadioState<T> {
218 fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
219 &app.get(self).ticker_provider
220 }
221
222 fn ticker_provider_data_mut(
223 self: Handle<Self>,
224 app: &mut App,
225 ) -> &mut TickerProviderStateMixinData {
226 &mut app.get_mut(self).ticker_provider
227 }
228}
229
230impl<T: Clone + PartialEq + 'static> TickerProviderObject for RawRadioState<T> {
232 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
233 TickerProviderStateMixin::create_ticker(self, app, on_tick)
234 }
235}
236
237impl<T: Clone + PartialEq + 'static> RadioClient<T> for RawRadioState<T> {
238 crate::radio_client_accessors!(T);
239
240 fn tristate(self: Handle<Self>, app: &App) -> bool {
241 self.widget(app).toggleable
242 }
243
244 fn radio_value(self: Handle<Self>, app: &App) -> T {
245 self.widget(app).value.clone()
246 }
247
248 fn enabled(self: Handle<Self>, app: &App) -> bool {
249 ToggleableStateMixin::is_interactive(self, app)
250 }
251
252 fn focus_node(self: Handle<Self>, app: &App) -> AnyFocusNode {
253 self.widget(app).focus_node.handle()
254 }
255}
256
257impl<T: Clone + PartialEq + 'static> ToggleableStateMixin for RawRadioState<T> {
258 fn toggleable_data(self: Handle<Self>, app: &App) -> &ToggleableStateMixinData {
259 &app.get(self).toggleable
260 }
261
262 fn toggleable_data_mut(self: Handle<Self>, app: &mut App) -> &mut ToggleableStateMixinData {
263 &mut app.get_mut(self).toggleable
264 }
265
266 fn on_changed(self: Handle<Self>, app: &App) -> Option<ValueChanged<Option<bool>>> {
267 RadioClient::registry(self, app)?;
268 Some(Rc::new(move |app: &mut App, selected| {
269 self.handle_changed(app, selected)
270 }))
271 }
272
273 fn tristate(self: Handle<Self>, app: &App) -> bool {
274 self.widget(app).toggleable
275 }
276
277 fn value(self: Handle<Self>, app: &App) -> Option<bool> {
278 let registry = RadioClient::registry(self, app);
279 let group_value = registry.and_then(|registry| registry.group_value(app));
280 Some(group_value.as_ref() == Some(&self.widget(app).value))
281 }
282
283 fn is_interactive(self: Handle<Self>, app: &App) -> bool {
284 self.widget(app).enabled
285 }
286}
287
288impl<T: Clone + PartialEq + 'static> State for RawRadioState<T> {
289 type Widget = RawRadio<T>;
290 crate::state_accessors!();
291
292 fn init_state(self: Handle<Self>, app: &mut App) {
293 let registry = self.widget(app).group_registry.clone();
296 self.set_registry(app, registry);
297 ToggleableStateMixin::init_state(self, app);
298 }
299
300 fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &RawRadio<T>) {
301 let registry = self.widget(app).group_registry.clone();
302 self.set_registry(app, registry);
303 self.animate_to_value(app); }
305
306 fn activate(self: Handle<Self>, app: &mut App) {
307 TickerProviderStateMixin::activate(self, app);
308 }
309
310 fn dispose(self: Handle<Self>, app: &mut App) {
311 ToggleableStateMixin::dispose(self, app);
312 TickerProviderStateMixin::dispose(self, app);
313 self.set_registry(app, None);
314 }
315
316 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
317 let accessibility_selected: Option<bool>;
318 let mut semantics_hint: Option<String> = None;
319
320 match app.platform().target_platform() {
321 TargetPlatform::Android
322 | TargetPlatform::Fuchsia
323 | TargetPlatform::Linux
324 | TargetPlatform::Windows => {
325 accessibility_selected = None;
326 semantics_hint = None;
327 }
328 TargetPlatform::IOS | TargetPlatform::MacOS => {
329 accessibility_selected = self.value(app);
330 if !self.value(app).unwrap_or(false) {
334 let localizations = <dyn WidgetsLocalizations>::of(app, context);
335 semantics_hint = Some(localizations.radio_button_unselected_label());
336 }
337 }
338 }
339
340 let widget = self.widget(app);
341 let focus_node = widget.focus_node.clone();
342 let autofocus = widget.autofocus;
343 let mouse_cursor = Rc::clone(&widget.mouse_cursor);
344 let builder = Rc::clone(&widget.builder);
345 let child = builder(app, context, self.as_toggleable_state());
346 let mut semantics = Semantics::new().in_mutually_exclusive_group(true);
347 if let Some(checked) = self.value(app) {
348 semantics = semantics.checked(checked);
349 }
350 if let Some(selected) = accessibility_selected {
351 semantics = semantics.selected(selected);
352 }
353 if let Some(hint) = semantics_hint {
354 semantics = semantics.hint(hint);
355 }
356 semantics
357 .child(self.build_toggleable_with_child(
358 app,
359 Some(focus_node),
360 None,
361 autofocus,
362 Some(mouse_cursor),
363 child,
364 ))
365 .into_widget()
366 }
367}
368
369#[cfg(test)]
370mod tests {
371 use std::any::Any;
372 use std::cell::{Cell, RefCell};
373 use std::time::Duration;
374 use waft_foundation::Ref;
375
376 use waft_embedder::{Canvas, Size};
377 use waft_rendering::CustomPainter;
378 use waft_services::SystemMouseCursors;
379
380 use super::*;
381 use crate::framework::IntoWidget;
382 use crate::testing::{WidgetTester, find, test_widgets};
383 use crate::widgets::basic::{Builder, Center, CustomPaint, Directionality, SizedBox};
384 use crate::widgets::focus_manager::FocusNode;
385 use crate::widgets::radio_group::{AnyRadioClient, RadioGroup, RadioGroupRegistry};
386 use crate::widgets::widget_state::WidgetStateProperty;
387 use waft_embedder::TextDirection;
388
389 struct TestRegistry {
391 group_value: Option<u32>,
392 clients: Vec<AnyRadioClient<u32>>,
393 }
394
395 impl RadioGroupRegistry<u32> for TestRegistry {
396 fn group_value(self: Handle<Self>, app: &App) -> Option<u32> {
397 app.get(self).group_value
398 }
399
400 fn register_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<u32>) {
401 app.get_mut(self).clients.push(radio);
402 }
403
404 fn unregister_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<u32>) {
405 app.get_mut(self).clients.retain(|client| *client != radio);
406 }
407
408 fn on_changed(self: Handle<Self>, app: &mut App, value: Option<u32>) {
409 app.get_mut(self).group_value = value;
410 }
411 }
412
413 fn registry(app: &mut App) -> Ref<TestRegistry> {
414 app.create(TestRegistry {
415 group_value: None,
416 clients: Vec::new(),
417 })
418 }
419
420 fn raw_radio(
421 node: FocusNodeRef,
422 registry: Option<RadioGroupRegistryRef<u32>>,
423 enabled: bool,
424 toggleable: bool,
425 captured: Rc<Cell<Option<AnyToggleableState>>>,
426 child: impl Fn() -> WidgetRef + 'static,
427 ) -> RawRadio<u32> {
428 RawRadio::new(
429 0,
430 <dyn WidgetStateProperty<MouseCursorRef>>::all(SystemMouseCursors::CLICK.into()),
431 toggleable,
432 node,
433 false,
434 registry,
435 enabled,
436 Rc::new(move |_app, _context, state| {
437 captured.set(Some(state));
438 child()
439 }),
440 )
441 }
442
443 struct TestPainter;
445
446 impl CustomPainter for TestPainter {
447 fn paint(&self, _app: &mut App, _canvas: &mut Canvas, _size: Size) {}
448
449 fn should_repaint(&self, _app: &App, _old_delegate: &dyn CustomPainter) -> bool {
450 true
451 }
452
453 fn as_any(&self) -> &dyn Any {
454 self
455 }
456 }
457
458 fn painted_box() -> WidgetRef {
459 CustomPaint::new()
460 .size(Size::new(40.0, 40.0))
461 .painter(TestPainter)
462 .into_widget()
463 }
464
465 fn focus_node(tester: &WidgetTester) -> FocusNodeRef {
466 tester.update(|app| FocusNode::new(app).erase())
467 }
468
469 #[test]
470 fn a_tap_selects_the_radio_in_its_registry() {
471 test_widgets(|tester| {
472 let node = focus_node(tester);
473 let registry = tester.update(registry);
474 let captured = Rc::new(Cell::new(None));
475 let build = |captured: &Rc<Cell<Option<AnyToggleableState>>>| {
476 raw_radio(
477 node.clone(),
478 Some(registry.erase()),
479 true,
480 true,
481 Rc::clone(captured),
482 painted_box,
483 )
484 };
485
486 tester.pump_widget(build(&captured));
487 let actual_state = captured.get().expect("the builder ran");
488 {
489 let app = tester.cell.borrow();
490 assert!(actual_state.tristate(&app));
491 assert_eq!(actual_state.value(&app), Some(false));
492 assert_eq!(app.get(®istry).group_value, None);
493
494 let state = app
495 .handle::<RawRadioState<u32>>(actual_state.id())
496 .expect("the radio's state");
497 assert!(
498 app.get(®istry)
499 .clients
500 .contains(&state.as_radio_client())
501 );
502 }
503
504 tester.tap(find::by_type::<RawRadio<u32>>());
505 tester.pump_widget(build(&captured));
507
508 let app = tester.cell.borrow();
509 assert_eq!(app.get(®istry).group_value, Some(0));
510 assert_eq!(actual_state.value(&app), Some(true));
511 });
512 }
513
514 #[test]
515 fn a_disabled_radio_does_not_report_a_tap() {
516 test_widgets(|tester| {
517 let node = focus_node(tester);
518 let registry = tester.update(registry);
519 let captured = Rc::new(Cell::new(None));
520
521 tester.pump_widget(raw_radio(
522 node,
523 Some(registry.erase()),
524 false,
525 true,
526 captured,
527 painted_box,
528 ));
529 tester.tap(find::by_type::<RawRadio<u32>>());
530
531 assert_eq!(tester.cell.borrow().get(®istry).group_value, None);
533 });
534 }
535
536 #[test]
537 #[should_panic(expected = "an enabled raw radio must have a registry")]
538 fn an_enabled_radio_without_a_registry_is_rejected() {
539 test_widgets(|tester| {
540 let node = focus_node(tester);
541
542 raw_radio(
543 node,
544 None,
545 true,
546 true,
547 Rc::new(Cell::new(None)),
548 painted_box,
549 );
550 });
551 }
552
553 fn string_radio_group(
556 node: FocusNodeRef,
557 group_value: Option<String>,
558 changes: Rc<RefCell<Vec<Option<String>>>>,
559 captured: Rc<Cell<Option<AnyToggleableState>>>,
560 ) -> WidgetRef {
561 let mut group = RadioGroup::<String>::new(
562 Rc::new(move |_app, value| changes.borrow_mut().push(value)),
563 Builder::new(move |app, context| {
564 let captured = Rc::clone(&captured);
565 RawRadio::new(
566 String::from("lafayette"),
567 <dyn WidgetStateProperty<MouseCursorRef>>::all(
568 SystemMouseCursors::CLICK.into(),
569 ),
570 true,
571 node.clone(),
572 false,
573 RadioGroup::<String>::maybe_of(app, context),
574 true,
575 Rc::new(move |_app, _context, state| {
576 captured.set(Some(state));
577 painted_box()
578 }),
579 )
580 .into_widget()
581 }),
582 );
583 if let Some(group_value) = group_value {
584 group = group.group_value(group_value);
585 }
586 group.into_widget()
587 }
588
589 #[test]
590 fn a_radio_takes_a_string_value_compared_with_eq() {
591 test_widgets(|tester| {
592 let node = focus_node(tester);
593 let changes: Rc<RefCell<Vec<Option<String>>>> = Rc::default();
594 let captured = Rc::new(Cell::new(None));
595
596 tester.pump_widget(string_radio_group(
597 node.clone(),
598 None,
599 Rc::clone(&changes),
600 Rc::clone(&captured),
601 ));
602 let state = captured.get().expect("the builder ran");
603 assert_eq!(state.value(&tester.cell.borrow()), Some(false));
604
605 tester.tap(find::by_type::<RawRadio<String>>());
606 assert_eq!(*changes.borrow(), [Some(String::from("lafayette"))]);
607
608 tester.pump_widget(string_radio_group(
610 node,
611 Some(String::from("lafayette")),
612 Rc::clone(&changes),
613 Rc::clone(&captured),
614 ));
615 assert_eq!(state.value(&tester.cell.borrow()), Some(true));
616
617 tester.tap(find::by_type::<RawRadio<String>>());
619 assert_eq!(*changes.borrow(), [Some(String::from("lafayette")), None]);
620 });
621 }
622
623 #[test]
624 #[should_panic(expected = "No WidgetsLocalizations found")]
625 fn an_unselected_radio_on_ios_reads_the_widgets_localizations() {
626 let mut tester = WidgetTester::on(TargetPlatform::IOS);
627 let node = focus_node(&tester);
628 let registry = tester.update(registry);
629
630 tester.pump_widget(raw_radio(
631 node,
632 Some(registry.erase()),
633 true,
634 false,
635 Rc::new(Cell::new(None)),
636 painted_box,
637 ));
638 }
639
640 #[test]
641 fn a_radio_at_zero_area_does_not_crash() {
642 test_widgets(|tester| {
643 let node = focus_node(tester);
644 let registry = tester.update(registry);
645 let captured = Rc::new(Cell::new(None));
646 let radio = raw_radio(
647 node,
648 Some(registry.erase()),
649 true,
650 false,
651 captured.clone(),
652 || SizedBox::square(Some(24.0)).into_widget(),
653 );
654
655 tester.pump_widget(Directionality::new(
656 TextDirection::Ltr,
657 Center::new().child(SizedBox::shrink().child(radio)),
658 ));
659 tester.pump_by(Duration::from_millis(16));
660
661 let app = tester.cell.borrow();
662 let state = captured.get().expect("the builder ran");
663 let size = state.context(&app).size(&app);
664 assert_eq!(size, Some(Size::ZERO));
665 });
666 }
667}