use super::next_id;
use crate::style::Style;
use crate::{Cmd, Msg as TeaMsg};
use std::fmt;
use std::time::Duration;
const BLINK_SPEED: Duration = Duration::from_millis(530);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Mode {
#[default]
Blink,
Static,
Hide,
}
impl fmt::Display for Mode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Blink => "blink",
Self::Static => "static",
Self::Hide => "hidden",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Msg {
InitialBlink,
Blink(BlinkMsg),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BlinkMsg {
id: u64,
tag: u64,
}
impl BlinkMsg {
#[must_use]
pub const fn id(&self) -> u64 {
self.id
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Model {
pub style: Style,
pub text_style: Style,
pub blink_speed: Duration,
pub is_blinked: bool,
char: String,
id: u64,
focus: bool,
blink_tag: u64,
mode: Mode,
}
impl Default for Model {
fn default() -> Self {
Self::new()
}
}
impl Model {
#[must_use]
pub fn new() -> Self {
Self {
style: Style::new(),
text_style: Style::new(),
blink_speed: BLINK_SPEED,
is_blinked: true,
char: String::new(),
id: next_id(),
focus: false,
blink_tag: 0,
mode: Mode::Blink,
}
}
#[must_use]
pub const fn id(&self) -> u64 {
self.id
}
pub fn update(&mut self, msg: &TeaMsg<Msg>) -> Cmd<Msg> {
match msg {
TeaMsg::App(Msg::InitialBlink) if self.blinking() => self.blink(),
TeaMsg::App(Msg::Blink(b)) if self.blinking() && self.is_mine(*b) => {
self.is_blinked = !self.is_blinked;
self.blink()
}
TeaMsg::Focus => self.focus(),
TeaMsg::Blur => {
self.blur();
Cmd::none()
}
_ => Cmd::none(),
}
}
fn blinking(&self) -> bool {
self.mode == Mode::Blink && self.focus
}
const fn is_mine(&self, msg: BlinkMsg) -> bool {
msg.id == self.id && msg.tag == self.blink_tag
}
#[must_use]
pub const fn mode(&self) -> Mode {
self.mode
}
pub fn set_mode(&mut self, mode: Mode) -> Cmd<Msg> {
self.mode = mode;
self.is_blinked = mode == Mode::Hide || !self.focus;
if mode == Mode::Blink {
blink()
} else {
Cmd::none()
}
}
pub fn blink(&mut self) -> Cmd<Msg> {
if self.mode != Mode::Blink {
return Cmd::none();
}
self.blink_tag += 1;
let msg = BlinkMsg {
id: self.id,
tag: self.blink_tag,
};
crate::tick(self.blink_speed, move |_| Msg::Blink(msg))
}
pub fn focus(&mut self) -> Cmd<Msg> {
self.focus = true;
self.is_blinked = self.mode == Mode::Hide;
if self.mode == Mode::Blink {
self.blink()
} else {
Cmd::none()
}
}
pub const fn blur(&mut self) {
self.focus = false;
self.is_blinked = true;
}
#[must_use]
pub const fn focused(&self) -> bool {
self.focus
}
pub fn set_char(&mut self, c: &str) {
c.clone_into(&mut self.char);
}
#[must_use]
pub fn view(&self) -> String {
if self.is_blinked {
self.text_style.paint(&self.char)
} else {
self.style.reverse(true).paint(&self.char)
}
}
}
pub fn blink() -> Cmd<Msg> {
super::now(Msg::InitialBlink)
}
#[cfg(test)]
mod tests;