use crate::{Bus, Css, Element, Widget};
pub use iced_style::radio::{Style, StyleSheet};
use dodrio::bumpalo;
#[allow(missing_debug_implementations)]
pub struct Radio<Message> {
is_selected: bool,
on_click: Message,
label: String,
id: Option<String>,
name: Option<String>,
#[allow(dead_code)]
style: Box<dyn StyleSheet>,
}
impl<Message> Radio<Message> {
pub fn new<F, V>(
value: V,
label: impl Into<String>,
selected: Option<V>,
f: F,
) -> Self
where
V: Eq + Copy,
F: 'static + Fn(V) -> Message,
{
Radio {
is_selected: Some(value) == selected,
on_click: f(value),
label: label.into(),
id: None,
name: None,
style: Default::default(),
}
}
pub fn style(mut self, style: impl Into<Box<dyn StyleSheet>>) -> Self {
self.style = style.into();
self
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn id(mut self, id: impl Into<String>) -> Self {
self.id = Some(id.into());
self
}
}
impl<Message> Widget<Message> for Radio<Message>
where
Message: 'static + Clone,
{
fn node<'b>(
&self,
bump: &'b bumpalo::Bump,
bus: &Bus<Message>,
_style_sheet: &mut Css<'b>,
) -> dodrio::Node<'b> {
use dodrio::builder::*;
use dodrio::bumpalo::collections::String;
let radio_label =
String::from_str_in(&self.label, bump).into_bump_str();
let event_bus = bus.clone();
let on_click = self.on_click.clone();
let (label, input) = if let Some(id) = &self.id {
let id = String::from_str_in(id, bump).into_bump_str();
(label(bump).attr("for", id), input(bump).attr("id", id))
} else {
(label(bump), input(bump))
};
let input = if let Some(name) = &self.name {
let name = String::from_str_in(name, bump).into_bump_str();
dodrio::builder::input(bump).attr("name", name)
} else {
input
};
label
.attr("style", "display: block; font-size: 20px")
.children(vec![
input
.attr("type", "radio")
.attr("style", "margin-right: 10px")
.bool_attr("checked", self.is_selected)
.on("click", move |_root, _vdom, _event| {
event_bus.publish(on_click.clone());
})
.finish(),
text(radio_label),
])
.finish()
}
}
impl<'a, Message> From<Radio<Message>> for Element<'a, Message>
where
Message: 'static + Clone,
{
fn from(radio: Radio<Message>) -> Element<'a, Message> {
Element::new(radio)
}
}