Skip to content

Commit 80cdff2

Browse files
authored
Merge pull request #19 from togglebyte/dev
added routing recipe
2 parents a825a96 + 953fe4d commit 80cdff2

File tree

1 file changed

+60
-6
lines changed

1 file changed

+60
-6
lines changed

src/recipes/routing.md

Lines changed: 60 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,73 @@
22

33
Routing can be done with a combination of state and `switch`.
44

5-
TODO
6-
THIS IS UNFINISHED
5+
Using a `switc / case` in the template we can <something> router.
6+
7+
## Component
8+
9+
We store the route name as a `String`.
10+
11+
The component key change event can be used to select the route.
12+
In this case a route is just a `String`.
13+
14+
Pressing `a` will set the route to `"a"`, and pressing `b` will set the route to `"b"`.
15+
Any other option will set it to `"home"`.
716

817
```rust,ignore
18+
use anathema::component::*;
19+
use anathema::prelude::*;
20+
21+
#[derive(Debug, Default)]
922
struct Router;
1023
1124
impl Component for Router {
12-
State = String;
13-
Message = String;
25+
type Message = ();
26+
type State = String;
27+
28+
fn on_key(&mut self, key: KeyEvent, state: &mut Self::State, _: Children<'_, '_>, _: Context<'_, '_, Self::State>) {
29+
match key.get_char() {
30+
Some('a') => *state = "a".to_string(),
31+
Some('b') => *state = "b".to_string(),
32+
_ => *state = "home".to_string(),
33+
}
34+
}
1435
}
1536
```
1637

38+
## Template
39+
40+
Since the route is the state (a string) we can use `switch` on the state
41+
and see if it's either `"a"` or `"b"`, otherwise fallback to `@home`.
42+
1743
```aml
18-
text "hello"
19-
span "sausage"
44+
border
45+
switch state
46+
case "a": @a
47+
case "b": @b
48+
default: @home
49+
```
50+
51+
52+
## Setting up the runtime
53+
54+
Finally register both "home", "a" and "b" as templates.
55+
56+
```rust,ignore
57+
fn main() {
58+
let doc = Document::new("@index [title: 'hello']");
59+
let mut backend = TuiBackend::full_screen();
60+
let mut builder = Runtime::builder(doc, &backend);
61+
62+
// Add routes
63+
builder.component("index", "templates/index.aml", Router, String::new()).unwrap();
64+
builder.template("a", "text 'hello from A'".to_template()).unwrap();
65+
builder.template("b", "text 'hello from B'".to_template()).unwrap();
66+
builder.template("home", "text 'default'".to_template()).unwrap();
67+
68+
let res = builder.finish(&mut backend, |runtime, backend| runtime.run(backend));
69+
70+
if let Err(e) = res {
71+
eprintln!("{e}");
72+
}
73+
}
2074
```

0 commit comments

Comments
 (0)