forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

poll.rs649 lines, 22.0 KiBHistoryRawDownload
1use crate::lang::w;
2use common::call::{ClosePoll, MyVotes, Vote};
3use common::model::Id;
4use common::model::{Message, Poll, Rank, User};
5use common::time::{DAY_MILLIS, HOUR_MILLIS, MINUTE_MILLIS, now_ms};
6use gpui_kit::{
7 Anchor, AnyElement, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement,
8 ParentElement, StatefulInteractiveElement, Styled, Window, assets::IconName,
9 component::popover::Popover, div, prelude::FluentBuilder as _, px, relative,
10};
11
12use super::{
13 Palette, Tooltip as _, Trigger, Yumush, avatar,
14 chat::Chat,
15 clickable, hoverable,
16 parts::{Scale, Tone, icon_button},
17 style::{radius, size, space, text},
18 text,
19 widget::{panel, spawn_done},
20};
21
22pub fn voter_count(poll: &Poll) -> usize {
23 poll.voters as usize
24}
25
26fn my_positions(poll: &Poll, user_id: Id) -> Vec<u32> {
27 poll.options
28 .iter()
29 .enumerate()
30 .filter(|(_, option)| option.voter_ids.contains(&user_id))
31 .map(|(position, _)| position as u32)
32 .collect()
33}
34
35fn next_votes(mine: &[u32], position: u32, multiple: bool) -> Vec<u32> {
36 let mut next = mine.to_vec();
37 if mine.contains(&position) {
38 next.retain(|vote| *vote != position);
39 next
40 } else if multiple {
41 next.push(position);
42 next
43 } else {
44 vec![position]
45 }
46}
47
48fn percent(count: usize, voters: usize) -> usize {
49 count * 100 / voters.max(1)
50}
51
52pub enum PollMode<'a> {
53 Live(&'a Message),
54 Snapshot(Id),
55}
56
57fn status_icon(
58 id: String,
59 icon: IconName,
60 tip: &'static str,
61 palette: Palette,
62) -> impl IntoElement {
63 div()
64 .id(id)
65 .tip(tip)
66 .flex_shrink_0()
67 .text_color(palette.muted)
68 .child(super::parts::small_icon(icon))
69}
70
71fn voters_label(voters: usize) -> Div {
72 div()
73 .flex()
74 .items_center()
75 .gap(px(space::XS))
76 .child(super::parts::small_icon(IconName::Users))
77 .child(format!("{voters}"))
78}
79
80fn voters_popover(key: &str, poll: &Poll, entity: &Entity<Yumush>, palette: Palette) -> AnyElement {
81 let options = poll.options.clone();
82 let list = format!("poll_voters_list_{key}");
83 let open = entity.clone();
84 Popover::new(format!("poll_voters_{key}"))
85 .anchor(Anchor::BottomLeft)
86 .appearance(false)
87 .trigger(Trigger::new(hoverable(
88 format!("poll_voters_trigger_{key}"),
89 voters_label(voter_count(poll)),
90 palette,
91 )))
92 .content(move |_, _, cx| {
93 let yumush = open.read(cx);
94 let chat = &yumush.chat;
95 let rows = options
96 .iter()
97 .filter(|option| !option.voter_ids.is_empty())
98 .map(|option| {
99 div()
100 .flex()
101 .flex_col()
102 .child(
103 div()
104 .h(px(size::CONTROL_SM))
105 .flex()
106 .items_center()
107 .gap(px(space::SM))
108 .text_size(text(text::CAPTION))
109 .text_color(palette.muted)
110 .child(div().flex_1().min_w_0().child(super::glyph::line(
111 option.text.clone().into(),
112 super::text(super::style::text::UI),
113 )))
114 .child(
115 div()
116 .flex_shrink_0()
117 .child(format!("{}", option.voter_ids.len())),
118 ),
119 )
120 .children(option.voter_ids.iter().filter_map(|id| {
121 chat.author(*id).map(|user| {
122 div()
123 .h(px(size::CONTROL_SM))
124 .flex()
125 .items_center()
126 .gap(px(space::SM))
127 .text_size(text(text::CAPTION))
128 .child(avatar(
129 palette,
130 user,
131 px(size::AVATAR),
132 text(text::CAPTION),
133 &chat.avatars,
134 ))
135 .child(
136 div()
137 .flex_1()
138 .min_w_0()
139 .truncate()
140 .child(user.username.clone()),
141 )
142 })
143 }))
144 });
145 panel(palette)
146 .w(px(size::SIDEBAR))
147 .id(list.clone())
148 .max_h(px(size::POPOVER))
149 .overflow_y_scroll()
150 .p(px(space::SM))
151 .flex()
152 .flex_col()
153 .children(rows)
154 })
155 .into_any_element()
156}
157
158pub fn is_closed(poll: &Poll) -> bool {
159 poll.closed || poll.ends_at.is_some_and(|end| end <= now_ms())
160}
161
162fn remaining(end: u64) -> String {
163 let left = end.saturating_sub(now_ms());
164 if left >= DAY_MILLIS {
165 w().poll.days_left(left / DAY_MILLIS)
166 } else if left >= HOUR_MILLIS {
167 w().poll.hours_left(left / HOUR_MILLIS)
168 } else {
169 w().poll.minutes_left((left / MINUTE_MILLIS).max(1))
170 }
171}
172
173pub fn poll_card(
174 poll: &Poll,
175 mode: PollMode,
176 me: Option<&User>,
177 chat: &Chat,
178 entity: &Entity<Yumush>,
179 palette: Palette,
180) -> impl IntoElement {
181 let voters = voter_count(poll);
182 let closed = is_closed(poll);
183 let me_id = me.map(|me| me.id);
184 let (key, live) = match mode {
185 PollMode::Live(message) => (message.id.to_string(), Some(message)),
186 PollMode::Snapshot(id) => (format!("snapshot_{id}"), None),
187 };
188 let mine = match me_id {
189 Some(id) if poll.public => my_positions(poll, id),
190 _ => live
191 .and_then(|message| chat.my_votes.get(&message.id))
192 .cloned()
193 .unwrap_or_default(),
194 };
195 let vote_id = live
196 .filter(|_| !closed && me_id.is_some())
197 .map(|message| message.id);
198 let close_id = live
199 .filter(|message| {
200 !closed
201 && me.is_some_and(|me| {
202 me.id == message.user_id || chat.rank_of(me) >= Some(Rank::Moderator)
203 })
204 })
205 .map(|message| message.id);
206
207 let rows = poll.options.iter().enumerate().map(|(position, option)| {
208 let share = percent(option.votes as usize, voters);
209 let picked = mine.contains(&(position as u32));
210 let next = me_id
211 .map(|_| next_votes(&mine, position as u32, poll.multiple))
212 .unwrap_or_default();
213 let voters_here: &[Id] = if poll.public { &option.voter_ids } else { &[] };
214 let entity = entity.clone();
215 let id = format!("poll_option_{key}_{position}");
216 match vote_id {
217 Some(message_id) => clickable(id, palette, move |window, cx| {
218 let next = next.clone();
219 entity.update(cx, |yumush, cx| yumush.vote(message_id, next, window, cx));
220 }),
221 None => div().id(id),
222 }
223 .relative()
224 .h(px(size::CONTROL))
225 .px(px(space::MD))
226 .flex()
227 .items_center()
228 .gap(px(space::SM))
229 .rounded(px(radius::MD))
230 .border_1()
231 .border_color(if picked {
232 palette.accent
233 } else {
234 palette.field
235 })
236 .overflow_hidden()
237 .bg(palette.field)
238 .child(
239 div()
240 .absolute()
241 .left_0()
242 .top_0()
243 .h_full()
244 .w(relative(share as f32 / 100.))
245 .bg(if picked {
246 palette.tokens.press()
247 } else {
248 palette.hover
249 }),
250 )
251 .child(
252 div()
253 .flex_shrink_0()
254 .size(px(size::ICON_SM))
255 .flex()
256 .items_center()
257 .justify_center()
258 .rounded_full()
259 .border_1()
260 .border_color(if picked {
261 palette.accent
262 } else {
263 palette.muted
264 })
265 .when(picked, |marker| {
266 marker
267 .bg(palette.accent)
268 .text_color(palette.on_accent)
269 .child(super::parts::small_icon(IconName::Check))
270 }),
271 )
272 .child(div().flex_1().min_w_0().child(super::glyph::line(
273 option.text.clone().into(),
274 super::text(super::style::text::UI),
275 )))
276 .children((!voters_here.is_empty()).then(|| {
277 div()
278 .flex()
279 .items_center()
280 .children(
281 voters_here
282 .iter()
283 .take(3)
284 .enumerate()
285 .filter_map(|(index, id)| {
286 chat.author(*id).map(|user| {
287 avatar(
288 palette,
289 user,
290 px(size::AVATAR),
291 text(text::CAPTION),
292 &chat.avatars,
293 )
294 .border_2()
295 .border_color(palette.panel)
296 .when(index > 0, |el| el.ml(px(-space::SM)))
297 })
298 }),
299 )
300 .children((voters_here.len() > 3).then(|| {
301 div()
302 .ml(px(space::XS))
303 .text_size(text(text::CAPTION))
304 .text_color(palette.muted)
305 .child(format!("+{}", voters_here.len() - 3))
306 }))
307 }))
308 .child(
309 div()
310 .flex_shrink_0()
311 .text_size(text(text::CAPTION))
312 .font_weight(FontWeight::SEMIBOLD)
313 .text_color(if picked { palette.text } else { palette.muted })
314 .child(format!("{share}%")),
315 )
316 });
317
318 let voters_view = if poll.public {
319 voters_popover(&key, poll, entity, palette)
320 } else {
321 voters_label(voters).into_any_element()
322 };
323
324 let timer = poll.ends_at.filter(|_| !closed).map(|end| {
325 div()
326 .flex()
327 .items_center()
328 .gap(px(space::XS))
329 .child(super::parts::small_icon(IconName::Timer))
330 .child(remaining(end))
331 });
332
333 let footer = div()
334 .flex()
335 .items_center()
336 .justify_between()
337 .text_size(text(text::CAPTION))
338 .text_color(palette.muted)
339 .child(voters_view)
340 .child(
341 div()
342 .flex()
343 .items_center()
344 .gap(px(space::SM))
345 .children(timer)
346 .children(close_id.map(|close_id| {
347 let close_entity = entity.clone();
348 icon_button(
349 format!("poll_close_{close_id}"),
350 IconName::CircleStop,
351 w().poll.end_poll,
352 Tone::Idle,
353 Scale::Small,
354 palette.tokens,
355 move |window, cx| {
356 close_entity
357 .update(cx, |yumush, cx| yumush.close_poll(close_id, window, cx));
358 },
359 )
360 })),
361 );
362
363 let (visibility, visibility_tip) = if poll.public {
364 (IconName::Eye, w().poll.voters_visible)
365 } else {
366 (IconName::EyeOff, w().poll.anonymous)
367 };
368
369 div()
370 .flex()
371 .flex_col()
372 .gap(px(space::SM))
373 .p(px(space::LG))
374 .w(px(size::SHEET))
375 .max_w_full()
376 .rounded(px(radius::LG))
377 .bg(palette.panel)
378 .child(
379 div()
380 .flex()
381 .items_start()
382 .justify_between()
383 .gap(px(space::SM))
384 .child(
385 div()
386 .min_w_0()
387 .font_weight(FontWeight::SEMIBOLD)
388 .text_size(text(text::UI))
389 .child(super::glyph::wrapped(
390 poll.question.clone().into(),
391 super::text(super::style::text::UI),
392 )),
393 )
394 .child(
395 div()
396 .flex_shrink_0()
397 .flex()
398 .items_center()
399 .gap(px(space::SM))
400 .child(status_icon(
401 format!("poll_public_{key}_{}", poll.public),
402 visibility,
403 visibility_tip,
404 palette,
405 ))
406 .children(poll.multiple.then(|| {
407 status_icon(
408 format!("poll_multiple_{key}"),
409 IconName::ListChecks,
410 w().poll.multiple_choice,
411 palette,
412 )
413 }))
414 .children(closed.then(|| {
415 status_icon(
416 format!("poll_closed_{key}"),
417 IconName::Lock,
418 w().poll.closed,
419 palette,
420 )
421 })),
422 ),
423 )
424 .children(rows)
425 .child(footer)
426}
427
428impl Yumush {
429 pub(super) fn poll_banner(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> {
430 let open: Vec<(&Message, &Poll)> = self
431 .chat
432 .pins
433 .iter()
434 .filter_map(|pin| {
435 pin.poll
436 .as_ref()
437 .filter(|poll| !is_closed(poll))
438 .map(|poll| (pin, poll))
439 })
440 .collect();
441 let count = open.len();
442 let page = self.chat.poll_page % count.max(1);
443 let (message, poll) = *open.get(page)?;
444 let me = self.user.as_ref();
445 let expanded = self.chat.poll_expanded;
446 let toggle = entity.clone();
447 let jump = entity.clone();
448 let message_id = message.id;
449
450 Some(
451 div()
452 .flex()
453 .flex_col()
454 .gap(px(space::SM))
455 .px(px(space::LG))
456 .py(px(space::SM))
457 .border_b_1()
458 .border_color(palette.border)
459 .bg(palette.panel)
460 .child(
461 div()
462 .flex()
463 .items_center()
464 .gap(px(space::SM))
465 .child(
466 clickable("poll_banner_toggle", palette, move |_, cx| {
467 toggle.update(cx, |yumush, cx| {
468 yumush.chat.poll_expanded = !yumush.chat.poll_expanded;
469 cx.notify();
470 })
471 })
472 .flex()
473 .flex_1()
474 .min_w_0()
475 .items_center()
476 .gap(px(space::SM))
477 .text_size(text(text::CAPTION))
478 .child(
479 div()
480 .flex_shrink_0()
481 .text_color(palette.muted)
482 .child(super::parts::small_icon(IconName::ChartBar)),
483 )
484 .child(div().min_w_0().font_weight(FontWeight::SEMIBOLD).child(
485 super::glyph::line(
486 poll.question.clone().into(),
487 super::text(super::style::text::UI),
488 ),
489 ))
490 .child(
491 div()
492 .flex_shrink_0()
493 .text_color(palette.muted)
494 .child(w().poll.votes(voter_count(poll))),
495 )
496 .child(
497 div().flex_shrink_0().text_color(palette.muted).child(
498 super::parts::small_icon(if expanded {
499 IconName::ChevronUp
500 } else {
501 IconName::ChevronDown
502 }),
503 ),
504 ),
505 )
506 .children((count > 1).then(|| {
507 div()
508 .flex()
509 .items_center()
510 .gap(px(space::XXS))
511 .text_size(text(text::CAPTION))
512 .text_color(palette.muted)
513 .child(page_button(
514 "poll_page_back",
515 IconName::ChevronLeft,
516 w().poll.previous,
517 count - 1,
518 entity,
519 palette,
520 ))
521 .child(format!("{}/{count}", page + 1))
522 .child(page_button(
523 "poll_page_next",
524 IconName::ChevronRight,
525 w().poll.next,
526 1,
527 entity,
528 palette,
529 ))
530 }))
531 .child(icon_button(
532 "poll_banner_jump",
533 IconName::ArrowUpRight,
534 w().poll.jump_to_message,
535 Tone::Idle,
536 Scale::Small,
537 palette.tokens,
538 move |window, cx| {
539 jump.update(cx, |yumush, cx| {
540 yumush.go_to_message(message_id, window, cx)
541 });
542 },
543 )),
544 )
545 .children(expanded.then(|| {
546 poll_card(
547 poll,
548 PollMode::Live(message),
549 me,
550 &self.chat,
551 entity,
552 palette,
553 )
554 })),
555 )
556 }
557
558 pub(super) fn request_poll_votes(&mut self, cx: &mut Context<Self>) {
559 let anonymous: Vec<Id> = self
560 .chat
561 .messages
562 .iter()
563 .chain(&self.chat.pins)
564 .filter(|message| message.poll.as_ref().is_some_and(|poll| !poll.public))
565 .map(|message| message.id)
566 .collect();
567 for message_id in anonymous {
568 self.request_my_votes(message_id, cx);
569 }
570 }
571
572 pub(super) fn request_my_votes(&mut self, message_id: Id, cx: &mut Context<Self>) {
573 if self.chat.my_votes.contains_key(&message_id) {
574 return;
575 }
576 self.chat.my_votes.insert(message_id, Vec::new());
577
578 let network = self.network.clone();
579
580 cx.spawn(async move |this, cx| {
581 let Ok(positions) = network.call(MyVotes { message_id }).await else {
582 return;
583 };
584 let _ = this.update(cx, |yumush, cx| {
585 yumush.chat.my_votes.insert(message_id, positions);
586 cx.notify();
587 });
588 })
589 .detach();
590 }
591
592 pub(super) fn vote(
593 &mut self,
594 message_id: Id,
595 positions: Vec<u32>,
596 window: &mut Window,
597 cx: &mut Context<Self>,
598 ) {
599 self.chat.my_votes.insert(message_id, positions.clone());
600 let network = self.network.clone();
601
602 spawn_done(window, cx, async move {
603 network
604 .call(Vote {
605 message_id,
606 positions,
607 })
608 .await
609 });
610 }
611
612 pub(super) fn close_poll(
613 &mut self,
614 message_id: Id,
615 window: &mut Window,
616 cx: &mut Context<Self>,
617 ) {
618 let network = self.network.clone();
619
620 spawn_done(window, cx, async move {
621 network.call(ClosePoll { message_id }).await
622 });
623 }
624}
625
626fn page_button(
627 id: &'static str,
628 icon: IconName,
629 tip: &'static str,
630 step: usize,
631 entity: &Entity<Yumush>,
632 palette: Palette,
633) -> impl IntoElement {
634 let entity = entity.clone();
635 icon_button(
636 id,
637 icon,
638 tip,
639 Tone::Idle,
640 Scale::Small,
641 palette.tokens,
642 move |_, cx| {
643 entity.update(cx, |yumush, cx| {
644 yumush.chat.poll_page = yumush.chat.poll_page.wrapping_add(step);
645 cx.notify();
646 });
647 },
648 )
649}