Calendar is now displayed on home page and recipes can be scheduled without being logged
This commit is contained in:
parent
ccb1248da3
commit
37721ac3ea
22 changed files with 538 additions and 166 deletions
|
|
@ -17,6 +17,7 @@ chrono = { version = "0.4", features = ["serde", "unstable-locales"] }
|
|||
|
||||
ron = "0.8"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_html_form = "0.2"
|
||||
thiserror = "2"
|
||||
|
||||
futures = "0.3"
|
||||
|
|
@ -30,12 +31,14 @@ web-sys = { version = "0.3", features = [
|
|||
"NodeList",
|
||||
"Window",
|
||||
"Location",
|
||||
"Storage",
|
||||
"EventTarget",
|
||||
"DragEvent",
|
||||
"DataTransfer",
|
||||
"DomRect",
|
||||
"KeyboardEvent",
|
||||
"Element",
|
||||
"DomStringMap",
|
||||
"HtmlElement",
|
||||
"HtmlDivElement",
|
||||
"HtmlLabelElement",
|
||||
|
|
|
|||
|
|
@ -1,20 +1,21 @@
|
|||
use std::{cell::RefCell, rc::Rc};
|
||||
use std::{cell::RefCell, default, rc::Rc};
|
||||
|
||||
use chrono::{offset::Local, DateTime, Datelike, Days, Months, Weekday};
|
||||
use chrono::{offset::Local, DateTime, Datelike, Days, Months, NaiveDate, Weekday};
|
||||
use common::ron_api;
|
||||
use gloo::{console::log, events::EventListener};
|
||||
use gloo::{console::log, events::EventListener, utils::document};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::spawn_local;
|
||||
use web_sys::Element;
|
||||
|
||||
use crate::{
|
||||
recipe_scheduler::{self, RecipeScheduler},
|
||||
request,
|
||||
utils::{by_id, SelectorExt},
|
||||
utils::{by_id, selector, selector_all, SelectorExt},
|
||||
};
|
||||
|
||||
struct CalendarStateInternal {
|
||||
displayed_date: DateTime<Local>,
|
||||
selected_date: DateTime<Local>,
|
||||
displayed_date: NaiveDate,
|
||||
selected_date: NaiveDate,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
|
|
@ -24,7 +25,7 @@ pub struct CalendarState {
|
|||
|
||||
impl CalendarState {
|
||||
pub fn new() -> Self {
|
||||
let current_date = Local::now();
|
||||
let current_date = Local::now().date_naive();
|
||||
Self {
|
||||
internal_state: Rc::new(RefCell::new(CalendarStateInternal {
|
||||
displayed_date: current_date,
|
||||
|
|
@ -43,33 +44,48 @@ impl CalendarState {
|
|||
state_borrowed.displayed_date = state_borrowed.displayed_date - Months::new(1);
|
||||
}
|
||||
|
||||
pub fn get_displayed_date(&self) -> DateTime<Local> {
|
||||
pub fn get_displayed_date(&self) -> NaiveDate {
|
||||
self.internal_state.borrow().displayed_date
|
||||
}
|
||||
|
||||
pub fn get_selected_date(&self) -> DateTime<Local> {
|
||||
pub fn get_selected_date(&self) -> NaiveDate {
|
||||
self.internal_state.borrow().selected_date
|
||||
}
|
||||
|
||||
pub fn set_selected_date(&self, date: DateTime<Local>) {
|
||||
pub fn set_selected_date(&self, date: NaiveDate) {
|
||||
self.internal_state.borrow_mut().selected_date = date;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn setup(calendar: Element) -> CalendarState {
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct CalendarOptions {
|
||||
pub can_select_date: bool,
|
||||
// pub show_scheduled_recipes: bool,
|
||||
}
|
||||
|
||||
pub fn setup(
|
||||
calendar: Element,
|
||||
options: CalendarOptions,
|
||||
recipe_scheduler: RecipeScheduler,
|
||||
) -> CalendarState {
|
||||
let prev: Element = calendar.selector(".prev");
|
||||
let next: Element = calendar.selector(".next");
|
||||
|
||||
let state = CalendarState::new();
|
||||
|
||||
display_month(&calendar, state.clone());
|
||||
display_month(&calendar, state.clone(), options, recipe_scheduler);
|
||||
|
||||
// Click on previous month.
|
||||
let calendar_clone = calendar.clone();
|
||||
let state_clone = state.clone();
|
||||
EventListener::new(&prev, "click", move |_event| {
|
||||
state_clone.displayed_date_previous_month();
|
||||
display_month(&calendar_clone, state_clone.clone());
|
||||
display_month(
|
||||
&calendar_clone,
|
||||
state_clone.clone(),
|
||||
options,
|
||||
recipe_scheduler,
|
||||
);
|
||||
})
|
||||
.forget();
|
||||
|
||||
|
|
@ -78,33 +94,55 @@ pub fn setup(calendar: Element) -> CalendarState {
|
|||
let state_clone = state.clone();
|
||||
EventListener::new(&next, "click", move |_event| {
|
||||
state_clone.displayed_date_next_month();
|
||||
display_month(&calendar_clone, state_clone.clone());
|
||||
display_month(
|
||||
&calendar_clone,
|
||||
state_clone.clone(),
|
||||
options,
|
||||
recipe_scheduler,
|
||||
);
|
||||
})
|
||||
.forget();
|
||||
|
||||
// Click on a day of the current month.
|
||||
let days: Element = calendar.selector(".days");
|
||||
let calendar_clone = calendar.clone();
|
||||
let state_clone = state.clone();
|
||||
EventListener::new(&days, "click", move |event| {
|
||||
let target: Element = event.target().unwrap().dyn_into().unwrap();
|
||||
if target.class_name() == "number" {
|
||||
let first_day = first_grid_day(state_clone.get_displayed_date());
|
||||
let day_grid_id = target.parent_element().unwrap().id();
|
||||
let day_offset = day_grid_id[9..10].parse::<u64>().unwrap() * 7
|
||||
+ day_grid_id[10..11].parse::<u64>().unwrap();
|
||||
state_clone.set_selected_date(first_day + Days::new(day_offset));
|
||||
display_month(&calendar_clone, state_clone.clone());
|
||||
}
|
||||
})
|
||||
.forget();
|
||||
if options.can_select_date {
|
||||
let days: Element = calendar.selector(".days");
|
||||
let calendar_clone = calendar.clone();
|
||||
let state_clone = state.clone();
|
||||
EventListener::new(&days, "click", move |event| {
|
||||
let target: Element = event.target().unwrap().dyn_into().unwrap();
|
||||
|
||||
// log!(event);
|
||||
|
||||
if target.class_name() == "number" {
|
||||
let first_day = first_grid_day(state_clone.get_displayed_date());
|
||||
let day_grid_id = target.parent_element().unwrap().id();
|
||||
let day_offset = day_grid_id[9..10].parse::<u64>().unwrap() * 7
|
||||
+ day_grid_id[10..11].parse::<u64>().unwrap();
|
||||
state_clone.set_selected_date(first_day + Days::new(day_offset));
|
||||
display_month(
|
||||
&calendar_clone,
|
||||
state_clone.clone(),
|
||||
options,
|
||||
recipe_scheduler,
|
||||
);
|
||||
} else if target.class_name() == "remove-scheduled-recipe" {
|
||||
log!("REMOVE"); // TODO.
|
||||
}
|
||||
})
|
||||
.forget();
|
||||
}
|
||||
|
||||
state
|
||||
}
|
||||
|
||||
const NB_CALENDAR_ROW: u64 = 5;
|
||||
|
||||
fn display_month(calendar: &Element, state: CalendarState) {
|
||||
fn display_month(
|
||||
calendar: &Element,
|
||||
state: CalendarState,
|
||||
options: CalendarOptions,
|
||||
recipe_scheduler: RecipeScheduler,
|
||||
) {
|
||||
let date = state.get_displayed_date();
|
||||
|
||||
calendar
|
||||
|
|
@ -129,6 +167,7 @@ fn display_month(calendar: &Element, state: CalendarState) {
|
|||
for i in 0..NB_CALENDAR_ROW {
|
||||
for j in 0..7 {
|
||||
let day_element: Element = by_id(&format!("day-grid-{}{}", i, j));
|
||||
|
||||
let day_content: Element = day_element.selector(".number");
|
||||
day_content.set_inner_html(¤t.day().to_string());
|
||||
|
||||
|
|
@ -140,13 +179,13 @@ fn display_month(calendar: &Element, state: CalendarState) {
|
|||
}
|
||||
class_name += "current-month";
|
||||
}
|
||||
if current.date_naive() == Local::now().date_naive() {
|
||||
if current == Local::now().date_naive() {
|
||||
if !class_name.is_empty() {
|
||||
class_name += " ";
|
||||
}
|
||||
class_name += "today";
|
||||
}
|
||||
if current.date_naive() == state.get_selected_date().date_naive() {
|
||||
if options.can_select_date && current == state.get_selected_date() {
|
||||
if !class_name.is_empty() {
|
||||
class_name += " ";
|
||||
}
|
||||
|
|
@ -158,30 +197,82 @@ fn display_month(calendar: &Element, state: CalendarState) {
|
|||
}
|
||||
}
|
||||
|
||||
// Load and display scheduled recipes.
|
||||
// if options.show_scheduled_recipes {
|
||||
spawn_local(async move {
|
||||
let scheduled_recipes: ron_api::ScheduledRecipes = request::get(
|
||||
"calendar/get_scheduled_recipes",
|
||||
[
|
||||
("start_date", first_day.date_naive().to_string()),
|
||||
(
|
||||
"end_date",
|
||||
(first_day + Days::new(NB_CALENDAR_ROW * 7))
|
||||
.date_naive()
|
||||
.to_string(),
|
||||
),
|
||||
],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// let scheduled_recipes: ron_api::ScheduledRecipes = request::get(
|
||||
// "calendar/get_scheduled_recipes",
|
||||
// [
|
||||
// ("start_date", first_day.date_naive().to_string()),
|
||||
// (
|
||||
// "end_date",
|
||||
// (first_day + Days::new(NB_CALENDAR_ROW * 7))
|
||||
// .date_naive()
|
||||
// .to_string(),
|
||||
// ),
|
||||
// ],
|
||||
// )
|
||||
// .await
|
||||
// .unwrap();
|
||||
|
||||
for recipe in scheduled_recipes.recipes {
|
||||
// log!(recipe.1);
|
||||
// TODO
|
||||
let scheduled_recipes = recipe_scheduler
|
||||
.get_scheduled_recipes(first_day, first_day + Days::new(NB_CALENDAR_ROW * 7))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
for scheduled_recipe in selector_all::<Element>(".scheduled-recipes") {
|
||||
scheduled_recipe.set_inner_html("");
|
||||
}
|
||||
|
||||
if !scheduled_recipes.is_empty() {
|
||||
let recipe_template: Element = selector("#hidden-templates-calendar .scheduled-recipe");
|
||||
for (date, title, recipe_id) in scheduled_recipes {
|
||||
let id = format!("scheduled-recipe-{}-{}", recipe_id, date);
|
||||
if document().get_element_by_id(&id).is_some() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let delta_from_first_day = (date - first_day).num_days();
|
||||
let i = delta_from_first_day / 7;
|
||||
let j = delta_from_first_day % 7;
|
||||
let scheduled_recipes_element: Element =
|
||||
selector(&format!("#day-grid-{}{} .scheduled-recipes", i, j));
|
||||
|
||||
let recipe_element = recipe_template
|
||||
.clone_node_with_deep(true)
|
||||
.unwrap()
|
||||
.dyn_into::<Element>()
|
||||
.unwrap();
|
||||
recipe_element.set_id(&id);
|
||||
|
||||
let recipe_link_element: Element = recipe_element.selector("a");
|
||||
|
||||
// let recipe_remove_element: Element =
|
||||
// recipe_element.selector(".remove-scheduled-recipe");
|
||||
//
|
||||
// EventListener::new(&recipe_remove_element, "click", move |_event| {
|
||||
// log!("CLICK REMOVE");
|
||||
// })
|
||||
// .forget();
|
||||
|
||||
recipe_link_element
|
||||
.set_attribute("href", &format!("/recipe/view/{}", recipe_id))
|
||||
.unwrap();
|
||||
|
||||
recipe_link_element.set_inner_html(&title);
|
||||
scheduled_recipes_element
|
||||
.append_child(&recipe_element)
|
||||
.unwrap();
|
||||
|
||||
// log!(&title);
|
||||
// TODO
|
||||
}
|
||||
}
|
||||
});
|
||||
// }
|
||||
}
|
||||
|
||||
fn first_grid_day(mut date: DateTime<Local>) -> DateTime<Local> {
|
||||
pub fn first_grid_day(mut date: NaiveDate) -> NaiveDate {
|
||||
while (date - Days::new(1)).month() == date.month() {
|
||||
date = date - Days::new(1);
|
||||
}
|
||||
|
|
|
|||
29
frontend/src/home.rs
Normal file
29
frontend/src/home.rs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
use std::str::FromStr;
|
||||
|
||||
use chrono::Locale;
|
||||
use common::{ron_api, utils::substitute_with_names};
|
||||
use gloo::events::EventListener;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::spawn_local;
|
||||
use web_sys::{Element, HtmlElement, HtmlInputElement};
|
||||
|
||||
use crate::{
|
||||
calendar, modal_dialog,
|
||||
recipe_scheduler::RecipeScheduler,
|
||||
request,
|
||||
toast::{self, Level},
|
||||
utils::{get_locale, selector, SelectorExt},
|
||||
};
|
||||
|
||||
pub fn setup_page(is_user_logged: bool) -> Result<(), JsValue> {
|
||||
let recipe_scheduler = RecipeScheduler::new(!is_user_logged);
|
||||
|
||||
calendar::setup(
|
||||
selector(".calendar"),
|
||||
calendar::CalendarOptions {
|
||||
can_select_date: false,
|
||||
},
|
||||
recipe_scheduler,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -3,12 +3,16 @@ use gloo::{console::log, events::EventListener, utils::window};
|
|||
use utils::by_id;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::spawn_local;
|
||||
use web_sys::HtmlSelectElement;
|
||||
use web_sys::{HtmlElement, HtmlSelectElement};
|
||||
|
||||
use crate::utils::selector;
|
||||
|
||||
mod calendar;
|
||||
mod home;
|
||||
mod modal_dialog;
|
||||
mod on_click;
|
||||
mod recipe_edit;
|
||||
mod recipe_scheduler;
|
||||
mod recipe_view;
|
||||
mod request;
|
||||
mod toast;
|
||||
|
|
@ -21,6 +25,12 @@ pub fn main() -> Result<(), JsValue> {
|
|||
let location = window().location().pathname()?;
|
||||
let path: Vec<&str> = location.split('/').skip(1).collect();
|
||||
|
||||
let is_user_logged = selector::<HtmlElement>("html")
|
||||
.dataset()
|
||||
.get("userLogged")
|
||||
.map(|v| v == "true")
|
||||
.unwrap_or_default();
|
||||
|
||||
// if let ["recipe", "edit", id] = path[..] {
|
||||
match path[..] {
|
||||
["recipe", "edit", id] => {
|
||||
|
|
@ -31,7 +41,13 @@ pub fn main() -> Result<(), JsValue> {
|
|||
}
|
||||
["recipe", "view", id] => {
|
||||
let id = id.parse::<i64>().unwrap(); // TODO: remove unwrap.
|
||||
if let Err(error) = recipe_view::setup_page(id) {
|
||||
if let Err(error) = recipe_view::setup_page(id, is_user_logged) {
|
||||
log!(error);
|
||||
}
|
||||
}
|
||||
// Home.
|
||||
[""] => {
|
||||
if let Err(error) = home::setup_page(is_user_logged) {
|
||||
log!(error);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -157,10 +157,12 @@ pub fn setup_page(recipe_id: i64) -> Result<(), JsValue> {
|
|||
// Tags.
|
||||
{
|
||||
spawn_local(async move {
|
||||
let tags: ron_api::Tags =
|
||||
request::get("recipe/get_tags", [("recipe_id", &recipe_id.to_string())])
|
||||
.await
|
||||
.unwrap();
|
||||
let tags: ron_api::Tags = request::get(
|
||||
"recipe/get_tags",
|
||||
ron_api::Id { id: recipe_id }, /*[("id", &recipe_id.to_string())]*/
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
create_tag_elements(recipe_id, &tags.tags);
|
||||
});
|
||||
|
||||
|
|
@ -279,7 +281,7 @@ pub fn setup_page(recipe_id: i64) -> Result<(), JsValue> {
|
|||
{
|
||||
spawn_local(async move {
|
||||
let groups: Vec<common::ron_api::Group> =
|
||||
request::get("recipe/get_groups", [("recipe_id", &recipe_id.to_string())])
|
||||
request::get("recipe/get_groups", ron_api::Id { id: recipe_id })
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
|
|
|
|||
150
frontend/src/recipe_scheduler.rs
Normal file
150
frontend/src/recipe_scheduler.rs
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
use chrono::{Datelike, Days, Months, NaiveDate};
|
||||
use common::ron_api;
|
||||
use gloo::storage::{LocalStorage, Storage};
|
||||
use ron::ser::{to_string_pretty, PrettyConfig};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{calendar, request};
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum Error {
|
||||
#[error("Request error: {0}")]
|
||||
Request(#[from] request::Error),
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RecipeScheduler {
|
||||
is_local: bool,
|
||||
}
|
||||
|
||||
pub enum ScheduleRecipeResult {
|
||||
Ok,
|
||||
RecipeAlreadyScheduledAtThisDate,
|
||||
}
|
||||
|
||||
impl From<ron_api::ScheduleRecipeResult> for ScheduleRecipeResult {
|
||||
fn from(api_res: ron_api::ScheduleRecipeResult) -> Self {
|
||||
match api_res {
|
||||
ron_api::ScheduleRecipeResult::Ok => Self::Ok,
|
||||
ron_api::ScheduleRecipeResult::RecipeAlreadyScheduledAtThisDate => {
|
||||
Self::RecipeAlreadyScheduledAtThisDate
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
struct ScheduledRecipesStore {
|
||||
recipe_id: i64,
|
||||
date: NaiveDate,
|
||||
}
|
||||
|
||||
fn build_key(year: i32, month: u32) -> String {
|
||||
format!("scheduled_recipes-{}-{}", year, month)
|
||||
}
|
||||
|
||||
fn load_scheduled_recipes(year: i32, month: u32) -> Vec<ScheduledRecipesStore> {
|
||||
LocalStorage::get::<Vec<ScheduledRecipesStore>>(build_key(year, month)).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn save_scheduled_recipes(scheduled_recipes: Vec<ScheduledRecipesStore>, year: i32, month: u32) {
|
||||
LocalStorage::set(build_key(year, month), scheduled_recipes).unwrap();
|
||||
}
|
||||
|
||||
impl RecipeScheduler {
|
||||
pub fn new(is_local: bool) -> Self {
|
||||
Self { is_local }
|
||||
}
|
||||
|
||||
pub async fn get_scheduled_recipes(
|
||||
&self,
|
||||
start_date: NaiveDate,
|
||||
end_date: NaiveDate,
|
||||
) -> Result<Vec<(NaiveDate, String, i64)>> {
|
||||
if self.is_local {
|
||||
let mut recipe_ids_and_dates = vec![];
|
||||
let mut current_date = start_date;
|
||||
while current_date <= end_date {
|
||||
current_date = current_date + Months::new(1);
|
||||
for recipe in load_scheduled_recipes(current_date.year(), current_date.month0()) {
|
||||
if recipe.date >= start_date && recipe.date <= end_date {
|
||||
recipe_ids_and_dates.push(recipe);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if recipe_ids_and_dates.is_empty() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
|
||||
let titles: ron_api::Strings = request::get(
|
||||
"recipe/get_titles",
|
||||
ron_api::Ids {
|
||||
ids: recipe_ids_and_dates
|
||||
.iter()
|
||||
.map(|r| r.recipe_id)
|
||||
.collect::<Vec<_>>(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(recipe_ids_and_dates
|
||||
.iter()
|
||||
.zip(titles.strs.into_iter())
|
||||
.map(|(id_and_date, title)| (id_and_date.date, title, id_and_date.recipe_id))
|
||||
.collect::<Vec<_>>())
|
||||
} else {
|
||||
let scheduled_recipes: ron_api::ScheduledRecipes = request::get(
|
||||
"calendar/get_scheduled_recipes",
|
||||
ron_api::DateRange {
|
||||
start_date,
|
||||
end_date,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(scheduled_recipes.recipes)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn shedule_recipe(
|
||||
&self,
|
||||
recipe_id: i64,
|
||||
date: NaiveDate,
|
||||
servings: u32,
|
||||
) -> Result<ScheduleRecipeResult> {
|
||||
if self.is_local {
|
||||
// storage.get(format("scheduled_recipes-{}-{}", )
|
||||
// storage.set("asd", "hello").unwrap();
|
||||
let mut recipe_ids_and_dates = load_scheduled_recipes(date.year(), date.month0());
|
||||
for recipe in recipe_ids_and_dates.iter() {
|
||||
if recipe.recipe_id == recipe_id && recipe.date == date {
|
||||
return Ok(ScheduleRecipeResult::RecipeAlreadyScheduledAtThisDate);
|
||||
}
|
||||
}
|
||||
recipe_ids_and_dates.push(ScheduledRecipesStore { recipe_id, date });
|
||||
save_scheduled_recipes(recipe_ids_and_dates, date.year(), date.month0());
|
||||
Ok(ScheduleRecipeResult::Ok)
|
||||
} else {
|
||||
request::post::<ron_api::ScheduleRecipeResult, _>(
|
||||
"calendar/schedule_recipe",
|
||||
ron_api::ScheduleRecipe {
|
||||
recipe_id,
|
||||
date,
|
||||
servings,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(Error::from)
|
||||
.map(From::<ron_api::ScheduleRecipeResult>::from)
|
||||
}
|
||||
}
|
||||
|
||||
// pub async fn remove_scheduled_recipe(
|
||||
// &self,
|
||||
// recipe_id: i64
|
||||
// )
|
||||
}
|
||||
|
|
@ -8,50 +8,56 @@ use wasm_bindgen_futures::spawn_local;
|
|||
use web_sys::{Element, HtmlInputElement};
|
||||
|
||||
use crate::{
|
||||
calendar, modal_dialog, request,
|
||||
calendar, modal_dialog,
|
||||
recipe_scheduler::{RecipeScheduler, ScheduleRecipeResult},
|
||||
toast::{self, Level},
|
||||
utils::{get_locale, selector, SelectorExt},
|
||||
};
|
||||
|
||||
pub fn setup_page(recipe_id: i64) -> Result<(), JsValue> {
|
||||
pub fn setup_page(recipe_id: i64, is_user_logged: bool) -> Result<(), JsValue> {
|
||||
let recipe_scheduler = RecipeScheduler::new(!is_user_logged);
|
||||
|
||||
let add_to_planner: Element = selector("#recipe-view .add-to-planner");
|
||||
|
||||
EventListener::new(&add_to_planner, "click", move |_event| {
|
||||
spawn_local(async move {
|
||||
if let Some((date, servings)) = modal_dialog::show_and_initialize_with_ok(
|
||||
"#hidden-templates .date-and-servings",
|
||||
async |element| calendar::setup(element.selector(".calendar")),
|
||||
async |element| {
|
||||
calendar::setup(
|
||||
element.selector(".calendar"),
|
||||
calendar::CalendarOptions {
|
||||
can_select_date: true,
|
||||
},
|
||||
recipe_scheduler,
|
||||
)
|
||||
},
|
||||
|element, calendar_state| {
|
||||
let servings_element: HtmlInputElement = element.selector("#input-servings");
|
||||
(
|
||||
calendar_state.get_selected_date().date_naive(),
|
||||
calendar_state.get_selected_date(),
|
||||
servings_element.value_as_number() as u32,
|
||||
)
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
if let Ok(result) = request::post::<ron_api::ScheduleRecipeResult, _>(
|
||||
"calendar/schedule_recipe",
|
||||
ron_api::ScheduleRecipe {
|
||||
recipe_id,
|
||||
date,
|
||||
servings,
|
||||
},
|
||||
)
|
||||
.await
|
||||
if let Ok(result) = recipe_scheduler
|
||||
.shedule_recipe(recipe_id, date, servings)
|
||||
.await
|
||||
{
|
||||
toast::show_element_and_initialize(
|
||||
match result {
|
||||
ron_api::ScheduleRecipeResult::Ok => Level::Success,
|
||||
ron_api::ScheduleRecipeResult::RecipeAlreadyScheduledAtThisDate => {
|
||||
ScheduleRecipeResult::Ok => Level::Success,
|
||||
ScheduleRecipeResult::RecipeAlreadyScheduledAtThisDate => {
|
||||
Level::Warning
|
||||
}
|
||||
},
|
||||
match result {
|
||||
ron_api::ScheduleRecipeResult::Ok => {
|
||||
ScheduleRecipeResult::Ok => {
|
||||
"#hidden-templates .calendar-add-to-planner-success"
|
||||
}
|
||||
ron_api::ScheduleRecipeResult::RecipeAlreadyScheduledAtThisDate => {
|
||||
ScheduleRecipeResult::RecipeAlreadyScheduledAtThisDate => {
|
||||
"#hidden-templates .calendar-add-to-planner-already-exists"
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,8 +1,5 @@
|
|||
use common::ron_api;
|
||||
use gloo::{
|
||||
console::log,
|
||||
net::http::{Request, RequestBuilder},
|
||||
};
|
||||
use gloo::net::http::{Request, RequestBuilder};
|
||||
use serde::{de::DeserializeOwned, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
|
|
@ -42,20 +39,18 @@ where
|
|||
send_req(request_builder.body(ron_api::to_string(body))?).await
|
||||
}
|
||||
|
||||
async fn req_with_params<'a, T, U, V>(
|
||||
async fn req_with_params<T, U>(
|
||||
api_name: &str,
|
||||
params: U,
|
||||
method_fn: fn(&str) -> RequestBuilder,
|
||||
) -> Result<T>
|
||||
where
|
||||
T: DeserializeOwned,
|
||||
U: IntoIterator<Item = (&'a str, V)>,
|
||||
V: AsRef<str>,
|
||||
U: Serialize,
|
||||
{
|
||||
let url = format!("/ron-api/{}", api_name);
|
||||
let request_builder = method_fn(&url)
|
||||
.header(CONTENT_TYPE, CONTENT_TYPE_RON)
|
||||
.query(params);
|
||||
let mut url = format!("/ron-api/{}?", api_name);
|
||||
serde_html_form::ser::push_to_string(&mut url, params).unwrap();
|
||||
let request_builder = method_fn(&url).header(CONTENT_TYPE, CONTENT_TYPE_RON);
|
||||
send_req(request_builder.build()?).await
|
||||
}
|
||||
|
||||
|
|
@ -111,28 +106,10 @@ where
|
|||
req_with_body(api_name, body, Request::delete).await
|
||||
}
|
||||
|
||||
pub async fn get<'a, T, U, V>(api_name: &str, params: U) -> Result<T>
|
||||
pub async fn get<T, U>(api_name: &str, params: U) -> Result<T>
|
||||
where
|
||||
T: DeserializeOwned,
|
||||
U: IntoIterator<Item = (&'a str, V)>,
|
||||
V: AsRef<str>,
|
||||
U: Serialize,
|
||||
{
|
||||
req_with_params(api_name, params, Request::get).await
|
||||
}
|
||||
|
||||
// pub async fn api_request_get<T>(api_name: &str, params: QueryParams) -> Result<T, String>
|
||||
// where
|
||||
// T: DeserializeOwned,
|
||||
// {
|
||||
// match Request::get(&format!("/ron-api/recipe/{}?{}", api_name, params))
|
||||
// .header("Content-Type", "application/ron")
|
||||
// .send()
|
||||
// .await
|
||||
// {
|
||||
// Err(error) => {
|
||||
// toast::show(Level::Info, &format!("Internal server error: {}", error));
|
||||
// Err(error.to_string())
|
||||
// }
|
||||
// Ok(response) => Ok(ron::de::from_bytes::<T>(&response.binary().await.unwrap()).unwrap()),
|
||||
// }
|
||||
// }
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue