SelectVIew::selection now returns Option<Rc<T>>

This commit is contained in:
Alexandre Bury 2018-07-22 20:25:13 -07:00
parent f5535f2db7
commit 0046eba66d
2 changed files with 16 additions and 9 deletions

View File

@ -1,7 +1,7 @@
extern crate cursive; extern crate cursive;
use cursive::views::{Dialog, TextView}; use cursive::views::{Dialog, TextView};
use cursive::{thene, Cursive}; use cursive::{theme, Cursive};
fn main() { fn main() {
let mut siv = Cursive::default(); let mut siv = Cursive::default();
@ -9,7 +9,7 @@ fn main() {
siv.load_theme_file("assets/style.toml").unwrap(); siv.load_theme_file("assets/style.toml").unwrap();
// Or you can directly load it from a string for easy deployment. // Or you can directly load it from a string for easy deployment.
siv.load_toml(include_str!("../assets/style.toml").unwrap()); siv.load_toml(include_str!("../assets/style.toml")).unwrap();
siv.add_layer( siv.add_layer(
Dialog::around(TextView::new( Dialog::around(TextView::new(

View File

@ -201,8 +201,13 @@ impl<T: 'static> SelectView<T> {
/// Returns the value of the currently selected item. /// Returns the value of the currently selected item.
/// ///
/// Panics if the list is empty. /// Panics if the list is empty.
pub fn selection(&self) -> Rc<T> { pub fn selection(&self) -> Option<Rc<T>> {
Rc::clone(&self.items[self.focus()].value) let focus = self.focus();
if self.len() <= focus {
None
} else {
Some(Rc::clone(&self.items[focus].value))
}
} }
/// Removes all items from this view. /// Removes all items from this view.
@ -414,9 +419,11 @@ impl<T: 'static> SelectView<T> {
fn submit(&mut self) -> EventResult { fn submit(&mut self) -> EventResult {
let cb = self.on_submit.clone().unwrap(); let cb = self.on_submit.clone().unwrap();
let v = self.selection();
// We return a Callback Rc<|s| cb(s, &*v)> // We return a Callback Rc<|s| cb(s, &*v)>
EventResult::Consumed(Some(Callback::from_fn(move |s| cb(s, &v)))) EventResult::Consumed(
self.selection()
.map(|v| Callback::from_fn(move |s| cb(s, &v))),
)
} }
fn on_event_regular(&mut self, event: Event) -> EventResult { fn on_event_regular(&mut self, event: Event) -> EventResult {
@ -554,9 +561,9 @@ impl<T: 'static> SelectView<T> {
/// Returns a callback from selection change. /// Returns a callback from selection change.
fn make_select_cb(&self) -> Option<Callback> { fn make_select_cb(&self) -> Option<Callback> {
self.on_select.clone().map(|cb| { self.on_select.clone().and_then(|cb| {
let v = self.selection(); self.selection()
Callback::from_fn(move |s| cb(s, &v)) .map(|v| Callback::from_fn(move |s| cb(s, &v)))
}) })
} }