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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use eframe::{
    self,
    egui::{Area, Button, Context, Id, Layout, Response, RichText, Sense, Ui, Window},
    emath::{Align, Align2},
    epaint::{Color32, Pos2, Rounding},
};

const ERROR_ICON_COLOR: Color32 = Color32::from_rgb(200, 90, 90);
const INFO_ICON_COLOR: Color32 = Color32::from_rgb(150, 200, 210);
const WARNING_ICON_COLOR: Color32 = Color32::from_rgb(230, 220, 140);
const SUCCESS_ICON_COLOR: Color32 = Color32::from_rgb(140, 230, 140);

const CAUTION_BUTTON_FILL: Color32 = Color32::from_rgb(87, 38, 34);
const SUGGESTED_BUTTON_FILL: Color32 = Color32::from_rgb(33, 54, 84);
const CAUTION_BUTTON_TEXT_COLOR: Color32 = Color32::from_rgb(242, 148, 148);
const SUGGESTED_BUTTON_TEXT_COLOR: Color32 = Color32::from_rgb(141, 182, 242);

const OVERLAY_COLOR: Color32 = Color32::from_rgba_premultiplied(0, 0, 0, 200);

/// The different styles a modal button can take.
pub enum ModalButtonStyle {
    /// A normal [`egui`] button
    None,
    /// A button highlighted blue
    Suggested,
    /// A button highlighted red
    Caution,
}

/// An icon. If used, it will be shown next to the body of 
/// the modal.
#[derive(Clone, Default, PartialEq)]
pub enum Icon {
    #[default]
    /// An info icon
    Info,
    /// A warning icon
    Warning,
    /// A success icon
    Success,
    /// An error icon
    Error,
    /// A custom icon. The first field in the tuple is
    /// the text of the icon, and the second field is the
    /// color.
    Custom((String, Color32)),
}

impl std::fmt::Display for Icon {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Icon::Info => write!(f, "ℹ"),
            Icon::Warning => write!(f, "⚠"),
            Icon::Success => write!(f, "✔"),
            Icon::Error => write!(f, "❗"),
            Icon::Custom((icon_text, _)) => write!(f, "{icon_text}"),
        }
    }
}

#[derive(Clone, Default)]
struct ModalData {
    title: Option<String>,
    body: Option<String>,
    icon: Option<Icon>,
}

#[derive(Clone)]
enum ModalType {
    Modal,
    Dialog(ModalData),
}

#[derive(Clone)]
/// Information about the current state of the modal. (Pretty empty
/// right now but may be expanded upon in the future.)
struct ModalState {
    is_open: bool,
    modal_type: ModalType,
}

#[derive(Clone)]
/// Contains styling parameters for the modal, like body margin
/// and button colors.
pub struct ModalStyle {
    /// The margin around the modal body. Only applies if using
    /// [`.body()`]
    pub body_margin: f32,
    /// The margin around the container of the icon and body. Only
    /// applies if using [`.frame()`]
    pub frame_margin: f32,
    /// The margin around the container of the icon. Only applies
    /// if using [`.icon()`].
    pub icon_margin: f32,
    /// The size of any icons used in the modal
    pub icon_size: f32,
    /// The color of the overlay that dims the background
    pub overlay_color: Color32,

    /// The fill color for the caution button style
    pub caution_button_fill: Color32,
    /// The fill color for the suggested button style
    pub suggested_button_fill: Color32,

    /// The text color for the caution button style
    pub caution_button_text_color: Color32,
    /// The text color for the suggested button style
    pub suggested_button_text_color: Color32,

    /// The text of the acknowledgement button for dialogs
    pub dialog_ok_text: String,

    /// The color of the info icon
    pub info_icon_color: Color32,
    /// The color of the warning icon
    pub warning_icon_color: Color32,
    /// The color of the success icon
    pub success_icon_color: Color32,
    /// The color of the error icon
    pub error_icon_color: Color32,  

    /// The alignment of text inside the body
    pub body_alignment: Align,
}

impl ModalState {
    fn load(ctx: &Context, id: Id) -> Self {
        ctx.data().get_persisted(id).unwrap_or_default()
    }
    fn save(self, ctx: &Context, id: Id) {
        ctx.data().insert_persisted(id, self)
    }
}

impl Default for ModalState {
    fn default() -> Self {
        Self {
            is_open: false,
            modal_type: ModalType::Modal,
        }
    }
}

impl Default for ModalStyle {
    fn default() -> Self {
        Self {
            body_margin: 5.,
            icon_margin: 7.,
            frame_margin: 2.,
            icon_size: 30.,
            overlay_color: OVERLAY_COLOR,

            caution_button_fill: CAUTION_BUTTON_FILL,
            suggested_button_fill: SUGGESTED_BUTTON_FILL,

            caution_button_text_color: CAUTION_BUTTON_TEXT_COLOR,
            suggested_button_text_color: SUGGESTED_BUTTON_TEXT_COLOR,

            dialog_ok_text: "ok".to_string(),

            info_icon_color: INFO_ICON_COLOR,
            warning_icon_color: WARNING_ICON_COLOR,
            success_icon_color: SUCCESS_ICON_COLOR,
            error_icon_color: ERROR_ICON_COLOR,

            body_alignment: Align::Min,
            // default_size: None,//Some([150., 20.]),
        }
    }
}
/// A [`Modal`] is created using [`Modal::new()`]. Make sure to use a `let` binding when
/// using [`Modal::new()`] to ensure you can call things like [`Modal::open()`] later on.
/// ```
/// let modal = Modal::new("my_modal");
/// modal.show(ctx, |ui| {
///     ui.label("Hello world!")
/// });
/// if ui.button("modal").clicked() {
///     modal.open(ctx);
/// }
/// ```
pub struct Modal {
    close_on_outside_click: bool,
    style: ModalStyle,
    ctx: Context,
    id: Id,
    window_id: Id,
}

fn ui_with_margin<R>(ui: &mut Ui, margin: f32, add_contents: impl FnOnce(&mut Ui) -> R) {
    egui::Frame::none()
        .inner_margin(margin)
        .show(ui, |ui| add_contents(ui));
}

impl Modal {
    /// Creates a new [`Modal`]. Can use constructor functions like [`Modal::with_style`]
    /// to modify upon creation.
    pub fn new(ctx: &Context, id_source: impl std::fmt::Display) -> Self {
        Self {
            id: Id::new(id_source.to_string()),
            style: ModalStyle::default(),
            ctx: ctx.clone(),
            close_on_outside_click: false,
            window_id: Id::new("window_".to_string() + &id_source.to_string()),
        }
    }

    fn set_open_state(&self, is_open: bool) {
        let mut modal_state = ModalState::load(&self.ctx, self.id);
        modal_state.is_open = is_open;
        modal_state.save(&self.ctx, self.id)
    }

    /// Open the modal; make it visible. The modal prevents user input to other parts of the
    /// application.
    pub fn open(&self) {
        self.set_open_state(true)
    }

    /// Close the modal so that it is no longer visible, allowing input to flow back into
    /// the application.
    pub fn close(&self) {
        self.set_open_state(false)
    }

    /// If set to `true`, the modal will close itself if the user clicks outside on the modal window
    /// (onto the overlay).
    pub fn with_close_on_outside_click(mut self, do_close_on_click_ouside: bool) -> Self {
        self.close_on_outside_click = do_close_on_click_ouside;
        self
    }

    /// Change the [`ModalStyle`] of the modal upon creation.
    pub fn with_style(mut self, style: &ModalStyle) -> Self {
        self.style = style.clone();
        self
    }

    /// Helper function for styling the title of the modal.
    pub fn title(&self, ui: &mut Ui, text: impl Into<RichText>) {
        let text: RichText = text.into();
        ui.vertical_centered(|ui| {
            ui.heading(text);
        });
        ui.separator();
    }

    /// Helper function for styling the icon of the modal.
    pub fn icon(&self, ui: &mut Ui, icon: Icon) {
        let color = match icon {
            Icon::Info => self.style.info_icon_color,
            Icon::Warning => self.style.warning_icon_color,
            Icon::Success => self.style.success_icon_color,
            Icon::Error => self.style.error_icon_color,
            Icon::Custom((_, color)) => color,
        };
        let text = RichText::new(icon.to_string())
            .color(color)
            .size(self.style.icon_size);
        ui_with_margin(ui, self.style.icon_margin, |ui| {
            ui.add(egui::Label::new(text));
        });
    }

    /// Helper function for styling the container the of body and icon.
    pub fn frame<R>(&self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) {
        ui.with_layout(
            Layout::top_down(Align::Center).with_cross_align(Align::Center),
            |ui| ui_with_margin(ui, self.style.frame_margin, |ui| add_contents(ui)),
        );
    }

    /// Helper function that should be used when using a body and icon together.
    pub fn body_and_icon(&self, ui: &mut Ui, text: impl Into<RichText>, icon: Icon) {
        egui::Grid::new(self.id).num_columns(2).show(ui, |ui| {
            self.icon(ui, icon);
            self.body(ui, text);
        });
    }

    /// Helper function for styling the body of the modal.
    pub fn body(&self, ui: &mut Ui, text: impl Into<RichText>) {
        let text: RichText = text.into();
        ui.with_layout(Layout::top_down(self.style.body_alignment), |ui| {
            ui_with_margin(ui, self.style.body_margin, |ui| {
                ui.label(text);
            })
        });
    }

    /// Helper function for styling the button container of the modal.
    pub fn buttons<R>(&self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) {
        ui.separator();
        ui.with_layout(Layout::right_to_left(Align::Min), add_contents);
    }

    /// Helper function for creating a normal button for the modal.
    /// Automatically closes the modal on click.
    pub fn button(&self, ui: &mut Ui, text: impl Into<RichText>) -> Response {
        self.styled_button(ui, text, ModalButtonStyle::None)
    }

    /// Helper function for creating a "cautioned" button for the modal.
    /// Automatically closes the modal on click.
    pub fn caution_button(&self, ui: &mut Ui, text: impl Into<RichText>) -> Response {
        self.styled_button(ui, text, ModalButtonStyle::Caution)
    }

    /// Helper function for creating a "suggested" button for the modal.
    /// Automatically closes the modal on click.
    pub fn suggested_button(&self, ui: &mut Ui, text: impl Into<RichText>) -> Response {
        self.styled_button(ui, text, ModalButtonStyle::Suggested)
    }

    fn styled_button(
        &self,
        ui: &mut Ui,
        text: impl Into<RichText>,
        button_style: ModalButtonStyle,
    ) -> Response {
        let button = match button_style {
            ModalButtonStyle::Suggested => {
                let text: RichText = text.into().color(self.style.suggested_button_text_color);
                Button::new(text).fill(self.style.suggested_button_fill)
            }
            ModalButtonStyle::Caution => {
                let text: RichText = text.into().color(self.style.caution_button_text_color);
                Button::new(text).fill(self.style.caution_button_fill)
            }
            ModalButtonStyle::None => Button::new(text.into()),
        };

        let response = ui.add(button);
        if response.clicked() {
            self.close()
        }
        response
    }

    /// The ui contained in this function will be shown within the modal window. The modal will only actually show
    /// when [`Modal::open`] is used.
    pub fn show<R>(&self, add_contents: impl FnOnce(&mut Ui) -> R) {
        let mut modal_state = ModalState::load(&self.ctx, self.id);
        if modal_state.is_open {
            let ctx_clone = self.ctx.clone();
            Area::new(self.id)
                .interactable(true)
                .fixed_pos(Pos2::ZERO)
                .show(&self.ctx, |ui: &mut Ui| {
                    let screen_rect = ui.ctx().input().screen_rect;
                    let area_response = ui.allocate_response(screen_rect.size(), Sense::click());
                    if area_response.clicked() && self.close_on_outside_click {
                        self.close();
                    }
                    ui.painter().rect_filled(
                        screen_rect,
                        Rounding::none(),
                        self.style.overlay_color,
                    );
                });

            let window = Window::new("")
                .id(self.window_id)
                .open(&mut modal_state.is_open)
                .title_bar(false)
                .anchor(Align2::CENTER_CENTER, [0., 0.])
                .resizable(false);

            let response = window.show(&ctx_clone, add_contents);
            if let Some(inner_response) = response {
                inner_response.response.request_focus();
                ctx_clone.move_to_top(inner_response.response.layer_id);
            }
        }
    }

    /// Open the modal as a dialog. This is a shorthand way of defining a [`Modal::show`] once,
    /// for example, if a function returns an `Error`. This should be used in conjunction with
    /// [`Modal::show_dialog`]. This function should be put AFTER any calls to
    pub fn open_dialog(
        &self,
        title: Option<impl std::fmt::Display>,
        body: Option<impl std::fmt::Display>,
        icon: Option<Icon>,
    ) {
        let modal_data = ModalData {
            title: title.map(|s| s.to_string()),
            body: body.map(|s| s.to_string()),
            icon,
        };
        let mut modal_state = ModalState::load(&self.ctx, self.id);
        modal_state.modal_type = ModalType::Dialog(modal_data);
        modal_state.is_open = true;
        modal_state.save(&self.ctx, self.id);
    }

    /// Needed in order to use [`Modal::open_dialog`]. Make sure this is called every frame, as
    /// it renders the necessary ui when using a modal as a dialog.
    pub fn show_dialog(&mut self) {
        let modal_state = ModalState::load(&self.ctx, self.id);
        if let ModalType::Dialog(modal_data) = modal_state.modal_type {
            self.close_on_outside_click = true;
            self.show(|ui| {
                if let Some(title) = modal_data.title {
                    self.title(ui, title)
                }
                self.frame(ui, |ui| {
                    if !modal_data.body.is_some() {
                        if let Some(icon) = modal_data.icon {
                            self.icon(ui, icon)
                        }
                    } else if !modal_data.icon.is_some() {
                        if let Some(body) = modal_data.body {
                            self.body(ui, body)
                        }
                    } else if modal_data.icon.is_some() && modal_data.icon.is_some() {
                        self.body_and_icon(ui, modal_data.body.unwrap(), modal_data.icon.unwrap())
                    }
                });
                self.buttons(ui, |ui| {
                    ui.with_layout(Layout::top_down_justified(Align::Center), |ui| {
                        self.button(ui, &self.style.dialog_ok_text)
                    })
                })
            });
        }
    }
}