hanhan_multi_select/
lib.rs

1use eframe::egui;
2
3#[derive(Default, Clone)]
4pub struct MultiSelect {
5    pub options: Vec<String>,
6    pub selected_options: Vec<String>,
7    pub popup: bool,
8    pub title: String,
9}
10
11impl MultiSelect {
12    pub fn new(
13        options: Vec<String>,
14        selected_options: Vec<String>,
15        title: String,
16        popup: bool,
17    ) -> MultiSelect {
18        Self {
19            options,
20            selected_options,
21            popup,
22            title,
23        }
24    }
25
26    pub fn selected(&self) -> Vec<String> {
27        self.selected_options.clone()
28    }
29}
30pub fn multi_select(
31    multi_select: &mut MultiSelect,
32    refreshed: &mut bool,
33    ctx: &egui::Context,
34    ui: &mut egui::Ui,
35) {
36    if ui
37        .add(egui::SelectableLabel::new(
38            false,
39            multi_select.title.clone(),
40        ))
41        .clicked()
42    {
43        multi_select.popup = true;
44    }
45
46    if multi_select.popup {
47        multi_select.options.sort();
48        egui::Window::new("Select Options")
49            .open(&mut multi_select.popup)
50            .collapsible(false)
51            .resizable(false)
52            .scroll(true)
53            .movable(false)
54            .show(ctx, |ui| {
55                for option in &multi_select.options {
56                    let mut selected = multi_select.selected_options.contains(&option.to_string());
57                    if ui.add(egui::Checkbox::new(&mut selected, option)).clicked() {
58                        if selected {
59                            multi_select.selected_options.push(option.to_string());
60                            *refreshed = false;
61                        } else {
62                            multi_select.selected_options.retain(|x| x != option);
63                            *refreshed = false;
64                        }
65                    }
66                }
67            });
68    }
69}