checkbox_with_label.rs

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