kitchen/web/src/web.rs

159 lines
5.2 KiB
Rust
Raw Normal View History

2022-01-13 18:07:01 -05:00
// Copyright 2022 Jeremy Wall
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2022-01-25 21:03:36 -05:00
use crate::{console_debug, console_error, console_log};
2022-01-23 14:28:01 -05:00
use reqwasm::http;
2022-01-25 20:32:17 -05:00
use sycamore::context::{use_context, ContextProvider, ContextProviderProps};
use sycamore::futures::spawn_local_in_scope;
use sycamore::prelude::*;
2022-01-26 20:40:21 -05:00
use sycamore_router::{HistoryIntegration, Route, Router, RouterProps};
2022-01-23 14:28:01 -05:00
use recipes::{parse, Recipe};
2022-01-25 20:32:17 -05:00
#[derive(Clone)]
2022-01-24 19:59:16 -05:00
struct AppService {
2022-01-26 19:15:43 -05:00
recipes: Signal<Vec<(usize, Recipe)>>,
2022-01-23 14:28:01 -05:00
}
2022-01-24 19:59:16 -05:00
impl AppService {
fn new() -> Self {
Self {
2022-01-25 20:32:17 -05:00
recipes: Signal::new(Vec::new()),
2022-01-24 19:59:16 -05:00
}
}
2022-01-23 14:28:01 -05:00
2022-01-26 19:15:43 -05:00
async fn fetch_recipes() -> Result<Vec<(usize, Recipe)>, String> {
2022-01-24 19:59:16 -05:00
let resp = match http::Request::get("/api/v1/recipes").send().await {
Ok(resp) => resp,
Err(e) => return Err(format!("Error: {}", e)),
};
if resp.status() != 200 {
return Err(format!("Status: {}", resp.status()));
} else {
2022-01-25 21:03:36 -05:00
console_debug!("We got a valid response back!");
2022-01-24 19:59:16 -05:00
let recipe_list = match resp.json::<Vec<String>>().await {
Ok(recipes) => recipes,
Err(e) => return Err(format!("Eror getting recipe list as json {}", e)),
};
let mut parsed_list = Vec::new();
for r in recipe_list {
let recipe = match parse::as_recipe(&r) {
Ok(r) => r,
Err(e) => {
2022-01-25 21:03:36 -05:00
console_error!("Error parsing recipe {}", e);
2022-01-24 19:59:16 -05:00
break;
2022-01-23 14:28:01 -05:00
}
2022-01-24 19:59:16 -05:00
};
2022-01-25 21:03:36 -05:00
console_debug!("We parsed a recipe {}", recipe.title);
2022-01-24 19:59:16 -05:00
parsed_list.push(recipe);
2022-01-23 14:28:01 -05:00
}
2022-01-26 19:15:43 -05:00
return Ok(parsed_list.drain(0..).enumerate().collect());
2022-01-23 14:28:01 -05:00
}
2022-01-24 19:59:16 -05:00
}
2022-01-26 19:15:43 -05:00
fn get_recipes(&self) -> Signal<Vec<(usize, Recipe)>> {
2022-01-25 20:32:17 -05:00
self.recipes.clone()
2022-01-24 19:59:16 -05:00
}
2022-01-26 19:15:43 -05:00
fn set_recipes(&mut self, recipes: Vec<(usize, Recipe)>) {
2022-01-25 20:32:17 -05:00
self.recipes.set(recipes);
2022-01-24 19:59:16 -05:00
}
}
/// Component to list available recipes.
2022-01-25 20:32:17 -05:00
#[component(RecipeList<G>)]
fn recipe_list() -> View<G> {
2022-01-25 21:14:30 -05:00
let app_service = use_context::<AppService>();
2022-01-24 19:59:16 -05:00
2022-01-26 19:15:43 -05:00
let titles = create_memo(cloned!(app_service => move || {
app_service.get_recipes().get().iter().map(|(i, r)| (*i, r.title.clone())).collect::<Vec<(usize, String)>>()
}));
2022-01-25 20:32:17 -05:00
view! {
2022-01-23 14:28:01 -05:00
ul {
2022-01-26 19:15:43 -05:00
Keyed(KeyedProps{
iterable: titles,
template: |(i, title)| {
view! { li(on:click=move |_| {
console_log!("clicked item with index: {}", i)
}) { (title) } }
},
key: |(i, title)| (*i, title.clone()),
2022-01-25 20:32:17 -05:00
})
2022-01-23 14:28:01 -05:00
}
2022-01-25 20:32:17 -05:00
}
2022-01-23 14:28:01 -05:00
}
2022-01-13 18:07:01 -05:00
2022-01-26 20:40:21 -05:00
#[derive(Route, Debug)]
enum AppRoutes {
#[to("/ui")]
Root,
#[to("/ui/recipe/<index>")]
Recipe { index: usize },
#[to("/ui/menu")]
Menu,
#[not_found]
NotFound,
}
2022-01-25 20:32:17 -05:00
#[component(UI<G>)]
pub fn ui() -> View<G> {
2022-01-25 21:14:30 -05:00
let app_service = AppService::new();
2022-01-25 21:03:36 -05:00
console_log!("Starting UI");
2022-01-26 20:40:21 -05:00
create_effect(cloned!((app_service) => move || {
spawn_local_in_scope({
let mut app_service = app_service.clone();
async move {
match AppService::fetch_recipes().await {
Ok(recipes) => {
app_service.set_recipes(recipes);
}
Err(msg) => console_error!("Failed to get recipes {}", msg),
2022-01-25 20:32:17 -05:00
}
2022-01-24 19:59:16 -05:00
}
2022-01-26 20:40:21 -05:00
});
}));
2022-01-25 20:32:17 -05:00
view! {
2022-01-26 20:40:21 -05:00
Router(RouterProps::new(HistoryIntegration::new(), move |routes: ReadSignal<AppRoutes>| {
let t = create_memo(cloned!((app_service) => move || {
console_debug!("Determining route.");
let route = routes.get();
console_debug!("Route {:?}", route);
match route.as_ref() {
AppRoutes::Root => view! {
div { "hello chefs!" }
ContextProvider(ContextProviderProps {
value: app_service.clone(),
children: || view! { RecipeList() }
})
},
AppRoutes::Recipe{index:_idx} => view! {
"TODO!!"
},
AppRoutes::Menu => view! {
"TODO!!"
},
AppRoutes::NotFound => view! {
"NotFound"
}
}
}));
console_debug!("Created our route view memo.");
view! {
div(class="app") {
(t.get().as_ref().clone())
}
}
}))
2022-01-25 20:32:17 -05:00
}
2022-01-23 14:28:01 -05:00
}