use termusiclib::config::{SharedTuiSettings, v2::tui::theme::styles::ColorTermusic};
use tui_realm_stdlib::Paragraph;
use tuirealm::{
Component, Event, MockComponent,
event::{Key, KeyEvent},
props::{Alignment, BorderType, Borders, TextModifiers, TextSpan},
};
use crate::ui::ids::Id;
use crate::ui::model::{Model, UserEvent};
use crate::ui::msg::{ErrorPopupMsg, Msg};
#[derive(MockComponent)]
pub struct ErrorPopup {
component: Paragraph,
config: SharedTuiSettings,
}
impl ErrorPopup {
pub fn new<E: Into<anyhow::Error>>(config: SharedTuiSettings, msg: E) -> Self {
let msg = msg.into();
error!("Displaying error popup: {msg:?}");
let msg = format!("{msg:#}");
let config_r = config.read_recursive();
let color = config_r.settings.theme.get_color_from_theme(ColorTermusic::Red);
let component = {
Paragraph::default()
.borders(
Borders::default()
.color(color)
.modifiers(BorderType::Rounded),
)
.title(" Error ", Alignment::Center)
.foreground(color)
.background(config_r.settings.theme.fallback_background())
.modifiers(TextModifiers::BOLD)
.alignment(Alignment::Center)
.text([TextSpan::from(msg)])
};
drop(config_r);
Self { component, config }
}
}
impl Component<Msg, UserEvent> for ErrorPopup {
fn on(&mut self, ev: Event<UserEvent>) -> Option<Msg> {
let config = self.config.clone();
let keys = &config.read().settings.keys;
match ev {
Event::Keyboard(KeyEvent {
code: Key::Enter | Key::Esc,
..
}) => Some(Msg::ErrorPopup(ErrorPopupMsg::Close)),
Event::Keyboard(key) if key == keys.quit.get() => {
Some(Msg::ErrorPopup(ErrorPopupMsg::Close))
}
Event::Keyboard(key) if key == keys.escape.get() => {
Some(Msg::ErrorPopup(ErrorPopupMsg::Close))
}
_ => None,
}
}
}
impl Model {
pub fn mount_error_popup<E: Into<anyhow::Error>>(&mut self, err: E) {
assert!(
self.app
.remount(
Id::ErrorPopup,
Box::new(ErrorPopup::new(self.config_tui.clone(), err)),
vec![]
)
.is_ok()
);
assert!(self.app.active(&Id::ErrorPopup).is_ok());
}
pub fn umount_error_popup(&mut self) {
self.app.umount(&Id::ErrorPopup).ok();
}
}