diff --git a/crates/kobold_router/src/lib.rs b/crates/kobold_router/src/lib.rs index 95dc023..c1fcc07 100644 --- a/crates/kobold_router/src/lib.rs +++ b/crates/kobold_router/src/lib.rs @@ -68,17 +68,6 @@ impl Router { } } - /// Add a route to the router - // pub fn add_route(&mut self, route: &str, view: F) - // where - // F: Fn() + 'static, - // { - // self.router - // .borrow_mut() - // .insert(route, Box::new(move || view())) - // .expect_throw("failed to insert route"); - // } - /// Add a route to the router pub fn add_route(&mut self, route: &str, view: impl View) { self.router @@ -87,6 +76,25 @@ impl Router { .expect_throw("failed to insert route"); } + pub fn add_route_with_params( + &mut self, + route: &str, + params: T, + closure: impl FnOnce(T) -> V + 'static, + ) where + V: kobold::View, + { + let view = move |params: T| { + let view = closure(params); + get_js_value(view) + }; + + self.router + .borrow_mut() + .insert(route, view(params)) + .expect_throw("failed to insert route"); + } + fn handle_route(&mut self) { log_1(&JsValue::from_str("Ran route")); diff --git a/examples/router/src/main.rs b/examples/router/src/main.rs index 9552dd2..4adcf62 100644 --- a/examples/router/src/main.rs +++ b/examples/router/src/main.rs @@ -1,5 +1,6 @@ use kobold::prelude::*; use kobold::View; +use kobold_router::ParamError; use kobold_router::Router; use wasm_bindgen::JsValue; use web_sys::console::error_1; @@ -25,24 +26,12 @@ fn navigate<'a>() -> impl View + 'a { ) } -#[component(auto_branch)] -fn inventory() -> impl View + 'static { +#[component] +fn inventory(id: Option) -> impl View + 'static { //TODO still need to remove need to get a new router - let router = get_router(); - let id = router.get_param::("id"); - match id { - Ok(id) => { - view! { -

"ID: "{ id }

- } - } - Err(param_err) => { - error_1(&JsValue::from_str(&format!("{:?}", param_err))); - view! { -

"Could not read the value of id"

- } - } + view! { +

"ID: "{ id }

} } @@ -88,10 +77,27 @@ fn route_two(_state: &Hook) -> impl View + '_ { fn get_router() -> Router { let mut router = Router::new(); - router.add_route("/one", stateful(State::default, route_one)); router.add_route("/two", stateful(State::default, route_two)); - // router.add_route("/inventory/{id}", view!()); + router.add_route_with_params("/inventory/{id}", (2, ""), |(id, foo)| { + view! { + + } + }); + // router.add_route_with_params("/inventory/{id}", ||(id, foo): (usize, &str), { + // |params| { + // // let id = params.get(0).unwrap().as_f64().unwrap() as usize; + // view! { + // + // } + // } + // }); + // router.add_route_with_params("/inventory/{id}", |(id, foo): (usize, &str)| { + // view! { + //

"ID: "{ id }

+ //

"Foo: "{ foo }

+ // } + // }); // router.add_route("/route-test", view!()); router