Add on_submit to EditView

It simplifies the Edit example
This commit is contained in:
Alexandre Bury 2016-07-30 02:34:47 -07:00
parent 42a377d92b
commit 3726df46b7
2 changed files with 33 additions and 18 deletions

View File

@ -6,15 +6,9 @@ fn main() {
let mut siv = Cursive::new();
// Create a dialog with an edit text and a button.
siv.add_layer(Dialog::new(EditView::new().min_length(20).with_id("edit"))
.padding((1, 1, 1, 0))
.title("Enter your name")
.button("Ok", |s| {
// When the button is clicked, read the text and print it in a new dialog.
let name = s.find_id::<EditView>("edit")
.unwrap()
.get_content()
.to_string();
siv.add_layer(Dialog::new(EditView::new()
.min_length(20)
.on_submit(|s, name| {
if name.is_empty() {
s.add_layer(Dialog::new(TextView::new("Please enter a name!"))
.dismiss_button("Ok"));
@ -24,7 +18,9 @@ fn main() {
s.add_layer(Dialog::new(TextView::new(&content))
.button("Quit", |s| s.quit()));
}
}));
}))
.padding((1, 1, 1, 0))
.title("Enter your name"));
siv.run();
}

View File

@ -70,6 +70,9 @@ pub struct EditView {
/// Will be called with the current content and the cursor position
on_edit: Option<Rc<Fn(&mut Cursive, &str, usize)>>,
/// Callback when <Enter> is pressed.
on_submit: Option<Rc<Fn(&mut Cursive, &str)>>,
enabled: bool,
}
@ -85,6 +88,7 @@ impl EditView {
min_length: 1,
last_length: 0, // scrollable: false,
on_edit: None,
on_submit: None,
enabled: true,
}
}
@ -117,6 +121,14 @@ impl EditView {
self
}
/// Sets a callback to be called when `<Enter>` is pressed.
///
/// `callback` will be given the content of the view.
pub fn on_submit<F: Fn(&mut Cursive, &str) + 'static>(mut self, callback: F) -> Self {
self.on_submit = Some(Rc::new(callback));
self
}
/// Enable or disable this view.
pub fn set_enabled(&mut self, enabled: bool) {
self.enabled = enabled;
@ -294,6 +306,13 @@ impl View for EditView {
.len();
self.remove(len);
}
Event::Key(Key::Enter) if self.on_submit.is_some() => {
let cb = self.on_submit.clone().unwrap();
let content = self.content.clone();
return EventResult::with_cb(move |s| {
cb(s, &content);
});
}
_ => return EventResult::Ignored,
}