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", 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, 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(props: Self::Properties, link: ComponentLink) -> Self { let mut table = GroupTable { common: CommonComponentParts::::create(props, link), groups: None, }; table.common.call_graphql::( get_group_list::Variables {}, Msg::ListGroupsResponse, "Error trying to fetch groups", ); table } fn update(&mut self, msg: Self::Message) -> ShouldRender { CommonComponentParts::::update(self, msg) } fn change(&mut self, _: Self::Properties) -> ShouldRender { false } fn view(&self) -> Html { html! {
{self.view_groups()} {self.view_errors()}
} } } impl GroupTable { fn view_groups(&self) -> Html { let make_table = |groups: &Vec| { html! {
{groups.iter().map(|u| self.view_group(u)).collect::>()}
{"Groups"} {"Delete"}
} }; match &self.groups { None => html! {{"Loading..."}}, Some(groups) => make_table(groups), } } fn view_group(&self, group: &Group) -> Html { html! { {&group.display_name} } } fn view_errors(&self) -> Html { match &self.common.error { None => html! {}, Some(e) => html! {
{"Error: "}{e.to_string()}
}, } } }