-
-
Save w4ngzhen/96e49b5054054cab2138c976adf8c98d to your computer and use it in GitHub Desktop.
ratatui-demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "ratatui-demo" | |
version = "0.1.0" | |
edition = "2024" | |
[dependencies] | |
ratatui = { version = "0.29.0" } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use ratatui::crossterm::event::{Event, KeyCode, KeyEvent}; | |
use ratatui::prelude::*; | |
use ratatui::widgets::Block; | |
use std::io; | |
struct Cursor { | |
x: u16, | |
y: u16, | |
activated: bool, // <- 注意,因为光标的颜色与是否激活有关,这里我们简化为只记录是否激活即可 | |
} | |
fn main() -> io::Result<()> { | |
let mut terminal = ratatui::init(); | |
let mut cursor = Cursor { | |
x: 0, | |
y: 0, | |
activated: false, | |
}; | |
let result = loop { | |
terminal.draw(|f: &mut ratatui::Frame| { | |
// 先渲染一个灰色背景 | |
f.render_widget(Block::default().bg(Color::Gray), f.area()); | |
// 在对应位置渲染光标 | |
let color = if cursor.activated { | |
Color::Blue | |
} else { | |
Color::White | |
}; | |
f.buffer_mut() | |
.cell_mut(Position::new(cursor.x, cursor.y)) | |
.unwrap() | |
.set_style(Style::default().fg(color).bg(color)); | |
})?; | |
let event = ratatui::crossterm::event::read()?; | |
match event { | |
Event::Key(KeyEvent { code, .. }) => { | |
let activated = cursor.activated; | |
if KeyCode::Char('q') == code { | |
break Ok(()); | |
} else if KeyCode::Char(' ') == code { | |
cursor.activated = !activated; | |
} else if activated { | |
match code { | |
KeyCode::Up => cursor.y = cursor.y.saturating_sub(1), | |
KeyCode::Down => cursor.y = cursor.y.saturating_add(1), | |
KeyCode::Left => cursor.x = cursor.x.saturating_sub(1), | |
KeyCode::Right => cursor.x = cursor.x.saturating_add(1), | |
_ => {} | |
} | |
} | |
} | |
_ => {} | |
} | |
}; | |
ratatui::restore(); | |
result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment