typistapp/
view.rs

1use std::{
2    io::{Write, stdout},
3    thread,
4    time::Duration,
5};
6
7use crossterm::{cursor, execute, style::Print, terminal};
8
9use crate::PER_CHARACTER_DELAY_MS;
10
11/// A struct that serves as the View (V) in MVC.
12/// Specializes in displaying the generated typist-art in the terminal.
13pub struct View {}
14
15impl View {
16    /// Animates the given typist art line by line with a per-character delay.
17    pub fn animate(data: &[String]) -> std::io::Result<()> {
18        let mut stdout = stdout();
19
20        // clear the terminal.
21        execute!(
22            stdout,
23            terminal::Clear(terminal::ClearType::All),
24            cursor::MoveTo(0, 0),
25            cursor::Hide
26        )?;
27
28        for (y, line) in data.iter().enumerate() {
29            for (x, c) in line.chars().enumerate() {
30                execute!(stdout, cursor::MoveTo((x * 2) as u16, y as u16), Print(c))?;
31                stdout.flush()?;
32                thread::sleep(Duration::from_millis(PER_CHARACTER_DELAY_MS));
33            }
34        }
35
36        // move cursor under typist-art after animation
37        execute!(stdout, cursor::MoveTo(0, data.len() as u16), cursor::Show)?;
38
39        Ok(())
40    }
41}