diff --git a/examples/edit.rs b/examples/edit.rs index 8df9e8d..6221339 100644 --- a/examples/edit.rs +++ b/examples/edit.rs @@ -6,25 +6,21 @@ 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")) + 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")); + } else { + let content = format!("Hello {}!", name); + s.pop_layer(); + s.add_layer(Dialog::new(TextView::new(&content)) + .button("Quit", |s| s.quit())); + } + })) .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::("edit") - .unwrap() - .get_content() - .to_string(); - if name.is_empty() { - s.add_layer(Dialog::new(TextView::new("Please enter a name!")) - .dismiss_button("Ok")); - } else { - let content = format!("Hello {}!", name); - s.pop_layer(); - s.add_layer(Dialog::new(TextView::new(&content)) - .button("Quit", |s| s.quit())); - } - })); + .title("Enter your name")); siv.run(); } diff --git a/src/views/edit_view.rs b/src/views/edit_view.rs index 666c9b7..8775c8f 100644 --- a/src/views/edit_view.rs +++ b/src/views/edit_view.rs @@ -70,6 +70,9 @@ pub struct EditView { /// Will be called with the current content and the cursor position on_edit: Option>, + /// Callback when is pressed. + on_submit: Option>, + 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 `` is pressed. + /// + /// `callback` will be given the content of the view. + pub fn on_submit(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, }