use crate::lang::w; use common::call::{ClosePoll, MyVotes, Vote}; use common::model::Id; use common::model::{Message, Poll, Rank, User}; use common::time::{DAY_MILLIS, HOUR_MILLIS, MINUTE_MILLIS, now_ms}; use gpui_kit::{ Anchor, AnyElement, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement, Styled, Window, assets::IconName, component::popover::Popover, div, prelude::FluentBuilder as _, px, relative, }; use super::{ Tooltip as _, Trigger, Yumush, avatar, chat::Chat, clickable, hoverable, notify_error, parts::{Scale, Tone, icon_button, surface}, style::{Tokens, radius, size, space, text}, text, widget::spawn_done, }; fn my_positions(poll: &Poll, user_id: Id) -> Vec { poll.options .iter() .enumerate() .filter(|(_, option)| option.voter_ids.contains(&user_id)) .map(|(position, _)| position as u32) .collect() } fn next_votes(mine: &[u32], position: u32, multiple: bool) -> Vec { let mut next = mine.to_vec(); if mine.contains(&position) { next.retain(|vote| *vote != position); next } else if multiple { next.push(position); next } else { vec![position] } } fn percent(count: usize, voters: usize) -> usize { count * 100 / voters.max(1) } pub enum PollMode<'a> { Live(&'a Message), Snapshot(Id), } fn status_icon(id: String, icon: IconName, tip: &'static str, t: Tokens) -> impl IntoElement { div() .id(id) .tip(tip) .flex_shrink_0() .text_color(t.dim()) .child(super::parts::small_icon(icon)) } fn voters_label(voters: usize) -> Div { div() .flex() .items_center() .gap(px(space::XS)) .child(super::parts::small_icon(IconName::Users)) .child(format!("{voters}")) } fn voters_popover(key: &str, poll: &Poll, entity: &Entity, t: Tokens) -> AnyElement { let options = poll.options.clone(); let list = format!("poll_voters_list_{key}"); let open = entity.clone(); Popover::new(format!("poll_voters_{key}")) .anchor(Anchor::BottomLeft) .appearance(false) .trigger(Trigger::new(hoverable( format!("poll_voters_trigger_{key}"), voters_label(poll.voters as usize), t, ))) .content(move |_, _, cx| { let yumush = open.read(cx); let chat = &yumush.chat; let rows = options .iter() .filter(|option| !option.voter_ids.is_empty()) .map(|option| { div() .flex() .flex_col() .child( div() .h(px(size::CONTROL_SM)) .flex() .items_center() .gap(px(space::SM)) .text_size(text(text::CAPTION)) .text_color(t.dim()) .child(div().flex_1().min_w_0().child(super::glyph::line( option.text.clone().into(), super::text(super::style::text::UI), ))) .child( div() .flex_shrink_0() .child(format!("{}", option.voter_ids.len())), ), ) .children(option.voter_ids.iter().filter_map(|id| { chat.author(*id).map(|user| { div() .h(px(size::CONTROL_SM)) .flex() .items_center() .gap(px(space::SM)) .text_size(text(text::CAPTION)) .child(avatar( t, user, px(size::AVATAR), text(text::CAPTION), &chat.session.avatars, )) .child( div() .flex_1() .min_w_0() .truncate() .child(user.username.clone()), ) }) })) }); surface(t) .w(px(size::SIDEBAR)) .id(list.clone()) .max_h(px(size::POPOVER)) .overflow_y_scroll() .p(px(space::SM)) .flex() .flex_col() .children(rows) }) .into_any_element() } pub fn is_closed(poll: &Poll) -> bool { poll.closed || poll.ends_at.is_some_and(|end| end <= now_ms()) } fn remaining(end: u64) -> String { let left = end.saturating_sub(now_ms()); if left >= DAY_MILLIS { w().poll.days_left(left / DAY_MILLIS) } else if left >= HOUR_MILLIS { w().poll.hours_left(left / HOUR_MILLIS) } else { w().poll.minutes_left((left / MINUTE_MILLIS).max(1)) } } pub fn poll_card( poll: &Poll, mode: PollMode, me: Option<&User>, chat: &Chat, entity: &Entity, t: Tokens, ) -> impl IntoElement { let voters = poll.voters as usize; let closed = is_closed(poll); let (key, mine, vote_id, close_id) = match mode { PollMode::Live(message) => { let mine = match me { Some(me) if poll.public => my_positions(poll, me.id), _ => chat .session .my_votes .get(&message.id) .cloned() .unwrap_or_default(), }; let vote_id = (!closed && me.is_some()).then_some(message.id); let close_id = (!closed && me.is_some_and(|me| { me.id == message.user_id || chat.rank_of(me) >= Some(Rank::Moderator) })) .then_some(message.id); (message.id.to_string(), mine, vote_id, close_id) } PollMode::Snapshot(id) => (format!("snapshot_{id}"), Vec::new(), None, None), }; let rows = poll.options.iter().enumerate().map(|(position, option)| { let share = percent(option.votes as usize, voters); let picked = mine.contains(&(position as u32)); let next = next_votes(&mine, position as u32, poll.multiple); let voters_here: &[Id] = if poll.public { &option.voter_ids } else { &[] }; let entity = entity.clone(); let id = format!("poll_option_{key}_{position}"); match vote_id { Some(message_id) => clickable(id, t, move |window, cx| { let next = next.clone(); entity.update(cx, |yumush, cx| yumush.vote(message_id, next, window, cx)); }), None => div().id(id), } .relative() .h(px(size::CONTROL)) .px(px(space::MD)) .flex() .items_center() .gap(px(space::SM)) .rounded(px(radius::MD)) .border_1() .border_color(if picked { t.paper() } else { t.raise() }) .overflow_hidden() .bg(t.raise()) .child( div() .absolute() .left_0() .top_0() .h_full() .w(relative(share as f32 / 100.)) .bg(if picked { t.press() } else { t.hov() }), ) .child( div() .flex_shrink_0() .size(px(size::ICON_SM)) .flex() .items_center() .justify_center() .rounded_full() .border_1() .border_color(if picked { t.paper() } else { t.dim() }) .when(picked, |marker| { marker .bg(t.paper()) .text_color(t.ground()) .child(super::parts::small_icon(IconName::Check)) }), ) .child(div().flex_1().min_w_0().child(super::glyph::line( option.text.clone().into(), super::text(super::style::text::UI), ))) .children((!voters_here.is_empty()).then(|| { div() .flex() .items_center() .children( voters_here .iter() .take(3) .enumerate() .filter_map(|(index, id)| { chat.author(*id).map(|user| { avatar( t, user, px(size::AVATAR), text(text::CAPTION), &chat.session.avatars, ) .border_2() .border_color(t.ground()) .when(index > 0, |el| el.ml(px(-space::SM))) }) }), ) .children((voters_here.len() > 3).then(|| { div() .ml(px(space::XS)) .text_size(text(text::CAPTION)) .text_color(t.dim()) .child(format!("+{}", voters_here.len() - 3)) })) })) .child( div() .flex_shrink_0() .text_size(text(text::CAPTION)) .font_weight(FontWeight::SEMIBOLD) .text_color(if picked { t.paper() } else { t.dim() }) .child(format!("{share}%")), ) }); let voters_view = if poll.public { voters_popover(&key, poll, entity, t) } else { voters_label(voters).into_any_element() }; let timer = poll.ends_at.filter(|_| !closed).map(|end| { div() .flex() .items_center() .gap(px(space::XS)) .child(super::parts::small_icon(IconName::Timer)) .child(remaining(end)) }); let footer = div() .flex() .items_center() .justify_between() .text_size(text(text::CAPTION)) .text_color(t.dim()) .child(voters_view) .child( div() .flex() .items_center() .gap(px(space::SM)) .children(timer) .children(close_id.map(|close_id| { let close_entity = entity.clone(); icon_button( format!("poll_close_{close_id}"), IconName::CircleStop, w().poll.end_poll, Tone::Idle, Scale::Small, t, move |window, cx| { close_entity .update(cx, |yumush, cx| yumush.close_poll(close_id, window, cx)); }, ) })), ); let (visibility, visibility_tip) = if poll.public { (IconName::Eye, w().poll.voters_visible) } else { (IconName::EyeOff, w().poll.anonymous) }; div() .flex() .flex_col() .gap(px(space::SM)) .p(px(space::LG)) .w(px(size::SHEET)) .max_w_full() .rounded(px(radius::LG)) .bg(t.ground()) .child( div() .flex() .items_start() .justify_between() .gap(px(space::SM)) .child( div() .min_w_0() .font_weight(FontWeight::SEMIBOLD) .text_size(text(text::UI)) .child(super::glyph::wrapped( poll.question.clone().into(), super::text(super::style::text::UI), )), ) .child( div() .flex_shrink_0() .flex() .items_center() .gap(px(space::SM)) .child(status_icon( format!("poll_public_{key}_{}", poll.public), visibility, visibility_tip, t, )) .children(poll.multiple.then(|| { status_icon( format!("poll_multiple_{key}"), IconName::ListChecks, w().poll.multiple_choice, t, ) })) .children(closed.then(|| { status_icon( format!("poll_closed_{key}"), IconName::Lock, w().poll.closed, t, ) })), ), ) .children(rows) .child(footer) } impl Yumush { fn open_polls(&self) -> Vec<(&Message, &Poll)> { self.chat .session .pins .iter() .filter_map(|pin| { pin.poll .as_ref() .filter(|poll| !is_closed(poll)) .map(|poll| (pin, poll)) }) .collect() } pub(super) fn poll_banner(&self, entity: &Entity, t: Tokens) -> Option
{ let open = self.open_polls(); let count = open.len(); let page = self.chat.poll.page % count.max(1); let (message, poll) = *open.get(page)?; let me = self.user.as_ref(); let expanded = self.chat.poll.expanded; let toggle = entity.clone(); let jump = entity.clone(); let message_id = message.id; Some( div() .flex() .flex_col() .gap(px(space::SM)) .px(px(space::LG)) .py(px(space::SM)) .border_b_1() .border_color(t.thread()) .bg(t.ground()) .child( div() .flex() .items_center() .gap(px(space::SM)) .child( clickable("poll_banner_toggle", t, move |_, cx| { toggle.update(cx, |yumush, cx| { yumush.chat.poll.expanded = !yumush.chat.poll.expanded; cx.notify(); }) }) .flex() .flex_1() .min_w_0() .items_center() .gap(px(space::SM)) .text_size(text(text::CAPTION)) .child( div() .flex_shrink_0() .text_color(t.dim()) .child(super::parts::small_icon(IconName::ChartBar)), ) .child(div().min_w_0().font_weight(FontWeight::SEMIBOLD).child( super::glyph::line( poll.question.clone().into(), super::text(super::style::text::UI), ), )) .child( div() .flex_shrink_0() .text_color(t.dim()) .child(w().poll.votes(poll.voters as usize)), ) .child( div().flex_shrink_0().text_color(t.dim()).child( super::parts::small_icon(if expanded { IconName::ChevronUp } else { IconName::ChevronDown }), ), ), ) .children((count > 1).then(|| { div() .flex() .items_center() .gap(px(space::XXS)) .text_size(text(text::CAPTION)) .text_color(t.dim()) .child(page_button( "poll_page_back", IconName::ChevronLeft, w().poll.previous, -1, entity, t, )) .child(format!("{}/{count}", page + 1)) .child(page_button( "poll_page_next", IconName::ChevronRight, w().poll.next, 1, entity, t, )) })) .child(icon_button( "poll_banner_jump", IconName::ArrowUpRight, w().poll.jump_to_message, Tone::Idle, Scale::Small, t, move |window, cx| { jump.update(cx, |yumush, cx| { yumush.go_to_message(message_id, window, cx) }); }, )), ) .children( expanded.then(|| { poll_card(poll, PollMode::Live(message), me, &self.chat, entity, t) }), ), ) } pub(super) fn request_poll_votes(&mut self, cx: &mut Context) { let anonymous: Vec = self .chat .session .messages .iter() .chain(&self.chat.session.pins) .filter(|message| message.poll.as_ref().is_some_and(|poll| !poll.public)) .map(|message| message.id) .collect(); for message_id in anonymous { self.request_my_votes(message_id, cx); } } pub(super) fn request_my_votes(&mut self, message_id: Id, cx: &mut Context) { if self.chat.session.my_votes.contains_key(&message_id) { return; } self.chat.session.my_votes.insert(message_id, Vec::new()); let network = self.network.clone(); cx.spawn(async move |this, cx| { let positions = network.call(MyVotes { message_id }).await; let _ = this.update(cx, |yumush, cx| { match positions { Ok(positions) => { yumush.chat.session.my_votes.insert(message_id, positions); } Err(_) => { yumush.chat.session.my_votes.remove(&message_id); } } cx.notify(); }); }) .detach(); } pub(super) fn vote( &mut self, message_id: Id, positions: Vec, window: &mut Window, cx: &mut Context, ) { let previous = self .chat .session .my_votes .insert(message_id, positions.clone()); let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { if let Err(error) = network .call(Vote { message_id, positions, }) .await { let _ = this.update_in(cx, |yumush, _, cx| { match previous { Some(previous) => { yumush.chat.session.my_votes.insert(message_id, previous); } None => { yumush.chat.session.my_votes.remove(&message_id); } } cx.notify(); }); notify_error(&this, cx, error); } }) .detach(); } pub(super) fn close_poll( &mut self, message_id: Id, window: &mut Window, cx: &mut Context, ) { let network = self.network.clone(); spawn_done(window, cx, async move { network.call(ClosePoll { message_id }).await }); } } fn page_button( id: &'static str, icon: IconName, tip: &'static str, step: isize, entity: &Entity, t: Tokens, ) -> impl IntoElement { let entity = entity.clone(); icon_button(id, icon, tip, Tone::Idle, Scale::Small, t, move |_, cx| { entity.update(cx, |yumush, cx| { let count = yumush.open_polls().len().max(1) as isize; yumush.chat.poll.page = (yumush.chat.poll.page as isize + step).rem_euclid(count) as usize; cx.notify(); }); }) }