forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.07.2 MiBe6d4742Tahinli55 minutes ago401 commits

composer.rs922 lines, 30.5 KiBHistoryRawDownload
1use super::parts::{Scale, Tone, icon_button};
2use super::style::{radius, size, space, stroke, text};
3use super::text;
4use super::widget::{compact_field, panel, spawn_done};
5use crate::gui::glyph::Fill as _;
6use common::model::Id;
7use std::time::{Duration, Instant};
8
9use crate::lang::w;
10use crate::net::Fail;
11use common::{
12 call::{CreateMessage, CreatePoll, Typing, UpdateMessage},
13 constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_POLL_OPTIONS, MINIMUM_POLL_OPTIONS},
14 error::Error,
15 model::Attachment,
16 time::now_ms,
17 validate::{validate_new_message, validate_poll},
18};
19use gpui_kit::{
20 Anchor, AnyElement, App, Context, Div, ElementId, Entity, FontWeight, InteractiveElement,
21 IntoElement, KeyBinding, MouseButton, ParentElement, StatefulInteractiveElement as _, Styled,
22 Window, actions,
23 assets::IconName,
24 component::{
25 WindowExt,
26 input::{InputEvent, InputState, TextareaState},
27 notification::Notification,
28 popover::Popover,
29 text::TextView,
30 },
31 div,
32 prelude::FluentBuilder as _,
33 px,
34};
35
36use super::{
37 Palette, Trigger, Yumush,
38 chat::{Chat, TYPING_SEND_INTERVAL},
39 clickable, hoverable, new_input, notify_error, parts,
40};
41
42actions!(composer, [Bold, Italic, Code, Strike]);
43
44const CONTEXT: &str = "MessageComposer";
45
46const MOD: &str = if cfg!(target_os = "macos") {
47 "Cmd"
48} else {
49 "Ctrl"
50};
51
52const FORMAT_ROWS: [(&str, &str); 6] = [
53 ("**bold**", "B"),
54 ("*italic*", "I"),
55 ("`code`", "E"),
56 ("~~strike~~", "Shift+X"),
57 ("> quote", ""),
58 ("- list", ""),
59];
60
61fn shortcut_label(keys: &str) -> String {
62 if keys.is_empty() {
63 String::new()
64 } else {
65 format!("{MOD}+{keys}")
66 }
67}
68
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum Composer {
71 Compose { reply: Option<Id> },
72 Edit { message_id: Id },
73 Select { ids: Vec<Id> },
74}
75
76const SLOW_TICK: Duration = Duration::from_secs(1);
77
78pub fn mode_bar(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> Option<AnyElement> {
79 if let Some(seconds) = chat.slow_seconds() {
80 return Some(slow_bar(seconds, palette).into_any_element());
81 }
82
83 match &chat.composer {
84 Composer::Compose {
85 reply: Some(message_id),
86 } => Some(reply_bar(chat, *message_id, entity, palette).into_any_element()),
87 Composer::Edit { .. } => Some(edit_bar(entity, palette).into_any_element()),
88 Composer::Compose { reply: None } | Composer::Select { .. } => None,
89 }
90}
91
92pub fn selection_bar(ids: &[Id], entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {
93 let count = ids.len();
94 let selected = ids.to_vec();
95 let forward_entity = entity.clone();
96
97 div()
98 .h(px(size::ROW))
99 .pl(px(space::LG))
100 .pr(px(space::XS))
101 .flex()
102 .items_center()
103 .gap(px(space::SM))
104 .rounded(px(radius::MD))
105 .border_1()
106 .border_color(palette.border)
107 .bg(palette.field)
108 .child(div().flex_1().child(w().composer.selected(count)))
109 .child(parts::button(
110 "forward_selected",
111 w().composer.forward,
112 parts::Press::Primary,
113 palette.tokens,
114 move |window, cx| {
115 let selected = selected.clone();
116 forward_entity.update(cx, |yumush, cx| yumush.open_forward(selected, window, cx));
117 },
118 ))
119 .child(cancel_button(entity, palette))
120}
121
122fn bar(palette: Palette) -> Div {
123 div()
124 .h(px(size::CONTROL_SM))
125 .mb(px(space::SM))
126 .pl(px(space::SM))
127 .flex()
128 .items_center()
129 .gap(px(space::SM))
130 .border_l(px(stroke::LINE))
131 .border_color(palette.border)
132 .text_size(text(text::CAPTION))
133 .text_color(palette.muted)
134}
135
136fn reply_bar(
137 chat: &Chat,
138 message_id: Id,
139 entity: &Entity<Yumush>,
140 palette: Palette,
141) -> impl IntoElement {
142 let message = chat
143 .messages
144 .iter()
145 .find(|message| message.id == message_id);
146 let author = message
147 .and_then(|message| chat.author(message.user_id))
148 .map_or(w().composer.unknown_author, |user| user.username.as_str())
149 .to_string();
150 let quote = message
151 .map(super::message_actions::message_text)
152 .unwrap_or_default();
153
154 let jump = entity.clone();
155
156 bar(palette)
157 .child(
158 div()
159 .id("reply_jump")
160 .flex_1()
161 .min_w_0()
162 .flex()
163 .items_center()
164 .gap(px(space::SM))
165 .cursor_pointer()
166 .on_click(move |_, window, cx| {
167 jump.update(cx, |yumush, cx| {
168 yumush.go_to_message(message_id, window, cx)
169 })
170 })
171 .child(w().composer.replying_to)
172 .child(
173 div()
174 .font_weight(FontWeight::SEMIBOLD)
175 .text_color(palette.text)
176 .child(author),
177 )
178 .child(div().flex_1().min_w_0().truncate().child(quote)),
179 )
180 .child(cancel_button(entity, palette))
181}
182
183fn slow_bar(seconds: u64, palette: Palette) -> impl IntoElement {
184 bar(palette)
185 .text_color(palette.danger)
186 .child(super::parts::small_icon(IconName::Hourglass))
187 .child(w().composer.slow_down(seconds))
188}
189
190fn edit_bar(entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {
191 bar(palette)
192 .child(super::parts::small_icon(IconName::Pencil))
193 .child(w().composer.editing)
194 .child(div().flex_1())
195 .child(cancel_button(entity, palette))
196}
197
198fn cancel_button(entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {
199 let entity = entity.clone();
200
201 icon_button(
202 "cancel_composer",
203 IconName::Close,
204 w().composer.cancel,
205 Tone::Idle,
206 Scale::Small,
207 palette.tokens,
208 move |window, cx| {
209 entity.update(cx, |yumush, cx| yumush.cancel_composer(window, cx));
210 },
211 )
212}
213
214impl Yumush {
215 pub(super) fn submit_composer(
216 &mut self,
217 input: &Entity<TextareaState>,
218 window: &mut Window,
219 cx: &mut Context<Self>,
220 ) {
221 if self.chat.media.uploading() {
222 return;
223 }
224 let body = input
225 .read(cx)
226 .text()
227 .to_string()
228 .trim_end()
229 .trim_start_matches(['\n', '\r'])
230 .to_string();
231
232 match self.chat.composer.clone() {
233 Composer::Compose { reply } => self.create_message(reply, body, input, window, cx),
234 Composer::Edit { message_id } => {
235 self.update_message(message_id, body, input, window, cx)
236 }
237 Composer::Select { .. } => {}
238 }
239 }
240
241 pub(super) fn send_typing(&mut self, cx: &mut Context<Self>) {
242 let Some(community_id) = self.chat.selected_community_id else {
243 return;
244 };
245 if self
246 .chat
247 .message_input
248 .read(cx)
249 .text()
250 .to_string()
251 .is_empty()
252 || self
253 .chat
254 .typing_sent
255 .get(&community_id)
256 .is_some_and(|at| at.elapsed() < TYPING_SEND_INTERVAL)
257 {
258 return;
259 }
260 self.chat.typing_sent.insert(community_id, Instant::now());
261 let network = self.network.clone();
262 cx.spawn(async move |_, _| {
263 let _ = network.call(Typing { community_id }).await;
264 })
265 .detach();
266 }
267
268 fn create_message(
269 &mut self,
270 reply: Option<Id>,
271 body: String,
272 input: &Entity<TextareaState>,
273 window: &mut Window,
274 cx: &mut Context<Self>,
275 ) {
276 let attachments: Vec<Id> = self
277 .chat
278 .media
279 .pending
280 .iter()
281 .map(|attachment| attachment.id)
282 .collect();
283
284 if self.chat.slow_seconds().is_some() {
285 return;
286 }
287 let maximum = self.max_message_length();
288 if let Err(error) = validate_new_message(&body, attachments.len(), maximum) {
289 window.push_notification(Notification::error(error.to_string()), cx);
290 return;
291 }
292 let Some(community_id) = self.chat.selected_community_id else {
293 window.push_notification(Notification::error(w().composer.no_community), cx);
294 return;
295 };
296 let network = self.network.clone();
297 let restore = input.clone();
298 let pending = self.chat.media.pending.clone();
299 let order = self.send_order.clone();
300 self.chat.drafts.remove(&community_id);
301
302 cx.spawn_in(window, async move |this, cx| {
303 let _turn = order.lock().await;
304 match network
305 .call(CreateMessage {
306 community_id,
307 body: body.clone(),
308 attachments,
309 reply_to: reply,
310 })
311 .await
312 {
313 Ok(_) => {}
314 Err(Fail::Server(Error::RateLimited {
315 retry_after_seconds,
316 })) => {
317 let _ = this.update_in(cx, |yumush, window, cx| {
318 yumush.restore_message(&restore, community_id, body, pending, window, cx);
319 yumush.slow_down(retry_after_seconds, window, cx)
320 });
321 }
322 Err(error) => {
323 let _ = this.update_in(cx, |yumush, window, cx| {
324 yumush.restore_message(&restore, community_id, body, pending, window, cx)
325 });
326 notify_error(&this, cx, error);
327 }
328 }
329 })
330 .detach();
331
332 input.update(cx, |state, cx| state.set_value("", window, cx));
333 self.chat.media.pending.clear();
334 self.chat.composer = Composer::Compose { reply: None };
335 }
336
337 fn restore_message(
338 &mut self,
339 input: &Entity<TextareaState>,
340 community_id: Id,
341 body: String,
342 pending: Vec<Attachment>,
343 window: &mut Window,
344 cx: &mut Context<Self>,
345 ) {
346 if self.chat.selected_community_id != Some(community_id) {
347 self.chat.drafts.insert(community_id, body);
348 return;
349 }
350 if input.read(cx).text().len() == 0 {
351 input.update(cx, |state, cx| state.fill(body, window, cx));
352 }
353 if self.chat.media.pending.is_empty() {
354 self.chat.media.pending = pending;
355 }
356 cx.notify();
357 }
358
359 fn slow_down(&mut self, seconds: u64, window: &mut Window, cx: &mut Context<Self>) {
360 self.chat.slowed_until = Some(now_ms() + seconds * 1000);
361
362 cx.spawn_in(window, async move |this, cx| {
363 loop {
364 cx.background_executor().timer(SLOW_TICK).await;
365 let slowed = this.update(cx, |yumush, cx| {
366 cx.notify();
367 yumush.chat.slow_seconds().is_some()
368 });
369 if !matches!(slowed, Ok(true)) {
370 break;
371 }
372 }
373 })
374 .detach();
375 }
376
377 fn update_message(
378 &mut self,
379 message_id: Id,
380 body: String,
381 input: &Entity<TextareaState>,
382 window: &mut Window,
383 cx: &mut Context<Self>,
384 ) {
385 if let Err(error) = validate_new_message(&body, 0, self.max_message_length()) {
386 window.push_notification(Notification::error(error.to_string()), cx);
387 return;
388 }
389 let network = self.network.clone();
390 let restore = input.clone();
391
392 cx.spawn_in(window, async move |this, cx| {
393 if let Err(error) = network
394 .call(UpdateMessage {
395 message_id,
396 body: body.clone(),
397 })
398 .await
399 {
400 let _ = this.update_in(cx, |yumush, window, cx| {
401 if restore.read(cx).text().len() == 0 {
402 restore.update(cx, |state, cx| state.fill(body, window, cx));
403 yumush.chat.composer = Composer::Edit { message_id };
404 cx.notify();
405 }
406 });
407 notify_error(&this, cx, error);
408 }
409 })
410 .detach();
411
412 input.update(cx, |state, cx| state.set_value("", window, cx));
413 self.chat.composer = Composer::Compose { reply: None };
414 cx.notify();
415 }
416
417 pub(super) fn save_draft(&mut self, cx: &mut Context<Self>) {
418 let Some(community_id) = self.chat.selected_community_id else {
419 return;
420 };
421 let text = self.chat.message_input.read(cx).text().to_string();
422 if text.is_empty() || !matches!(self.chat.composer, Composer::Compose { .. }) {
423 self.chat.drafts.remove(&community_id);
424 } else {
425 self.chat.drafts.insert(community_id, text);
426 }
427 }
428
429 pub(super) fn restore_draft(
430 &mut self,
431 community_id: Id,
432 window: &mut Window,
433 cx: &mut Context<Self>,
434 ) {
435 let text = self
436 .chat
437 .drafts
438 .get(&community_id)
439 .cloned()
440 .unwrap_or_default();
441 self.chat
442 .message_input
443 .update(cx, |input, cx| input.fill(text, window, cx));
444 }
445
446 pub(super) fn reply(&mut self, message_id: Id, window: &mut Window, cx: &mut Context<Self>) {
447 self.chat.composer = Composer::Compose {
448 reply: Some(message_id),
449 };
450 self.chat.focus(window, cx);
451 cx.notify();
452 }
453
454 pub(super) fn edit(&mut self, message_id: Id, window: &mut Window, cx: &mut Context<Self>) {
455 let Some(body) = self
456 .chat
457 .messages
458 .iter()
459 .find(|message| message.id == message_id)
460 .map(|message| message.body.clone())
461 else {
462 return;
463 };
464
465 self.chat
466 .message_input
467 .update(cx, |input, cx| input.fill(body, window, cx));
468 self.chat.composer = Composer::Edit { message_id };
469 self.chat.focus(window, cx);
470 cx.notify();
471 }
472
473 pub(super) fn start_select(
474 &mut self,
475 message_id: Id,
476 window: &mut Window,
477 cx: &mut Context<Self>,
478 ) {
479 self.chat.composer = Composer::Select {
480 ids: vec![message_id],
481 };
482 self.focus.focus(window, cx);
483 cx.notify();
484 }
485
486 pub(super) fn toggle_select(&mut self, message_id: Id, cx: &mut Context<Self>) {
487 let Composer::Select { ids } = &mut self.chat.composer else {
488 return;
489 };
490 if let Some(index) = ids.iter().position(|id| *id == message_id) {
491 ids.remove(index);
492 } else if ids.len() < MAXIMUM_FORWARD_MESSAGES {
493 ids.push(message_id);
494 }
495 cx.notify();
496 }
497
498 pub(super) fn cancel_composer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
499 match self.chat.composer.clone() {
500 Composer::Compose { reply: None } => return,
501 Composer::Compose { reply: Some(_) } | Composer::Select { .. } => {}
502 Composer::Edit { .. } => self
503 .chat
504 .message_input
505 .update(cx, |input, cx| input.set_value("", window, cx)),
506 }
507 self.chat.composer = Composer::Compose { reply: None };
508 self.chat.focus(window, cx);
509 cx.notify();
510 }
511}
512
513pub fn bind_keys(cx: &mut App) {
514 let scope = format!("{CONTEXT} > Input");
515 cx.bind_keys([
516 KeyBinding::new("ctrl-b", Bold, Some(scope.as_str())),
517 KeyBinding::new("ctrl-i", Italic, Some(scope.as_str())),
518 KeyBinding::new("ctrl-e", Code, Some(scope.as_str())),
519 KeyBinding::new("ctrl-shift-x", Strike, Some(scope.as_str())),
520 ]);
521}
522
523pub fn format_actions(input: &Entity<TextareaState>, row: Div) -> Div {
524 let (bold, italic, code, strike) = (input.clone(), input.clone(), input.clone(), input.clone());
525 row.key_context(CONTEXT)
526 .on_action(move |_: &Bold, window, cx| wrap(&bold, "**", window, cx))
527 .on_action(move |_: &Italic, window, cx| wrap(&italic, "*", window, cx))
528 .on_action(move |_: &Code, window, cx| wrap(&code, "`", window, cx))
529 .on_action(move |_: &Strike, window, cx| wrap(&strike, "~~", window, cx))
530}
531
532fn wrap(input: &Entity<TextareaState>, mark: &str, window: &mut Window, cx: &mut App) {
533 input.update(cx, |state, cx| {
534 let start = state.selected_range().start + mark.len();
535 let selected = state.selected_text().to_string();
536 state.replace(format!("{mark}{selected}{mark}"), window, cx);
537 state.set_selected_range(start..start + selected.len(), cx);
538 });
539}
540
541pub(super) fn trigger_icon(
542 id: impl Into<ElementId>,
543 icon: IconName,
544 size: f32,
545 palette: Palette,
546) -> Trigger {
547 Trigger::new(hoverable(
548 id,
549 div()
550 .size(px(size))
551 .flex()
552 .items_center()
553 .justify_center()
554 .rounded(px(radius::MD))
555 .text_color(palette.muted)
556 .child(super::parts::small_icon(icon)),
557 palette,
558 ))
559}
560
561fn format_panel(palette: Palette) -> impl IntoElement {
562 panel(palette)
563 .w(px(size::SHEET))
564 .p(px(space::SM))
565 .flex()
566 .flex_col()
567 .gap(px(space::SM))
568 .text_size(text(text::CAPTION))
569 .children(FORMAT_ROWS.map(|(syntax, shortcut)| {
570 div()
571 .flex()
572 .items_center()
573 .gap(px(space::MD))
574 .child(
575 div()
576 .w(px(size::THUMB))
577 .text_color(palette.muted)
578 .child(syntax),
579 )
580 .child(div().flex_1().child(TextView::markdown(syntax, syntax)))
581 .child(
582 div()
583 .text_color(palette.muted)
584 .child(shortcut_label(shortcut)),
585 )
586 }))
587}
588
589#[derive(Clone, Copy, PartialEq, Eq, Default)]
590pub(super) enum PlusMenu {
591 #[default]
592 Menu,
593 Poll,
594 Format,
595}
596
597fn plus_row(
598 id: &'static str,
599 icon: IconName,
600 label: &'static str,
601 palette: Palette,
602 on_click: impl Fn(&mut Window, &mut App) + 'static,
603) -> impl IntoElement {
604 clickable(id, palette, on_click)
605 .h(px(size::CONTROL))
606 .px(px(space::SM))
607 .gap(px(space::SM))
608 .rounded(px(radius::MD))
609 .flex()
610 .items_center()
611 .child(
612 div()
613 .text_color(palette.muted)
614 .child(super::parts::small_icon(icon)),
615 )
616 .child(label)
617}
618
619pub fn plus_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {
620 let question = chat.poll_question.clone();
621 let options = chat.poll_options.clone();
622 let multiple = chat.poll_multiple;
623 let public = chat.poll_public;
624 let duration = chat.poll_duration;
625 let reset = entity.clone();
626 let entity = entity.clone();
627
628 Popover::new("plus_popover")
629 .anchor(Anchor::BottomLeft)
630 .appearance(false)
631 .trigger(Trigger::new(
632 hoverable(
633 "plus_trigger",
634 div()
635 .size(px(size::CONTROL_SM))
636 .flex()
637 .items_center()
638 .justify_center()
639 .rounded(px(radius::MD))
640 .text_color(palette.muted)
641 .child(super::parts::small_icon(IconName::Plus)),
642 palette,
643 )
644 .on_mouse_down(MouseButton::Left, move |_, _, cx| {
645 reset.update(cx, |yumush, _| yumush.chat.plus_menu = PlusMenu::Menu)
646 }),
647 ))
648 .content(move |_, _, cx| {
649 let popover = cx.entity();
650 if entity.read(cx).chat.plus_menu == PlusMenu::Format {
651 return format_panel(palette).into_any_element();
652 }
653 if entity.read(cx).chat.plus_menu == PlusMenu::Menu {
654 let file = entity.clone();
655 let poll = entity.clone();
656 let format = entity.clone();
657 return panel(palette)
658 .w(px(size::SIDEBAR))
659 .p(px(space::XS))
660 .flex()
661 .flex_col()
662 .gap(px(space::XS))
663 .child(plus_row(
664 "plus_file",
665 IconName::File,
666 w().composer.file,
667 palette,
668 move |window, cx| {
669 popover.update(cx, |state, cx| state.dismiss(window, cx));
670 file.update(cx, |yumush, cx| yumush.attach_files(window, cx));
671 },
672 ))
673 .child(plus_row(
674 "plus_poll",
675 IconName::ChartBar,
676 w().composer.poll,
677 palette,
678 move |_, cx| {
679 poll.update(cx, |yumush, cx| {
680 yumush.chat.plus_menu = PlusMenu::Poll;
681 cx.notify();
682 })
683 },
684 ))
685 .child(plus_row(
686 "plus_format",
687 IconName::Type,
688 w().composer.format,
689 palette,
690 move |_, cx| {
691 format.update(cx, |yumush, cx| {
692 yumush.chat.plus_menu = PlusMenu::Format;
693 cx.notify();
694 })
695 },
696 ))
697 .into_any_element();
698 }
699 let toggle = entity.clone();
700 let toggle_public = entity.clone();
701 let duration_entity = entity.clone();
702 let submit = entity.clone();
703 panel(palette)
704 .w(px(size::POPOVER))
705 .p(px(space::SM))
706 .flex()
707 .flex_col()
708 .gap(px(space::SM))
709 .text_size(text(text::CAPTION))
710 .child(compact_field(palette, &question))
711 .children(options.iter().enumerate().map(|(index, option)| {
712 let remove = entity.clone();
713 let trailing_blank =
714 index + 1 == options.len() && option_text(option, cx).is_empty();
715 div()
716 .flex()
717 .items_center()
718 .gap(px(space::SM))
719 .child(
720 div()
721 .flex_1()
722 .min_w_0()
723 .child(compact_field(palette, option)),
724 )
725 .children(
726 (options.len() > MINIMUM_POLL_OPTIONS && !trailing_blank).then(|| {
727 icon_button(
728 format!("poll_remove_{index}"),
729 IconName::Close,
730 w().composer.remove_option,
731 Tone::Idle,
732 Scale::Small,
733 palette.tokens,
734 move |_, cx| {
735 remove.update(cx, |yumush, cx| {
736 yumush.remove_poll_option(index, cx)
737 });
738 },
739 )
740 }),
741 )
742 }))
743 .child(
744 div()
745 .flex()
746 .items_center()
747 .gap(px(space::XS))
748 .text_color(palette.muted)
749 .child(super::parts::small_icon(IconName::Timer))
750 .children(poll_durations().map(|(label, seconds)| {
751 let set = duration_entity.clone();
752 let active = duration == seconds;
753 clickable(label, palette, move |_, cx| {
754 set.update(cx, |yumush, cx| {
755 yumush.chat.poll_duration = seconds;
756 cx.notify();
757 })
758 })
759 .px(px(space::SM))
760 .py(px(space::XXS))
761 .rounded(px(radius::SM))
762 .text_color(if active {
763 palette.accent
764 } else {
765 palette.muted
766 })
767 .when(active, |this| this.bg(palette.tokens.press()))
768 .child(label)
769 })),
770 )
771 .child(
772 div().flex().items_center().justify_between().child(
773 div()
774 .flex()
775 .items_center()
776 .gap(px(space::MD))
777 .child(super::parts::labeled_toggle(
778 "poll_multiple",
779 w().composer.multiple_answers,
780 multiple,
781 palette.tokens,
782 move |_, cx| {
783 toggle.update(cx, |yumush, cx| {
784 yumush.chat.poll_multiple = !yumush.chat.poll_multiple;
785 cx.notify();
786 })
787 },
788 ))
789 .child(super::parts::labeled_toggle(
790 "poll_public",
791 w().composer.show_voters,
792 public,
793 palette.tokens,
794 move |_, cx| {
795 toggle_public
796 .update(cx, |yumush, cx| yumush.toggle_poll_public(cx))
797 },
798 )),
799 ),
800 )
801 .child(parts::button(
802 "poll_create",
803 w().composer.create,
804 parts::Press::Primary,
805 palette.tokens,
806 move |window, cx| {
807 if submit.update(cx, |yumush, cx| yumush.send_poll(window, cx)) {
808 popover.update(cx, |state, cx| state.dismiss(window, cx));
809 }
810 },
811 ))
812 .into_any_element()
813 })
814}
815
816fn poll_durations() -> [(&'static str, Option<u32>); 4] {
817 [
818 ("∞", None),
819 (w().composer.hour, Some(3600)),
820 (w().composer.day, Some(86400)),
821 (w().composer.week, Some(604800)),
822 ]
823}
824
825fn option_text(input: &Entity<InputState>, cx: &App) -> String {
826 input.read(cx).text().to_string().trim().to_owned()
827}
828
829pub(super) fn new_poll_option(window: &mut Window, cx: &mut Context<Yumush>) -> Entity<InputState> {
830 let input = new_input(w().composer.option, window, cx);
831 cx.subscribe_in(&input, window, |this, input, event, window, cx| {
832 if matches!(event, InputEvent::Change) {
833 this.grow_poll_options(input, window, cx);
834 }
835 })
836 .detach();
837 input
838}
839
840impl Yumush {
841 fn grow_poll_options(
842 &mut self,
843 input: &Entity<InputState>,
844 window: &mut Window,
845 cx: &mut Context<Self>,
846 ) {
847 let last = self.chat.poll_options.last() == Some(input);
848 if last && !option_text(input, cx).is_empty() {
849 self.add_poll_option(window, cx);
850 }
851 }
852
853 pub(super) fn add_poll_option(&mut self, window: &mut Window, cx: &mut Context<Self>) {
854 if self.chat.poll_options.len() < MAXIMUM_POLL_OPTIONS {
855 let input = new_poll_option(window, cx);
856 self.chat.poll_options.push(input);
857 cx.notify();
858 }
859 }
860
861 pub(super) fn remove_poll_option(&mut self, index: usize, cx: &mut Context<Self>) {
862 if self.chat.poll_options.len() > MINIMUM_POLL_OPTIONS
863 && index < self.chat.poll_options.len()
864 {
865 self.chat.poll_options.remove(index);
866 cx.notify();
867 }
868 }
869
870 pub(super) fn send_poll(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
871 let Some(community_id) = self.chat.selected_community_id else {
872 return false;
873 };
874 let question = self.chat.poll_question.read(cx).text().to_string();
875 let options: Vec<String> = self
876 .chat
877 .poll_options
878 .iter()
879 .map(|input| option_text(input, cx))
880 .filter(|text| !text.is_empty())
881 .collect();
882 if let Err(error) = validate_poll(&question, &options) {
883 window.push_notification(Notification::error(error.to_string()), cx);
884 return false;
885 }
886 let multiple = self.chat.poll_multiple;
887 let public = self.chat.poll_public;
888 let duration = self.chat.poll_duration;
889 let network = self.network.clone();
890
891 spawn_done(window, cx, async move {
892 network
893 .call(CreatePoll {
894 community_id,
895 question,
896 options,
897 multiple,
898 public,
899 duration,
900 })
901 .await
902 });
903
904 self.chat
905 .poll_question
906 .update(cx, |state, cx| state.set_value("", window, cx));
907 self.chat.poll_options.truncate(MINIMUM_POLL_OPTIONS);
908 for input in &self.chat.poll_options {
909 input.update(cx, |state, cx| state.set_value("", window, cx));
910 }
911 self.chat.poll_multiple = false;
912 self.chat.poll_public = true;
913 self.chat.poll_duration = None;
914 cx.notify();
915 true
916 }
917
918 pub(super) fn toggle_poll_public(&mut self, cx: &mut Context<Self>) {
919 self.chat.poll_public = !self.chat.poll_public;
920 cx.notify();
921 }
922}