gled-ui 2.32.1

gled's egui interface, shared by the desktop app and the browser
Documentation
use super::ChangeButton;
use egui::{Button, Color32, Ui, UiKind};
use gled_model::input::event::InputEvent;
use std::cell::RefCell;

thread_local! {
    /// The input events the engine reported for this frame.
    static FRAME_INPUT_EVENTS: RefCell<Vec<InputEvent>> = const { RefCell::new(Vec::new()) };
}

/// Makes `events` the input events the "Assign" menus see this frame.
pub(crate) fn set_frame_input_events(events: Vec<InputEvent>) {
    FRAME_INPUT_EVENTS.with(|frame| *frame.borrow_mut() = events);
}

fn first_frame_input_event() -> Option<InputEvent> {
    FRAME_INPUT_EVENTS.with(|frame| frame.borrow().first().copied())
}

impl ChangeButton for Option<InputEvent> {
    fn change_button(&mut self, ui: &mut Ui) -> bool {
        let mut changed = false;

        let mut layout = *ui.layout();
        layout.main_dir = egui::Direction::RightToLeft;

        ui.with_layout(layout, |ui| {
            if self.is_some() && ui.add(Button::new("🗙").fill(Color32::DARK_RED)).clicked() {
                *self = None;
                changed = true;
            }

            layout.main_justify = true;
            ui.with_layout(layout, |ui| {
                ui.menu_button(
                    match self {
                        Some(event) => format!("{event}"),
                        None => "Assign".to_string(),
                    },
                    |ui| {
                        ui.label("Please press a key or provide artnet input!");
                        if let Some(event) = first_frame_input_event().or_else(|| {
                            ui.ctx()
                                .input(|i| i.keys_down.iter().copied().next())
                                .map(|key| InputEvent::Key(crate::key_code::key_code(key)))
                        }) {
                            *self = Some(event);
                            ui.close_kind(UiKind::Menu);
                            changed = true;
                        }
                    },
                );
            });
        });

        changed
    }
}