use chrono::Weekday; use common::utils::substitute_with_names; use gloo::events::EventListener; use wasm_bindgen_futures::spawn_local; use web_sys::{Element, HtmlInputElement}; use crate::{ calendar, modal_dialog, recipe_scheduler::{RecipeScheduler, ScheduleRecipeResult}, toast::{self, Level}, utils::{SelectorExt, get_locale, selector}, }; pub fn setup_page(recipe_id: i64, is_user_logged: bool, first_day_of_the_week: Weekday) { 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, add_ingredients_to_shopping_list)) = modal_dialog::show_and_initialize_with_ok( "#hidden-templates .date-and-servings", async |element| { calendar::setup( element.selector(".calendar"), calendar::CalendarOptions { can_select_date: true, with_link_and_remove: false, first_day_of_the_week, }, recipe_scheduler, ) }, |element, calendar_state| { let servings_element: HtmlInputElement = element.selector("#input-servings"); let add_ingredients_element: HtmlInputElement = element.selector("#input-add-ingredients-to-shopping-list"); ( calendar_state.get_selected_date(), servings_element.value_as_number() as u32, add_ingredients_element.checked(), ) }, ) .await { if let Ok(result) = recipe_scheduler .shedule_recipe(recipe_id, date, servings, add_ingredients_to_shopping_list) .await { toast::show_element_level_and_initialize( match result { ScheduleRecipeResult::Ok => Level::Success, ScheduleRecipeResult::RecipeAlreadyScheduledAtThisDate => { Level::Warning } }, match result { ScheduleRecipeResult::Ok => { "#hidden-templates .calendar-add-to-planner-success" } ScheduleRecipeResult::RecipeAlreadyScheduledAtThisDate => { "#hidden-templates .calendar-add-to-planner-already-exists" } }, |element| { let title = selector::("#recipe-view .recipe-title").inner_html(); let date_format = selector::("#hidden-templates .calendar-date-format") .inner_html(); element.set_inner_html(&substitute_with_names( &element.inner_html(), &["{title}", "{date}"], &[ &title, &date .format_localized(&date_format, get_locale()) .to_string(), ], )); }, ); } } }); }) .forget(); }