|
2 | 2 |
|
3 | 3 | Routing can be done with a combination of state and `switch`. |
4 | 4 |
|
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"`. |
7 | 16 |
|
8 | 17 | ```rust,ignore |
| 18 | +use anathema::component::*; |
| 19 | +use anathema::prelude::*; |
| 20 | +
|
| 21 | +#[derive(Debug, Default)] |
9 | 22 | struct Router; |
10 | 23 |
|
11 | 24 | 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 | + } |
14 | 35 | } |
15 | 36 | ``` |
16 | 37 |
|
| 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 | + |
17 | 43 | ```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 | +} |
20 | 74 | ``` |
0 commit comments