use ratatui::{style::Color, text::Span};
#[derive(Default)]
pub struct ConnectionIndicator(ConnectionIndicatorState);
#[derive(Default)]
enum ConnectionIndicatorState {
#[default]
Disconnected,
Connecting {
spinner: i32,
},
Connected,
}
impl ConnectionIndicator {
pub fn on_step(&mut self) {
match &mut self.0 {
ConnectionIndicatorState::Connecting { spinner } => {
*spinner = (*spinner + 1) % 4;
}
_ => {}
}
}
pub fn on_connect(&mut self) {
self.0 = ConnectionIndicatorState::Connected;
}
pub fn on_disconnect(&mut self) {
self.0 = ConnectionIndicatorState::Disconnected;
}
pub fn is_connected(&self) -> bool {
matches!(self.0, ConnectionIndicatorState::Connected)
}
pub fn on_connecting(&mut self) {
if !matches!(self.0, ConnectionIndicatorState::Connecting { .. }) {
self.0 = ConnectionIndicatorState::Connecting { spinner: 0 };
}
}
pub fn symbol(&self) -> &'static str {
match &self.0 {
ConnectionIndicatorState::Disconnected => "■",
ConnectionIndicatorState::Connecting { spinner } => match spinner {
0 => "|",
1 => "/",
2 => "-",
3 => "\\",
_ => unreachable!(),
},
ConnectionIndicatorState::Connected => "●", }
}
pub fn color(&self) -> Color {
match &self.0 {
ConnectionIndicatorState::Disconnected => Color::Red,
ConnectionIndicatorState::Connecting { .. } => Color::Yellow,
ConnectionIndicatorState::Connected => Color::Green,
}
}
pub fn span(&self) -> Span<'static> {
Span::styled(self.symbol(), self.color())
}
}