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
use crate::{Model, Form}; use yew::{Callback, ComponentLink, Component, Html, html, Properties}; pub enum CheckBoxMessage { OnToggle, } #[derive(Properties, Clone)] pub struct CheckBoxProperties<T: Model> { pub field_name: String, pub form: Form<T>, #[prop_or_else(Callback::noop)] pub ontoggle: Callback<bool>, } pub struct CheckBox<T: Model> { link: ComponentLink<Self>, props: CheckBoxProperties<T>, } impl<T: Model> CheckBox<T> { fn value(&self) -> bool { let field_path = &self.props.field_name; self.props.form.field_value(field_path) == "true" } fn set_value(&mut self, value: bool) { let field_path = &self.props.field_name; self.props.form.set_field_value(field_path, &value.to_string()); } } impl<T: Model + Clone> Component for CheckBox<T> { type Message = CheckBoxMessage; type Properties = CheckBoxProperties<T>; fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self { Self { link, props, } } fn update(&mut self, msg: Self::Message) -> bool { match msg { CheckBoxMessage::OnToggle => { let value = !self.value(); self.set_value(value); self.props.ontoggle.emit(value); true } } } fn change(&mut self, _props: Self::Properties) -> bool { true } fn view(&self) -> Html { html! { <input type="checkbox" value=self.props.field_name onclick=self.link.callback(|e| CheckBoxMessage::OnToggle) checked=self.value() class="form-check-input form-input" /> } } }