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,
};
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>),
}
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),
}
}
}
pub trait RadioGroupRegistry<T: Clone + PartialEq + 'static>: Sized + 'static {
fn as_radio_group_registry(self: Handle<Self>) -> AnyRadioGroupRegistry<T> {
AnyRadioGroupRegistry {
id: self.id(),
vtable: const { &RadioGroupRegistryVTable::<T>::of::<Self>() },
}
}
fn group_value(self: Handle<Self>, app: &App) -> Option<T>;
fn register_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<T>);
fn unregister_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<T>);
fn on_changed(self: Handle<Self>, app: &mut App, value: Option<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()
}
}
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> {
pub fn id(self) -> HandleId {
self.id
}
pub fn group_value(self, app: &App) -> Option<T> {
(self.vtable.group_value)(app, self.id)
}
pub fn register_client(self, app: &mut App, radio: AnyRadioClient<T>) {
(self.vtable.register_client)(app, self.id, radio);
}
pub fn unregister_client(self, app: &mut App, radio: AnyRadioClient<T>) {
(self.vtable.unregister_client)(app, self.id, radio);
}
pub fn on_changed(self, app: &mut App, value: Option<T>) {
(self.vtable.on_changed)(app, self.id, value);
}
pub fn upgrade(self, app: &App) -> Option<RadioGroupRegistryRef<T>> {
Retained::upgrade(app, self)
}
#[track_caller]
pub fn keep(self, app: &App) -> RadioGroupRegistryRef<T> {
Retained::keep(app, self)
}
}
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),
}
}
}
pub struct RadioClientData<T: Clone + PartialEq + 'static> {
registry: Option<RadioGroupRegistryRef<T>>,
}
impl<T: Clone + PartialEq + 'static> RadioClientData<T> {
pub fn new() -> RadioClientData<T> {
RadioClientData { registry: None }
}
}
impl<T: Clone + PartialEq + 'static> Default for RadioClientData<T> {
fn default() -> RadioClientData<T> {
RadioClientData::new()
}
}
#[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
}
};
}
pub trait RadioClient<T: Clone + PartialEq + 'static>: Sized + 'static {
fn radio_client_data(self: Handle<Self>, app: &App) -> &RadioClientData<T>;
fn radio_client_data_mut(self: Handle<Self>, app: &mut App) -> &mut RadioClientData<T>;
fn as_radio_client(self: Handle<Self>) -> AnyRadioClient<T> {
AnyRadioClient {
id: self.id(),
vtable: const { &RadioClientVTable::<T>::of::<Self>() },
}
}
fn tristate(self: Handle<Self>, app: &App) -> bool;
fn radio_value(self: Handle<Self>, app: &App) -> T;
fn enabled(self: Handle<Self>, app: &App) -> bool;
fn focus_node(self: Handle<Self>, app: &App) -> AnyFocusNode;
fn registry(self: Handle<Self>, app: &App) -> Option<AnyRadioGroupRegistry<T>> {
self.radio_client_data(app).registry.handle()
}
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());
}
}
}
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> {
pub fn id(self) -> HandleId {
self.id
}
pub fn tristate(self, app: &App) -> bool {
(self.vtable.tristate)(app, self.id)
}
pub fn radio_value(self, app: &App) -> T {
(self.vtable.radio_value)(app, self.id)
}
pub fn enabled(self, app: &App) -> bool {
(self.vtable.enabled)(app, self.id)
}
pub fn focus_node(self, app: &App) -> AnyFocusNode {
(self.vtable.focus_node)(app, self.id)
}
}
pub struct RadioGroup<T: Clone + PartialEq + 'static> {
pub key: Option<KeyRef>,
pub group_value: Option<T>,
pub on_changed: ValueChanged<Option<T>>,
pub child: WidgetRef,
}
impl<T: Clone + PartialEq + 'static> RadioGroup<T> {
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(),
}
}
pub fn key(mut self, key: KeyRef) -> RadioGroup<T> {
self.key = Some(key);
self
}
pub fn group_value(mut self, group_value: T) -> RadioGroup<T> {
self.group_value = Some(group_value);
self
}
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(),
}
}
}
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> {
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,
),
]
}
pub fn radios(self: Handle<Self>, app: &App) -> Vec<AnyRadioClient<T>> {
app.get(self).radios.clone()
}
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 {
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()
.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()
}
}
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 {
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
}
}
pub struct RadioGroupStateScope<T: Clone + PartialEq + 'static> {
state: Handle<RadioGroupState<T>>,
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
}
}
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,
})
}
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() {
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 {
return nodes_in_read_order;
};
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;
#[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()
}
}
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()
}
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);
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)]);
});
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));
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"
);
});
}
}