checkbox_with_label.rs

 1use std::sync::Arc;
 2
 3use crate::{prelude::*, Checkbox};
 4
 5/// A [`Checkbox`] that has a [`Label`].
 6#[derive(IntoElement)]
 7pub struct CheckboxWithLabel {
 8    id: ElementId,
 9    label: Label,
10    checked: Selection,
11    on_click: Arc<dyn Fn(&Selection, &mut WindowContext) + 'static>,
12}
13
14impl CheckboxWithLabel {
15    pub fn new(
16        id: impl Into<ElementId>,
17        label: Label,
18        checked: Selection,
19        on_click: impl Fn(&Selection, &mut WindowContext) + 'static,
20    ) -> Self {
21        Self {
22            id: id.into(),
23            label,
24            checked,
25            on_click: Arc::new(on_click),
26        }
27    }
28}
29
30impl RenderOnce for CheckboxWithLabel {
31    fn render(self, cx: &mut WindowContext) -> impl IntoElement {
32        h_flex()
33            .gap(Spacing::Large.rems(cx))
34            .child(Checkbox::new(self.id.clone(), self.checked).on_click({
35                let on_click = self.on_click.clone();
36                move |checked, cx| {
37                    (on_click)(checked, cx);
38                }
39            }))
40            .child(
41                div()
42                    .id(SharedString::from(format!("{}-label", self.id)))
43                    .on_click(move |_event, cx| {
44                        (self.on_click)(&self.checked.inverse(), cx);
45                    })
46                    .child(self.label),
47            )
48    }
49}