use crate::{ components::{ delete_group::DeleteGroup, router::{AppRoute, Link}, }, infra::common_component::{CommonComponent, CommonComponentParts}, }; use anyhow::{Error, Result}; use graphql_client::GraphQLQuery; use yew::prelude::*; #[derive(GraphQLQuery)] #[graphql( schema_path = "../schema.graphql", query_path = "queries/get_group_list.graphql", response_derives = "Debug,Clone,PartialEq,Eq", custom_scalars_module = "crate::infra::graphql" )] pub struct GetGroupList; use get_group_list::ResponseData; pub type Group = get_group_list::GetGroupListGroups; pub struct GroupTable { common: CommonComponentParts, groups: Option>, } pub enum Msg { ListGroupsResponse(Result), OnGroupDeleted(i64), OnError(Error), } impl CommonComponent for GroupTable { fn handle_msg(&mut self, _: &Context, msg: ::Message) -> Result { match msg { Msg::ListGroupsResponse(groups) => { self.groups = Some(groups?.groups.into_iter().collect()); Ok(true) } Msg::OnError(e) => Err(e), Msg::OnGroupDeleted(group_id) => { debug_assert!(self.groups.is_some()); self.groups.as_mut().unwrap().retain(|u| u.id != group_id); Ok(true) } } } fn mut_common(&mut self) -> &mut CommonComponentParts { &mut self.common } } impl Component for GroupTable { type Message = Msg; type Properties = (); fn create(ctx: &Context) -> Self { let mut table = GroupTable { common: CommonComponentParts::::create(), groups: None, }; table.common.call_graphql::( ctx, get_group_list::Variables {}, Msg::ListGroupsResponse, "Error trying to fetch groups", ); table } fn update(&mut self, ctx: &Context, msg: Self::Message) -> bool { CommonComponentParts::::update(self, ctx, msg) } fn view(&self, ctx: &Context) -> Html { html! {
{self.view_groups(ctx)} {self.view_errors()}
} } } impl GroupTable { fn view_groups(&self, ctx: &Context) -> Html { let make_table = |groups: &Vec| { html! {
{groups.iter().map(|u| self.view_group(ctx, u)).collect::>()}
{"Group name"} {"Creation date"} {"Delete"}
} }; match &self.groups { None => html! {{"Loading..."}}, Some(groups) => make_table(groups), } } fn view_group(&self, ctx: &Context, group: &Group) -> Html { let link = ctx.link(); html! { {&group.display_name} {&group.creation_date.naive_local().date()} } } fn view_errors(&self) -> Html { match &self.common.error { None => html! {}, Some(e) => html! {
{"Error: "}{e.to_string()}
}, } } }