use crate::{ components::group_table::Group, infra::{api::HostService, modal::Modal}, }; use anyhow::{Error, Result}; use graphql_client::GraphQLQuery; use yew::prelude::*; use yew::services::fetch::FetchTask; use yewtil::NeqAssign; #[derive(GraphQLQuery)] #[graphql( schema_path = "../schema.graphql", query_path = "queries/delete_group.graphql", response_derives = "Debug", custom_scalars_module = "crate::infra::graphql" )] pub struct DeleteGroupQuery; pub struct DeleteGroup { link: ComponentLink, props: DeleteGroupProps, node_ref: NodeRef, modal: Option, task: Option, } #[derive(yew::Properties, Clone, PartialEq, Debug)] pub struct DeleteGroupProps { pub group: Group, pub on_group_deleted: Callback, pub on_error: Callback, } pub enum Msg { ClickedDeleteGroup, ConfirmDeleteGroup, DismissModal, DeleteGroupResponse(Result), } impl Component for DeleteGroup { type Message = Msg; type Properties = DeleteGroupProps; fn create(props: Self::Properties, link: ComponentLink) -> Self { Self { link, props, node_ref: NodeRef::default(), modal: None, task: None, } } fn rendered(&mut self, first_render: bool) { if first_render { self.modal = Some(Modal::new( self.node_ref .cast::() .expect("Modal node is not an element"), )); } } fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { Msg::ClickedDeleteGroup => { self.modal.as_ref().expect("modal not initialized").show(); } Msg::ConfirmDeleteGroup => { self.update(Msg::DismissModal); self.task = HostService::graphql_query::( delete_group_query::Variables { group_id: self.props.group.id, }, self.link.callback(Msg::DeleteGroupResponse), "Error trying to delete group", ) .map_err(|e| self.props.on_error.emit(e)) .ok(); } Msg::DismissModal => { self.modal.as_ref().expect("modal not initialized").hide(); } Msg::DeleteGroupResponse(response) => { self.task = None; if let Err(e) = response { self.props.on_error.emit(e); } else { self.props.on_group_deleted.emit(self.props.group.id); } } } true } fn change(&mut self, props: Self::Properties) -> ShouldRender { self.props.neq_assign(props) } fn view(&self) -> Html { html! { <> {self.show_modal()} } } } impl DeleteGroup { fn show_modal(&self) -> Html { html! { } } }