3个不稳定版本
0.2.0 | 2021年11月14日 |
---|---|
0.1.1 | 2021年9月12日 |
0.1.0 | 2021年9月12日 |
#6 in #tui-rs
16KB
272 行代码
tui-clap
tui-rs默认不支持输入小部件。这个crate提供对输入处理的抽象,并与clap的命令参数解析一起使用。
入门
tui-clap
提供两个小部件(输入和输出),并负责解析对clap
应用的输入。要使其工作,必须手动实现三个点
- 必须在主循环中包含获取事件
- 必须渲染输出和小部件
- 必须处理来自clap的arg匹配
以下代码演示了这三个点。
fn main() -> Result<(), io::Error> {
let yaml = load_yaml!("cli.yaml");
let clapp = App::from(yaml);
let stdout = io::stdout();
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
// Create a TuiClap instance and pass over a function that handles the arg matches
let mut tui = TuiClap::from_app(clapp);
terminal.clear();
// handle events, Events struct is a helper struct to read from crossterm events
let events = Events::default();
loop {
// your drawing method
draw(&mut terminal, &mut tui)?;
// handle events manually with the provided events struct, but you can use your own
if let Ok(Some(Event::Key(key_event))) = events.next() {
match key_event.code {
KeyCode::Backspace => {
tui.state().del_char()
}
KeyCode::Enter => {
if let Ok(matches) = tui.parse() {
match handle_matches(matches) {
Ok(output) => {
for message in output {
tui.write_to_output(message)
}
}
Err(err) => tui.write_to_output(err)
}
}
}
KeyCode::Char(char) => {
tui.state().add_char(char)
},
_ => {}
}
}
}
}
// your drawing method
fn draw<B: Backend>(terminal: &mut Terminal<B>, tui: &mut TuiClap) -> io::Result<()>{
terminal.draw(|f| {
let size = f.size();
// render the input widget of tui-clap
tui.render_input(f, size);
// render the output widget of tui-clap
tui.render_output(f, size);
});
Ok(())
}
// function that handles arg matches and returns a vec of strings that is pushed to the output widget
// return Ok() with vec of message that should be added to the output
// return Err(message) to display an error in the output
fn handle_matches(matches: ArgMatches) -> Result<Vec<String>, String> {}
Ok(vec!["handled".to_string()])
}
示例
查看example
文件夹或运行cargo run --example 命令
依赖关系
~5MB
~83K SLoC