Better Menu API

Now offer non-chainable methods as well.
This commit is contained in:
Alexandre Bury 2016-07-02 20:44:27 -07:00
parent e439b422da
commit 692c310656
2 changed files with 29 additions and 17 deletions

View File

@ -14,19 +14,17 @@ fn main() {
.add("File", .add("File",
MenuTree::new() MenuTree::new()
.leaf("New", |s| s.add_layer(Dialog::info("New file!"))) .leaf("New", |s| s.add_layer(Dialog::info("New file!")))
.subtree("Recent", .subtree("Recent", MenuTree::new().with(|tree| {
MenuTree::new() for i in 1..6 {
.leaf("Item 1", |_| ()) tree.add_leaf(&format!("Item {}", i), |_| ())
.leaf("Item 1", |_| ()) }
.leaf("Item 1", |_| ()) }))
.leaf("Item 1", |_| ()))
.delimiter() .delimiter()
.leaf("Item 1", |_| ()) .with(|tree| {
.leaf("Item 1", |_| ()) for i in 1..10 {
.leaf("Item 1", |_| ()) tree.add_leaf(&format!("Option {}", i), |_| ());
.leaf("Item 1", |_| ()) }
.leaf("Item 1", |_| ()) })
.leaf("Item 1", |_| ())
.delimiter() .delimiter()
.leaf("Quit", |s| s.quit())) .leaf("Quit", |s| s.quit()))
.add("Help", .add("Help",

View File

@ -54,20 +54,34 @@ impl MenuTree {
self.children.is_empty() self.children.is_empty()
} }
pub fn delimiter(mut self) -> Self { pub fn add_delimiter(&mut self) {
self.children.push(MenuItem::Delimiter); self.children.push(MenuItem::Delimiter);
self
} }
pub fn leaf<F: 'static + Fn(&mut Cursive)>(mut self, title: &str, cb: F) -> Self { pub fn delimiter(self) -> Self {
self.with(|menu| menu.add_delimiter())
}
pub fn add_leaf<F: 'static + Fn(&mut Cursive)>(&mut self, title: &str, cb: F) {
self.children self.children
.push(MenuItem::Leaf(title.to_string(), Rc::new(cb))); .push(MenuItem::Leaf(title.to_string(), Rc::new(cb)));
self
} }
pub fn subtree(mut self, title: &str, tree: MenuTree) -> Self { pub fn leaf<F: 'static + Fn(&mut Cursive)>(self, title: &str, cb: F) -> Self {
self.with(|menu| menu.add_leaf(title, cb))
}
pub fn add_subtree(&mut self, title: &str, tree: MenuTree) {
self.children self.children
.push(MenuItem::Subtree(title.to_string(), Rc::new(tree))); .push(MenuItem::Subtree(title.to_string(), Rc::new(tree)));
}
pub fn subtree(self, title: &str, tree: MenuTree) -> Self {
self.with(|menu| menu.add_subtree(title, tree))
}
pub fn with<F: FnOnce(&mut Self)>(mut self, f: F) -> Self {
f(&mut self);
self self
} }
} }