input text

This commit is contained in:
2024-09-21 08:13:33 +02:00
parent ee26dac788
commit b644df02e0
3 changed files with 74 additions and 8 deletions
+1
View File
@@ -14,3 +14,4 @@ name = "osui"
path = "src/main.rs" path = "src/main.rs"
[dependencies] [dependencies]
k_board = { version = "1.2.1", features = ["standar", "f", "alt_lower_letter", "ctrl_lower_letter", "lower_letter"] }
+14 -5
View File
@@ -2,7 +2,7 @@ use std::io::{self, Write};
pub mod ui; pub mod ui;
pub struct Component<T> { pub struct ComponentWrapper<T> {
pub component: T, pub component: T,
pub x: usize, pub x: usize,
pub y: usize, pub y: usize,
@@ -10,9 +10,15 @@ pub struct Component<T> {
pub clear_trace: bool, pub clear_trace: bool,
} }
impl<T: std::fmt::Display> Component<T> { pub trait Component {
pub fn new(component: T) -> Component<T> { fn render(&mut self) -> String {
Component { String::new()
}
}
impl<T: Component> ComponentWrapper<T> {
pub fn new(component: T) -> ComponentWrapper<T> {
ComponentWrapper {
component, component,
x: 0, x: 0,
y: 0, y: 0,
@@ -25,7 +31,10 @@ impl<T: std::fmt::Display> Component<T> {
self.clear(); self.clear();
} }
self.cleared_frame.clear(); self.cleared_frame.clear();
for (i, d) in format!("{}", self.component).split("\n").enumerate() { for (i, d) in format!("{}", self.component.render())
.split("\n")
.enumerate()
{
print!("\x1B[{};{}H{}", self.y + (i + 1), self.x, d); print!("\x1B[{};{}H{}", self.y + (i + 1), self.x, d);
self.cleared_frame += format!( self.cleared_frame += format!(
"\x1B[{};{}H{}", "\x1B[{};{}H{}",
+59 -3
View File
@@ -1,5 +1,61 @@
use crate::Component; use crate::{Component, ComponentWrapper};
use k_board::{keyboard::Keyboard, keys::Keys};
pub fn text(text: &str) -> Component<String> { impl Component for String {
Component::new(text.to_string()) fn render(&mut self) -> String {
self.clone()
}
}
pub fn text(text: &str) -> ComponentWrapper<String> {
ComponentWrapper::new(text.to_string())
}
pub struct Input {
pub max_length: usize,
}
impl Component for Input {
fn render(&mut self) -> String {
format!(
" {}\n|{}|\n {}\x1b[1A\x1b[{}D",
"_".repeat(self.max_length),
" ".repeat(self.max_length),
"‾".repeat(self.max_length),
self.max_length
)
}
}
impl Input {
pub fn get_input(&mut self) -> String {
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) => {
input += c.to_string().as_str();
print!("{c}");
}
Keys::Space => {
input += " ";
print!(" ");
}
Keys::Delete => {
input.pop();
print!("\x1b[1D \x1b[1D");
}
_ => {}
}
}
}
}
}
pub fn input(max_length: usize) -> ComponentWrapper<Input> {
ComponentWrapper::new(Input { max_length })
} }