keyboard input

This commit is contained in:
2024-09-21 19:08:03 +02:00
parent f47f3575de
commit 56d1691397
5 changed files with 85 additions and 64 deletions
+22 -26
View File
@@ -1,8 +1,6 @@
use crate::{Component, ComponentWrapper};
use k_board::{keyboard::Keyboard, keys::Keys};
use crate::{flush, key, read_key, Component, ComponentWrapper};
impl Component for String {
fn render(&mut self) -> String {
fn render(&self) -> String {
self.clone()
}
}
@@ -11,51 +9,49 @@ pub fn text(text: &str) -> ComponentWrapper<String> {
ComponentWrapper::new(text.to_string())
}
#[derive(Clone)]
pub struct Input {
pub max_length: usize,
}
impl Component for Input {
fn render(&mut self) -> String {
fn render(&self) -> String {
format!(
" {}\n|{}|\n {}\x1b[1A\x1b[{}D",
" {}\n|{}|\n {}",
"_".repeat(self.max_length),
" ".repeat(self.max_length),
"‾".repeat(self.max_length),
self.max_length
)
}
fn run(&mut self, x: usize, y: usize) -> String {
print!("\x1B[{};{}H", y + 2, x + 2);
flush();
let mut input = String::new();
loop {
let key = Keyboard::new().read_key();
if key == Keys::Enter {
return input;
}
if input.len() < self.max_length {
match key {
Keys::Char(c) => {
match read_key().as_str() {
key::ENTER => {
print!("\n\n");
return input;
}
key::BACKSPACE => {
if input.len() > 0 {
input.pop();
print!("\x1b[1D \x1b[1D");
flush();
}
}
c => {
if input.len() < self.max_length {
input += c.to_string().as_str();
print!("{c}");
flush();
}
Keys::Space => {
input += " ";
print!(" ");
}
Keys::Delete => {
if input.len() > 0 {
input.pop();
print!("\x1b[1D \x1b[1D");
}
}
_ => {}
}
}
}
}
}
pub fn input(max_length: usize) -> ComponentWrapper<Input> {
pub fn input_box(max_length: usize) -> ComponentWrapper<Input> {
ComponentWrapper::new(Input { max_length })
}