Skip to content

Commit

Permalink
Implement placeholder text in text boxes
Browse files Browse the repository at this point in the history
  • Loading branch information
Ralith committed Oct 22, 2023
1 parent 9d84126 commit 67c2717
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
21 changes: 19 additions & 2 deletions crates/yakui-widgets/src/widgets/textbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ pub struct TextBox {
pub style: TextStyle,
pub padding: Pad,
pub fill: Option<Color>,
/// Drawn when no text has been set
pub placeholder: String,
}

impl TextBox {
Expand All @@ -38,6 +40,7 @@ impl TextBox {
style: TextStyle::label(),
padding: Pad::all(8.0),
fill: Some(colors::BACKGROUND_3),
placeholder: String::new(),
}
}

Expand Down Expand Up @@ -76,12 +79,26 @@ impl Widget for TextBoxWidget {
fn update(&mut self, props: Self::Props) -> Self::Response {
self.props = props;

let text = self.updated_text.as_ref().unwrap_or(&self.props.text);
let mut text = self.updated_text.as_ref().unwrap_or(&self.props.text);
let use_placeholder = text.is_empty();
if use_placeholder {
text = &self.props.placeholder;
}

let mut render = RenderTextBox::new(text.clone());
render.style = self.props.style.clone();
render.selected = self.selected;
render.cursor = self.cursor;
if !use_placeholder {
render.cursor = self.cursor;
}
if use_placeholder {
// Dim towards background
render.style.color = self
.props
.style
.color
.lerp(&self.props.fill.unwrap_or(Color::CLEAR), 0.75);
}

pad(self.props.padding, || {
let res = render.show();
Expand Down
3 changes: 2 additions & 1 deletion crates/yakui/examples/textbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ use yakui::widgets::{Pad, TextBox};
use yakui::{center, use_state};

pub fn run() {
let text = use_state(|| "Hello\nWorld\nBar".to_owned());
let text = use_state(|| "".to_owned());

center(|| {
let mut my_box = TextBox::new(text.borrow().as_str());
my_box.style.font_size = 60.0;
my_box.padding = Pad::all(50.0);
my_box.placeholder = "placeholder".into();

if let Some(new_text) = my_box.show().into_inner().text {
text.set(new_text);
Expand Down

0 comments on commit 67c2717

Please sign in to comment.