use super::parts::{Scale, Tone, icon_button}; use super::style::{Tokens, radius, size, space, stroke, text}; use super::text; use super::widget::{compact_field, spawn_done}; use crate::gui::glyph::Fill as _; use common::model::Id; use std::time::{Duration, Instant}; use super::keys; use crate::lang::w; use crate::net::Fail; use common::{ call::{CreateMessage, CreatePoll, Typing, UpdateMessage}, constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_POLL_OPTIONS, MINIMUM_POLL_OPTIONS}, error::Error, model::Attachment, time::now_ms, validate::{validate_new_message, validate_poll}, }; use gpui_kit::{ Action, Anchor, AnyElement, App, Context, Div, ElementId, Entity, FontWeight, InteractiveElement, IntoElement, KeyBinding, MouseButton, ParentElement, StatefulInteractiveElement as _, Styled, Window, actions, assets::IconName, component::{ WindowExt, input::{InputEvent, InputState, TextareaState}, notification::Notification, popover::{Popover, PopoverState}, text::TextView, }, div, prelude::FluentBuilder as _, px, }; use super::{ Trigger, Yumush, chat::{Chat, TYPING_SEND_INTERVAL}, clickable, hoverable, new_input, notify_error, parts, }; actions!(composer, [Bold, Italic, Code, Strike]); const CONTEXT: &str = "MessageComposer"; const FORMAT_ROWS: [(&str, &str); 6] = [ ("**bold**", "B"), ("*italic*", "I"), ("`code`", "E"), ("~~strike~~", "Shift+X"), ("> quote", ""), ("- list", ""), ]; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Composer { Compose { reply: Option }, Edit { message_id: Id, stash: String }, Select { ids: Vec }, } const SLOW_TICK: Duration = Duration::from_secs(1); pub fn mode_bar(chat: &Chat, entity: &Entity, t: Tokens) -> Option { if let Some(seconds) = chat.slow_seconds() { return Some(slow_bar(seconds, t).into_any_element()); } match &chat.composer { Composer::Compose { reply: Some(message_id), } => Some(reply_bar(chat, *message_id, entity, t).into_any_element()), Composer::Edit { .. } => Some(edit_bar(entity, t).into_any_element()), Composer::Compose { reply: None } | Composer::Select { .. } => None, } } pub fn selection_bar(ids: &[Id], entity: &Entity, t: Tokens) -> impl IntoElement { let count = ids.len(); let selected = ids.to_vec(); let forward_entity = entity.clone(); div() .h(px(size::ROW)) .pl(px(space::LG)) .pr(px(space::XS)) .flex() .items_center() .gap(px(space::SM)) .rounded(px(radius::MD)) .border_1() .border_color(t.thread()) .bg(t.raise()) .child(div().flex_1().child(w().composer.selected(count))) .child(parts::button( "forward_selected", w().composer.forward, parts::Press::Primary, t, move |window, cx| { let selected = selected.clone(); forward_entity.update(cx, |yumush, cx| yumush.open_forward(selected, window, cx)); }, )) .child(cancel_button(entity, t)) } fn bar(t: Tokens) -> Div { div() .h(px(size::CONTROL_SM)) .mb(px(space::SM)) .pl(px(space::SM)) .flex() .items_center() .gap(px(space::SM)) .border_l(px(stroke::LINE)) .border_color(t.thread()) .text_size(text(text::CAPTION)) .text_color(t.dim()) } fn reply_bar(chat: &Chat, message_id: Id, entity: &Entity, t: Tokens) -> impl IntoElement { let message = chat .session .messages .iter() .find(|message| message.id == message_id); let author = message .and_then(|message| chat.author(message.user_id)) .map_or(w().composer.unknown_author, |user| user.username.as_str()) .to_string(); let quote = message .map(super::message_actions::message_text) .unwrap_or_default(); let jump = entity.clone(); bar(t) .child( div() .id("reply_jump") .flex_1() .min_w_0() .flex() .items_center() .gap(px(space::SM)) .cursor_pointer() .on_click(move |_, window, cx| { jump.update(cx, |yumush, cx| { yumush.go_to_message(message_id, window, cx) }) }) .child(w().composer.replying_to) .child( div() .font_weight(FontWeight::SEMIBOLD) .text_color(t.paper()) .child(author), ) .child(div().flex_1().min_w_0().truncate().child(quote)), ) .child(cancel_button(entity, t)) } fn slow_bar(seconds: u64, t: Tokens) -> impl IntoElement { bar(t) .text_color(t.bad()) .child(super::parts::small_icon(IconName::Hourglass)) .child(w().composer.slow_down(seconds)) } fn edit_bar(entity: &Entity, t: Tokens) -> impl IntoElement { bar(t) .child(super::parts::small_icon(IconName::Pencil)) .child(w().composer.editing) .child(div().flex_1()) .child(cancel_button(entity, t)) } fn cancel_button(entity: &Entity, t: Tokens) -> impl IntoElement { let entity = entity.clone(); icon_button( "cancel_composer", IconName::Close, w().composer.cancel, Tone::Idle, Scale::Small, t, move |window, cx| { entity.update(cx, |yumush, cx| yumush.cancel_composer(window, cx)); }, ) } impl Yumush { pub(super) fn submit_composer( &mut self, input: &Entity, window: &mut Window, cx: &mut Context, ) { if self.chat.session.media.uploading() { return; } let body = input .read(cx) .text() .to_string() .trim_end() .trim_start_matches(['\n', '\r']) .to_string(); match self.chat.composer.clone() { Composer::Compose { reply } => self.create_message(reply, body, input, window, cx), Composer::Edit { message_id, stash } => { self.update_message(message_id, body, stash, input, window, cx) } Composer::Select { .. } => {} } } pub(super) fn send_typing(&mut self, cx: &mut Context) { let Some(community_id) = self.chat.session.selected_community_id else { return; }; if self.chat.message_input.read(cx).text().len() == 0 || self .chat .session .typing_sent .get(&community_id) .is_some_and(|at| at.elapsed() < TYPING_SEND_INTERVAL) { return; } self.chat .session .typing_sent .insert(community_id, Instant::now()); let network = self.network.clone(); cx.spawn(async move |_, _| { let _ = network.call(Typing { community_id }).await; }) .detach(); } fn create_message( &mut self, reply: Option, body: String, input: &Entity, window: &mut Window, cx: &mut Context, ) { let attachments: Vec = self .chat .session .media .pending .iter() .map(|attachment| attachment.id) .collect(); if self.chat.slow_seconds().is_some() { return; } let maximum = self.max_message_length(); if let Err(error) = validate_new_message(&body, attachments.len(), maximum) { window.push_notification(Notification::error(error.to_string()), cx); return; } let Some(community_id) = self.chat.session.selected_community_id else { window.push_notification(Notification::error(w().composer.no_community), cx); return; }; let network = self.network.clone(); let restore = input.clone(); let pending = self.chat.session.media.pending.clone(); let order = self.send_order.clone(); self.chat.session.drafts.remove(&community_id); cx.spawn_in(window, async move |this, cx| { let _turn = order.lock().await; match network .call(CreateMessage { community_id, body: body.clone(), attachments, reply_to: reply, }) .await { Ok(_) => {} Err(Fail::Server(Error::RateLimited { retry_after_seconds, })) => { let _ = this.update_in(cx, |yumush, window, cx| { yumush.restore_message( &restore, community_id, body, pending, reply, window, cx, ); yumush.slow_down(retry_after_seconds, window, cx) }); } Err(error) => { let _ = this.update_in(cx, |yumush, window, cx| { yumush.restore_message( &restore, community_id, body, pending, reply, window, cx, ) }); notify_error(&this, cx, error); } } }) .detach(); input.update(cx, |state, cx| state.set_value("", window, cx)); self.chat.session.media.pending.clear(); self.chat.composer = Composer::Compose { reply: None }; } fn restore_message( &mut self, input: &Entity, community_id: Id, body: String, pending: Vec, reply: Option, window: &mut Window, cx: &mut Context, ) { if self.chat.session.selected_community_id != Some(community_id) { self.chat.session.drafts.insert(community_id, body); return; } if input.read(cx).text().len() == 0 { input.update(cx, |state, cx| state.fill(body, window, cx)); } if self.chat.session.media.pending.is_empty() { self.chat.session.media.pending = pending; } if self.chat.composer == (Composer::Compose { reply: None }) { self.chat.composer = Composer::Compose { reply }; } cx.notify(); } fn slow_down(&mut self, seconds: u64, window: &mut Window, cx: &mut Context) { self.chat.session.slowed_until = Some(now_ms() + seconds * 1000); cx.spawn_in(window, async move |this, cx| { loop { cx.background_executor().timer(SLOW_TICK).await; let slowed = this.update(cx, |yumush, cx| { cx.notify(); yumush.chat.slow_seconds().is_some() }); if !matches!(slowed, Ok(true)) { break; } } }) .detach(); } fn update_message( &mut self, message_id: Id, body: String, stash: String, input: &Entity, window: &mut Window, cx: &mut Context, ) { if let Err(error) = validate_new_message(&body, 0, self.max_message_length()) { window.push_notification(Notification::error(error.to_string()), cx); return; } let network = self.network.clone(); let restore = input.clone(); cx.spawn_in(window, async move |this, cx| { match network .call(UpdateMessage { message_id, body: body.clone(), }) .await { Ok(_) => { let _ = this.update_in(cx, |_, window, cx| { if restore.read(cx).text().len() == 0 { restore.update(cx, |state, cx| state.fill(stash, window, cx)); } }); } Err(error) => { let _ = this.update_in(cx, |yumush, window, cx| { if restore.read(cx).text().len() == 0 { restore.update(cx, |state, cx| state.fill(body, window, cx)); yumush.chat.composer = Composer::Edit { message_id, stash }; cx.notify(); } }); notify_error(&this, cx, error); } } }) .detach(); input.update(cx, |state, cx| state.set_value("", window, cx)); self.chat.composer = Composer::Compose { reply: None }; cx.notify(); } pub(super) fn save_draft(&mut self, cx: &mut Context) { let Some(community_id) = self.chat.session.selected_community_id else { return; }; let text = self.chat.message_input.read(cx).text().to_string(); if text.is_empty() || !matches!(self.chat.composer, Composer::Compose { .. }) { self.chat.session.drafts.remove(&community_id); } else { self.chat.session.drafts.insert(community_id, text); } } pub(super) fn restore_draft( &mut self, community_id: Id, window: &mut Window, cx: &mut Context, ) { let text = self .chat .session .drafts .get(&community_id) .cloned() .unwrap_or_default(); self.chat .message_input .update(cx, |input, cx| input.fill(text, window, cx)); } pub(super) fn reply(&mut self, message_id: Id, window: &mut Window, cx: &mut Context) { self.chat.composer = Composer::Compose { reply: Some(message_id), }; self.chat.focus(window, cx); cx.notify(); } pub(super) fn edit(&mut self, message_id: Id, window: &mut Window, cx: &mut Context) { let Some(body) = self .chat .session .messages .iter() .find(|message| message.id == message_id) .map(|message| message.body.clone()) else { return; }; let previous = std::mem::replace(&mut self.chat.composer, Composer::Compose { reply: None }); let stash = match previous { Composer::Edit { stash, .. } => stash, _ => self.chat.message_input.read(cx).text().to_string(), }; self.chat .message_input .update(cx, |input, cx| input.fill(body, window, cx)); self.chat.composer = Composer::Edit { message_id, stash }; self.chat.focus(window, cx); cx.notify(); } pub(super) fn start_select( &mut self, message_id: Id, window: &mut Window, cx: &mut Context, ) { self.chat.composer = Composer::Select { ids: vec![message_id], }; self.focus.focus(window, cx); cx.notify(); } pub(super) fn toggle_select(&mut self, message_id: Id, cx: &mut Context) { let Composer::Select { ids } = &mut self.chat.composer else { return; }; if let Some(index) = ids.iter().position(|id| *id == message_id) { ids.remove(index); } else if ids.len() < MAXIMUM_FORWARD_MESSAGES { ids.push(message_id); } if ids.is_empty() { self.chat.composer = Composer::Compose { reply: None }; } cx.notify(); } pub(super) fn cancel_composer(&mut self, window: &mut Window, cx: &mut Context) { match std::mem::replace(&mut self.chat.composer, Composer::Compose { reply: None }) { Composer::Compose { reply: None } => return, Composer::Compose { reply: Some(_) } | Composer::Select { .. } => {} Composer::Edit { stash, .. } => self .chat .message_input .update(cx, |input, cx| input.fill(stash, window, cx)), } self.chat.focus(window, cx); cx.notify(); } } pub fn bind_keys(cx: &mut App) { let scope = format!("{CONTEXT} > Input"); cx.bind_keys([ KeyBinding::new(keys::bind!("b"), Bold, Some(scope.as_str())), KeyBinding::new(keys::bind!("i"), Italic, Some(scope.as_str())), KeyBinding::new(keys::bind!("e"), Code, Some(scope.as_str())), KeyBinding::new(keys::bind!("shift-x"), Strike, Some(scope.as_str())), ]); } pub fn format_actions(input: &Entity, row: Div) -> Div { row.key_context(CONTEXT) .on_action(mark_action::(input, "**")) .on_action(mark_action::(input, "*")) .on_action(mark_action::(input, "`")) .on_action(mark_action::(input, "~~")) } fn mark_action( input: &Entity, mark: &'static str, ) -> impl Fn(&A, &mut Window, &mut App) + 'static { let input = input.clone(); move |_: &A, window, cx| wrap(&input, mark, window, cx) } fn wrap(input: &Entity, mark: &str, window: &mut Window, cx: &mut App) { input.update(cx, |state, cx| { let start = state.selected_range().start + mark.len(); let selected = state.selected_text().to_string(); state.replace(format!("{mark}{selected}{mark}"), window, cx); state.set_selected_range(start..start + selected.len(), cx); }); } pub(super) fn trigger_icon( id: impl Into, icon: IconName, size: f32, t: Tokens, ) -> Trigger { Trigger::new(hoverable( id, div() .size(px(size)) .flex() .items_center() .justify_center() .rounded(px(radius::MD)) .text_color(t.dim()) .child(super::parts::small_icon(icon)), t, )) } fn format_panel(t: Tokens) -> impl IntoElement { parts::surface(t) .w(px(size::SHEET)) .p(px(space::SM)) .flex() .flex_col() .gap(px(space::SM)) .text_size(text(text::CAPTION)) .children(FORMAT_ROWS.map(|(syntax, shortcut)| { div() .flex() .items_center() .gap(px(space::MD)) .child(div().w(px(size::THUMB)).text_color(t.dim()).child(syntax)) .child(div().flex_1().child(TextView::markdown(syntax, syntax))) .child(div().text_color(t.dim()).child(if shortcut.is_empty() { String::new() } else { keys::label(shortcut) })) })) } #[derive(Clone, Copy, PartialEq, Eq, Default)] pub(super) enum PlusMenu { #[default] Menu, Poll, Format, } fn plus_row( id: &'static str, icon: IconName, label: &'static str, t: Tokens, on_click: impl Fn(&mut Window, &mut App) + 'static, ) -> impl IntoElement { clickable(id, t, on_click) .h(px(size::CONTROL)) .px(px(space::SM)) .gap(px(space::SM)) .rounded(px(radius::MD)) .flex() .items_center() .child( div() .text_color(t.dim()) .child(super::parts::small_icon(icon)), ) .child(label) } pub fn plus_popover(entity: &Entity, t: Tokens) -> impl IntoElement { let reset = entity.clone(); let entity = entity.clone(); Popover::new("plus_popover") .anchor(Anchor::BottomLeft) .appearance(false) .trigger(Trigger::new( hoverable( "plus_trigger", div() .size(px(size::CONTROL_SM)) .flex() .items_center() .justify_center() .rounded(px(radius::MD)) .text_color(t.dim()) .child(super::parts::small_icon(IconName::Plus)), t, ) .on_mouse_down(MouseButton::Left, move |_, _, cx| { reset.update(cx, |yumush, _| yumush.chat.poll.plus_menu = PlusMenu::Menu) }), )) .content(move |_, _, cx| { let popover = cx.entity(); match entity.read(cx).chat.poll.plus_menu { PlusMenu::Format => format_panel(t).into_any_element(), PlusMenu::Menu => menu_panel(&entity, &popover, t).into_any_element(), PlusMenu::Poll => poll_panel(&entity, &popover, t, cx).into_any_element(), } }) } fn menu_panel( entity: &Entity, popover: &Entity, t: Tokens, ) -> impl IntoElement { let file = entity.clone(); let poll = entity.clone(); let format = entity.clone(); let dismiss = popover.clone(); parts::surface(t) .w(px(size::SIDEBAR)) .p(px(space::XS)) .flex() .flex_col() .gap(px(space::XS)) .child(plus_row( "plus_file", IconName::File, w().composer.file, t, move |window, cx| { dismiss.update(cx, |state, cx| state.dismiss(window, cx)); file.update(cx, |yumush, cx| yumush.attach_files(window, cx)); }, )) .child(plus_row( "plus_poll", IconName::ChartBar, w().composer.poll, t, move |_, cx| { poll.update(cx, |yumush, cx| { yumush.chat.poll.plus_menu = PlusMenu::Poll; cx.notify(); }) }, )) .child(plus_row( "plus_format", IconName::Type, w().composer.format, t, move |_, cx| { format.update(cx, |yumush, cx| { yumush.chat.poll.plus_menu = PlusMenu::Format; cx.notify(); }) }, )) } fn poll_panel( entity: &Entity, popover: &Entity, t: Tokens, cx: &App, ) -> impl IntoElement { let draft = &entity.read(cx).chat.poll; let duration = draft.duration; let toggle = entity.clone(); let toggle_public = entity.clone(); let duration_entity = entity.clone(); let submit = entity.clone(); let submit_popover = popover.clone(); let options = draft.options.len(); parts::surface(t) .w(px(size::POPOVER)) .p(px(space::SM)) .flex() .flex_col() .gap(px(space::SM)) .text_size(text(text::CAPTION)) .child(compact_field(t, &draft.question)) .children(draft.options.iter().enumerate().map(|(index, option)| { let remove = entity.clone(); let trailing_blank = index + 1 == options && option_text(option, cx).is_empty(); div() .flex() .items_center() .gap(px(space::SM)) .child(div().flex_1().min_w_0().child(compact_field(t, option))) .children( (options > MINIMUM_POLL_OPTIONS && !trailing_blank).then(|| { icon_button( format!("poll_remove_{index}"), IconName::Close, w().composer.remove_option, Tone::Idle, Scale::Small, t, move |window, cx| { remove.update(cx, |yumush, cx| { yumush.remove_poll_option(index, window, cx) }); }, ) }), ) })) .child( div() .flex() .items_center() .gap(px(space::XS)) .text_color(t.dim()) .child(super::parts::small_icon(IconName::Timer)) .children(poll_durations().map(|(label, seconds)| { let set = duration_entity.clone(); let active = duration == seconds; clickable(label, t, move |_, cx| { set.update(cx, |yumush, cx| { yumush.chat.poll.duration = seconds; cx.notify(); }) }) .px(px(space::SM)) .py(px(space::XXS)) .rounded(px(radius::SM)) .text_color(if active { t.paper() } else { t.dim() }) .when(active, |this| this.bg(t.press())) .child(label) })), ) .child( div().flex().items_center().justify_between().child( div() .flex() .items_center() .gap(px(space::MD)) .child(super::parts::labeled_toggle( "poll_multiple", w().composer.multiple_answers, draft.multiple, t, move |_, cx| { toggle.update(cx, |yumush, cx| { yumush.chat.poll.multiple = !yumush.chat.poll.multiple; cx.notify(); }) }, )) .child(super::parts::labeled_toggle( "poll_public", w().composer.show_voters, draft.public, t, move |_, cx| { toggle_public.update(cx, |yumush, cx| yumush.toggle_poll_public(cx)) }, )), ), ) .child(parts::button( "poll_create", w().composer.create, parts::Press::Primary, t, move |window, cx| { if submit.update(cx, |yumush, cx| yumush.send_poll(window, cx)) { submit_popover.update(cx, |state, cx| state.dismiss(window, cx)); } }, )) } fn poll_durations() -> [(&'static str, Option); 4] { [ ("∞", None), (w().composer.hour, Some(3600)), (w().composer.day, Some(86400)), (w().composer.week, Some(604800)), ] } fn option_text(input: &Entity, cx: &App) -> String { input.read(cx).text().to_string().trim().to_owned() } pub(super) fn new_poll_option(window: &mut Window, cx: &mut Context) -> Entity { let input = new_input(w().composer.option, window, cx); cx.subscribe_in(&input, window, |this, input, event, window, cx| { if matches!(event, InputEvent::Change) { this.grow_poll_options(input, window, cx); } }) .detach(); input } impl Yumush { fn grow_poll_options( &mut self, input: &Entity, window: &mut Window, cx: &mut Context, ) { let last = self.chat.poll.options.last() == Some(input); if last && !option_text(input, cx).is_empty() { self.add_poll_option(window, cx); } } fn add_poll_option(&mut self, window: &mut Window, cx: &mut Context) { if self.chat.poll.options.len() < MAXIMUM_POLL_OPTIONS { let input = new_poll_option(window, cx); self.chat.poll.options.push(input); cx.notify(); } } fn remove_poll_option(&mut self, index: usize, window: &mut Window, cx: &mut Context) { if self.chat.poll.options.len() > MINIMUM_POLL_OPTIONS && index < self.chat.poll.options.len() { self.chat.poll.options.remove(index); let last_filled = self .chat .poll .options .last() .is_some_and(|input| !option_text(input, cx).is_empty()); if last_filled { self.add_poll_option(window, cx); } cx.notify(); } } pub(super) fn send_poll(&mut self, window: &mut Window, cx: &mut Context) -> bool { let Some(community_id) = self.chat.session.selected_community_id else { return false; }; let question = self.chat.poll.question.read(cx).text().to_string(); let options: Vec = self .chat .poll .options .iter() .map(|input| option_text(input, cx)) .filter(|text| !text.is_empty()) .collect(); if let Err(error) = validate_poll(&question, &options) { window.push_notification(Notification::error(error.to_string()), cx); return false; } let multiple = self.chat.poll.multiple; let public = self.chat.poll.public; let duration = self.chat.poll.duration; let network = self.network.clone(); spawn_done(window, cx, async move { network .call(CreatePoll { community_id, question, options, multiple, public, duration, }) .await }); self.chat.poll.clear(window, cx); cx.notify(); true } pub(super) fn toggle_poll_public(&mut self, cx: &mut Context) { self.chat.poll.public = !self.chat.poll.public; cx.notify(); } }