chat_panel.rs

  1use crate::{channel_view::ChannelView, ChatPanelSettings};
  2use anyhow::Result;
  3use call::ActiveCall;
  4use channel::{ChannelChat, ChannelChatEvent, ChannelMessageId, ChannelStore};
  5use client::Client;
  6use collections::HashMap;
  7use db::kvp::KEY_VALUE_STORE;
  8use editor::Editor;
  9use feature_flags::{ChannelsAlpha, FeatureFlagAppExt};
 10use gpui::{
 11    actions,
 12    elements::*,
 13    platform::{CursorStyle, MouseButton},
 14    serde_json,
 15    views::{ItemType, Select, SelectStyle},
 16    AnyViewHandle, AppContext, AsyncAppContext, Entity, ImageData, ModelHandle, Subscription, Task,
 17    View, ViewContext, ViewHandle, WeakViewHandle,
 18};
 19use language::{language_settings::SoftWrap, LanguageRegistry};
 20use menu::Confirm;
 21use project::Fs;
 22use rich_text::RichText;
 23use serde::{Deserialize, Serialize};
 24use settings::SettingsStore;
 25use std::sync::Arc;
 26use theme::{IconButton, Theme};
 27use time::{OffsetDateTime, UtcOffset};
 28use util::{ResultExt, TryFutureExt};
 29use workspace::{
 30    dock::{DockPosition, Panel},
 31    Workspace,
 32};
 33
 34const MESSAGE_LOADING_THRESHOLD: usize = 50;
 35const CHAT_PANEL_KEY: &'static str = "ChatPanel";
 36
 37pub struct ChatPanel {
 38    client: Arc<Client>,
 39    channel_store: ModelHandle<ChannelStore>,
 40    languages: Arc<LanguageRegistry>,
 41    active_chat: Option<(ModelHandle<ChannelChat>, Subscription)>,
 42    message_list: ListState<ChatPanel>,
 43    input_editor: ViewHandle<Editor>,
 44    channel_select: ViewHandle<Select>,
 45    local_timezone: UtcOffset,
 46    fs: Arc<dyn Fs>,
 47    width: Option<f32>,
 48    active: bool,
 49    pending_serialization: Task<Option<()>>,
 50    subscriptions: Vec<gpui::Subscription>,
 51    workspace: WeakViewHandle<Workspace>,
 52    has_focus: bool,
 53    markdown_data: HashMap<ChannelMessageId, RichText>,
 54}
 55
 56#[derive(Serialize, Deserialize)]
 57struct SerializedChatPanel {
 58    width: Option<f32>,
 59}
 60
 61#[derive(Debug)]
 62pub enum Event {
 63    DockPositionChanged,
 64    Focus,
 65    Dismissed,
 66}
 67
 68actions!(
 69    chat_panel,
 70    [LoadMoreMessages, ToggleFocus, OpenChannelNotes, JoinCall]
 71);
 72
 73pub fn init(cx: &mut AppContext) {
 74    cx.add_action(ChatPanel::send);
 75    cx.add_action(ChatPanel::load_more_messages);
 76    cx.add_action(ChatPanel::open_notes);
 77    cx.add_action(ChatPanel::join_call);
 78}
 79
 80impl ChatPanel {
 81    pub fn new(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> ViewHandle<Self> {
 82        let fs = workspace.app_state().fs.clone();
 83        let client = workspace.app_state().client.clone();
 84        let channel_store = ChannelStore::global(cx);
 85        let languages = workspace.app_state().languages.clone();
 86
 87        let input_editor = cx.add_view(|cx| {
 88            let mut editor = Editor::auto_height(
 89                4,
 90                Some(Arc::new(|theme| theme.chat_panel.input_editor.clone())),
 91                cx,
 92            );
 93            editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
 94            editor
 95        });
 96
 97        let workspace_handle = workspace.weak_handle();
 98
 99        let channel_select = cx.add_view(|cx| {
100            let channel_store = channel_store.clone();
101            let workspace = workspace_handle.clone();
102            Select::new(0, cx, {
103                move |ix, item_type, is_hovered, cx| {
104                    Self::render_channel_name(
105                        &channel_store,
106                        ix,
107                        item_type,
108                        is_hovered,
109                        workspace,
110                        cx,
111                    )
112                }
113            })
114            .with_style(move |cx| {
115                let style = &theme::current(cx).chat_panel.channel_select;
116                SelectStyle {
117                    header: Default::default(),
118                    menu: style.menu,
119                }
120            })
121        });
122
123        let mut message_list =
124            ListState::<Self>::new(0, Orientation::Bottom, 1000., move |this, ix, cx| {
125                this.render_message(ix, cx)
126            });
127        message_list.set_scroll_handler(|visible_range, this, cx| {
128            if visible_range.start < MESSAGE_LOADING_THRESHOLD {
129                this.load_more_messages(&LoadMoreMessages, cx);
130            }
131        });
132
133        cx.add_view(|cx| {
134            let mut this = Self {
135                fs,
136                client,
137                channel_store,
138                languages,
139
140                active_chat: Default::default(),
141                pending_serialization: Task::ready(None),
142                message_list,
143                input_editor,
144                channel_select,
145                local_timezone: cx.platform().local_timezone(),
146                has_focus: false,
147                subscriptions: Vec::new(),
148                workspace: workspace_handle,
149                active: false,
150                width: None,
151                markdown_data: Default::default(),
152            };
153
154            let mut old_dock_position = this.position(cx);
155            this.subscriptions
156                .push(
157                    cx.observe_global::<SettingsStore, _>(move |this: &mut Self, cx| {
158                        let new_dock_position = this.position(cx);
159                        if new_dock_position != old_dock_position {
160                            old_dock_position = new_dock_position;
161                            cx.emit(Event::DockPositionChanged);
162                        }
163                        cx.notify();
164                    }),
165                );
166
167            this.update_channel_count(cx);
168            cx.observe(&this.channel_store, |this, _, cx| {
169                this.update_channel_count(cx)
170            })
171            .detach();
172
173            cx.observe(&this.channel_select, |this, channel_select, cx| {
174                let selected_ix = channel_select.read(cx).selected_index();
175
176                let selected_channel_id = this
177                    .channel_store
178                    .read(cx)
179                    .channel_at(selected_ix)
180                    .map(|e| e.id);
181                if let Some(selected_channel_id) = selected_channel_id {
182                    this.select_channel(selected_channel_id, cx)
183                        .detach_and_log_err(cx);
184                }
185            })
186            .detach();
187
188            let markdown = this.languages.language_for_name("Markdown");
189            cx.spawn(|this, mut cx| async move {
190                let markdown = markdown.await?;
191
192                this.update(&mut cx, |this, cx| {
193                    this.input_editor.update(cx, |editor, cx| {
194                        editor.buffer().update(cx, |multi_buffer, cx| {
195                            multi_buffer
196                                .as_singleton()
197                                .unwrap()
198                                .update(cx, |buffer, cx| buffer.set_language(Some(markdown), cx))
199                        })
200                    })
201                })?;
202
203                anyhow::Ok(())
204            })
205            .detach_and_log_err(cx);
206
207            this
208        })
209    }
210
211    pub fn active_chat(&self) -> Option<ModelHandle<ChannelChat>> {
212        self.active_chat.as_ref().map(|(chat, _)| chat.clone())
213    }
214
215    pub fn load(
216        workspace: WeakViewHandle<Workspace>,
217        cx: AsyncAppContext,
218    ) -> Task<Result<ViewHandle<Self>>> {
219        cx.spawn(|mut cx| async move {
220            let serialized_panel = if let Some(panel) = cx
221                .background()
222                .spawn(async move { KEY_VALUE_STORE.read_kvp(CHAT_PANEL_KEY) })
223                .await
224                .log_err()
225                .flatten()
226            {
227                Some(serde_json::from_str::<SerializedChatPanel>(&panel)?)
228            } else {
229                None
230            };
231
232            workspace.update(&mut cx, |workspace, cx| {
233                let panel = Self::new(workspace, cx);
234                if let Some(serialized_panel) = serialized_panel {
235                    panel.update(cx, |panel, cx| {
236                        panel.width = serialized_panel.width;
237                        cx.notify();
238                    });
239                }
240                panel
241            })
242        })
243    }
244
245    fn serialize(&mut self, cx: &mut ViewContext<Self>) {
246        let width = self.width;
247        self.pending_serialization = cx.background().spawn(
248            async move {
249                KEY_VALUE_STORE
250                    .write_kvp(
251                        CHAT_PANEL_KEY.into(),
252                        serde_json::to_string(&SerializedChatPanel { width })?,
253                    )
254                    .await?;
255                anyhow::Ok(())
256            }
257            .log_err(),
258        );
259    }
260
261    fn update_channel_count(&mut self, cx: &mut ViewContext<Self>) {
262        let channel_count = self.channel_store.read(cx).channel_count();
263        self.channel_select.update(cx, |select, cx| {
264            select.set_item_count(channel_count, cx);
265        });
266    }
267
268    fn set_active_chat(&mut self, chat: ModelHandle<ChannelChat>, cx: &mut ViewContext<Self>) {
269        if self.active_chat.as_ref().map(|e| &e.0) != Some(&chat) {
270            let id = chat.read(cx).channel().id;
271            {
272                let chat = chat.read(cx);
273                self.message_list.reset(chat.message_count());
274                let placeholder = format!("Message #{}", chat.channel().name);
275                self.input_editor.update(cx, move |editor, cx| {
276                    editor.set_placeholder_text(placeholder, cx);
277                });
278            }
279            let subscription = cx.subscribe(&chat, Self::channel_did_change);
280            self.active_chat = Some((chat, subscription));
281            self.acknowledge_last_message(cx);
282            self.channel_select.update(cx, |select, cx| {
283                if let Some(ix) = self.channel_store.read(cx).index_of_channel(id) {
284                    select.set_selected_index(ix, cx);
285                }
286            });
287            cx.notify();
288        }
289    }
290
291    fn channel_did_change(
292        &mut self,
293        _: ModelHandle<ChannelChat>,
294        event: &ChannelChatEvent,
295        cx: &mut ViewContext<Self>,
296    ) {
297        match event {
298            ChannelChatEvent::MessagesUpdated {
299                old_range,
300                new_count,
301            } => {
302                self.message_list.splice(old_range.clone(), *new_count);
303                if self.active {
304                    self.acknowledge_last_message(cx);
305                }
306            }
307            ChannelChatEvent::NewMessage {
308                channel_id,
309                message_id,
310            } => {
311                if !self.active {
312                    self.channel_store.update(cx, |store, cx| {
313                        store.new_message(*channel_id, *message_id, cx)
314                    })
315                }
316            }
317        }
318        cx.notify();
319    }
320
321    fn acknowledge_last_message(&mut self, cx: &mut ViewContext<'_, '_, ChatPanel>) {
322        if self.active {
323            if let Some((chat, _)) = &self.active_chat {
324                chat.update(cx, |chat, cx| {
325                    chat.acknowledge_last_message(cx);
326                });
327            }
328        }
329    }
330
331    fn render_channel(&self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
332        let theme = theme::current(cx);
333        Flex::column()
334            .with_child(
335                ChildView::new(&self.channel_select, cx)
336                    .contained()
337                    .with_style(theme.chat_panel.channel_select.container),
338            )
339            .with_child(self.render_active_channel_messages(&theme))
340            .with_child(self.render_input_box(&theme, cx))
341            .into_any()
342    }
343
344    fn render_active_channel_messages(&self, theme: &Arc<Theme>) -> AnyElement<Self> {
345        let messages = if self.active_chat.is_some() {
346            List::new(self.message_list.clone())
347                .contained()
348                .with_style(theme.chat_panel.list)
349                .into_any()
350        } else {
351            Empty::new().into_any()
352        };
353
354        messages.flex(1., true).into_any()
355    }
356
357    fn render_message(&mut self, ix: usize, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
358        let (message, is_continuation, is_last) = {
359            let active_chat = self.active_chat.as_ref().unwrap().0.read(cx);
360            let last_message = active_chat.message(ix.saturating_sub(1));
361            let this_message = active_chat.message(ix);
362            let is_continuation = last_message.id != this_message.id
363                && this_message.sender.id == last_message.sender.id;
364
365            (
366                active_chat.message(ix).clone(),
367                is_continuation,
368                active_chat.message_count() == ix + 1,
369            )
370        };
371
372        let is_pending = message.is_pending();
373        let text = self
374            .markdown_data
375            .entry(message.id)
376            .or_insert_with(|| rich_text::render_markdown(message.body, &self.languages, None));
377
378        let now = OffsetDateTime::now_utc();
379        let theme = theme::current(cx);
380        let style = if is_pending {
381            &theme.chat_panel.pending_message
382        } else if is_continuation {
383            &theme.chat_panel.continuation_message
384        } else {
385            &theme.chat_panel.message
386        };
387
388        let belongs_to_user = Some(message.sender.id) == self.client.user_id();
389        let message_id_to_remove =
390            if let (ChannelMessageId::Saved(id), true) = (message.id, belongs_to_user) {
391                Some(id)
392            } else {
393                None
394            };
395
396        enum MessageBackgroundHighlight {}
397        MouseEventHandler::new::<MessageBackgroundHighlight, _>(ix, cx, |state, cx| {
398            let container = style.container.style_for(state);
399            if is_continuation {
400                Flex::row()
401                    .with_child(
402                        text.element(
403                            theme.editor.syntax.clone(),
404                            style.body.clone(),
405                            theme.editor.document_highlight_read_background,
406                            cx,
407                        )
408                        .flex(1., true),
409                    )
410                    .with_child(render_remove(message_id_to_remove, cx, &theme))
411                    .contained()
412                    .with_style(*container)
413                    .with_margin_bottom(if is_last {
414                        theme.chat_panel.last_message_bottom_spacing
415                    } else {
416                        0.
417                    })
418                    .into_any()
419            } else {
420                Flex::column()
421                    .with_child(
422                        Flex::row()
423                            .with_child(
424                                Flex::row()
425                                    .with_child(render_avatar(
426                                        message.sender.avatar.clone(),
427                                        &theme,
428                                    ))
429                                    .with_child(
430                                        Label::new(
431                                            message.sender.github_login.clone(),
432                                            style.sender.text.clone(),
433                                        )
434                                        .contained()
435                                        .with_style(style.sender.container),
436                                    )
437                                    .with_child(
438                                        Label::new(
439                                            format_timestamp(
440                                                message.timestamp,
441                                                now,
442                                                self.local_timezone,
443                                            ),
444                                            style.timestamp.text.clone(),
445                                        )
446                                        .contained()
447                                        .with_style(style.timestamp.container),
448                                    )
449                                    .align_children_center()
450                                    .flex(1., true),
451                            )
452                            .with_child(render_remove(message_id_to_remove, cx, &theme))
453                            .align_children_center(),
454                    )
455                    .with_child(
456                        Flex::row()
457                            .with_child(
458                                text.element(
459                                    theme.editor.syntax.clone(),
460                                    style.body.clone(),
461                                    theme.editor.document_highlight_read_background,
462                                    cx,
463                                )
464                                .flex(1., true),
465                            )
466                            // Add a spacer to make everything line up
467                            .with_child(render_remove(None, cx, &theme)),
468                    )
469                    .contained()
470                    .with_style(*container)
471                    .with_margin_bottom(if is_last {
472                        theme.chat_panel.last_message_bottom_spacing
473                    } else {
474                        0.
475                    })
476                    .into_any()
477            }
478        })
479        .into_any()
480    }
481
482    fn render_input_box(&self, theme: &Arc<Theme>, cx: &AppContext) -> AnyElement<Self> {
483        ChildView::new(&self.input_editor, cx)
484            .contained()
485            .with_style(theme.chat_panel.input_editor.container)
486            .into_any()
487    }
488
489    fn render_channel_name(
490        channel_store: &ModelHandle<ChannelStore>,
491        ix: usize,
492        item_type: ItemType,
493        is_hovered: bool,
494        workspace: WeakViewHandle<Workspace>,
495        cx: &mut ViewContext<Select>,
496    ) -> AnyElement<Select> {
497        let theme = theme::current(cx);
498        let tooltip_style = &theme.tooltip;
499        let theme = &theme.chat_panel;
500        let style = match (&item_type, is_hovered) {
501            (ItemType::Header, _) => &theme.channel_select.header,
502            (ItemType::Selected, _) => &theme.channel_select.active_item,
503            (ItemType::Unselected, false) => &theme.channel_select.item,
504            (ItemType::Unselected, true) => &theme.channel_select.hovered_item,
505        };
506
507        let channel = &channel_store.read(cx).channel_at(ix).unwrap();
508        let channel_id = channel.id;
509
510        let mut row = Flex::row()
511            .with_child(
512                Label::new("#".to_string(), style.hash.text.clone())
513                    .contained()
514                    .with_style(style.hash.container),
515            )
516            .with_child(Label::new(channel.name.clone(), style.name.clone()));
517
518        if matches!(item_type, ItemType::Header) {
519            row.add_children([
520                MouseEventHandler::new::<OpenChannelNotes, _>(0, cx, |mouse_state, _| {
521                    render_icon_button(theme.icon_button.style_for(mouse_state), "icons/file.svg")
522                })
523                .on_click(MouseButton::Left, move |_, _, cx| {
524                    if let Some(workspace) = workspace.upgrade(cx) {
525                        ChannelView::open(channel_id, workspace, cx).detach();
526                    }
527                })
528                .with_tooltip::<OpenChannelNotes>(
529                    channel_id as usize,
530                    "Open Notes",
531                    Some(Box::new(OpenChannelNotes)),
532                    tooltip_style.clone(),
533                    cx,
534                )
535                .flex_float(),
536                MouseEventHandler::new::<ActiveCall, _>(0, cx, |mouse_state, _| {
537                    render_icon_button(
538                        theme.icon_button.style_for(mouse_state),
539                        "icons/speaker-loud.svg",
540                    )
541                })
542                .on_click(MouseButton::Left, move |_, _, cx| {
543                    ActiveCall::global(cx)
544                        .update(cx, |call, cx| call.join_channel(channel_id, cx))
545                        .detach_and_log_err(cx);
546                })
547                .with_tooltip::<ActiveCall>(
548                    channel_id as usize,
549                    "Join Call",
550                    Some(Box::new(JoinCall)),
551                    tooltip_style.clone(),
552                    cx,
553                )
554                .flex_float(),
555            ]);
556        }
557
558        row.align_children_center()
559            .contained()
560            .with_style(style.container)
561            .into_any()
562    }
563
564    fn render_sign_in_prompt(
565        &self,
566        theme: &Arc<Theme>,
567        cx: &mut ViewContext<Self>,
568    ) -> AnyElement<Self> {
569        enum SignInPromptLabel {}
570
571        MouseEventHandler::new::<SignInPromptLabel, _>(0, cx, |mouse_state, _| {
572            Label::new(
573                "Sign in to use chat".to_string(),
574                theme
575                    .chat_panel
576                    .sign_in_prompt
577                    .style_for(mouse_state)
578                    .clone(),
579            )
580        })
581        .with_cursor_style(CursorStyle::PointingHand)
582        .on_click(MouseButton::Left, move |_, this, cx| {
583            let client = this.client.clone();
584            cx.spawn(|this, mut cx| async move {
585                if client
586                    .authenticate_and_connect(true, &cx)
587                    .log_err()
588                    .await
589                    .is_some()
590                {
591                    this.update(&mut cx, |this, cx| {
592                        if cx.handle().is_focused(cx) {
593                            cx.focus(&this.input_editor);
594                        }
595                    })
596                    .ok();
597                }
598            })
599            .detach();
600        })
601        .aligned()
602        .into_any()
603    }
604
605    fn send(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
606        if let Some((chat, _)) = self.active_chat.as_ref() {
607            let body = self.input_editor.update(cx, |editor, cx| {
608                let body = editor.text(cx);
609                editor.clear(cx);
610                body
611            });
612
613            if let Some(task) = chat
614                .update(cx, |chat, cx| chat.send_message(body, cx))
615                .log_err()
616            {
617                task.detach();
618            }
619        }
620    }
621
622    fn remove_message(&mut self, id: u64, cx: &mut ViewContext<Self>) {
623        if let Some((chat, _)) = self.active_chat.as_ref() {
624            chat.update(cx, |chat, cx| chat.remove_message(id, cx).detach())
625        }
626    }
627
628    fn load_more_messages(&mut self, _: &LoadMoreMessages, cx: &mut ViewContext<Self>) {
629        if let Some((chat, _)) = self.active_chat.as_ref() {
630            chat.update(cx, |channel, cx| {
631                channel.load_more_messages(cx);
632            })
633        }
634    }
635
636    pub fn select_channel(
637        &mut self,
638        selected_channel_id: u64,
639        cx: &mut ViewContext<ChatPanel>,
640    ) -> Task<Result<()>> {
641        if let Some((chat, _)) = &self.active_chat {
642            if chat.read(cx).channel().id == selected_channel_id {
643                return Task::ready(Ok(()));
644            }
645        }
646
647        let open_chat = self.channel_store.update(cx, |store, cx| {
648            store.open_channel_chat(selected_channel_id, cx)
649        });
650        cx.spawn(|this, mut cx| async move {
651            let chat = open_chat.await?;
652            this.update(&mut cx, |this, cx| {
653                this.markdown_data = Default::default();
654                this.set_active_chat(chat, cx);
655            })
656        })
657    }
658
659    fn open_notes(&mut self, _: &OpenChannelNotes, cx: &mut ViewContext<Self>) {
660        if let Some((chat, _)) = &self.active_chat {
661            let channel_id = chat.read(cx).channel().id;
662            if let Some(workspace) = self.workspace.upgrade(cx) {
663                ChannelView::open(channel_id, workspace, cx).detach();
664            }
665        }
666    }
667
668    fn join_call(&mut self, _: &JoinCall, cx: &mut ViewContext<Self>) {
669        if let Some((chat, _)) = &self.active_chat {
670            let channel_id = chat.read(cx).channel().id;
671            ActiveCall::global(cx)
672                .update(cx, |call, cx| call.join_channel(channel_id, cx))
673                .detach_and_log_err(cx);
674        }
675    }
676}
677
678fn render_avatar(avatar: Option<Arc<ImageData>>, theme: &Arc<Theme>) -> AnyElement<ChatPanel> {
679    let avatar_style = theme.chat_panel.avatar;
680
681    avatar
682        .map(|avatar| {
683            Image::from_data(avatar)
684                .with_style(avatar_style.image)
685                .aligned()
686                .contained()
687                .with_corner_radius(avatar_style.outer_corner_radius)
688                .constrained()
689                .with_width(avatar_style.outer_width)
690                .with_height(avatar_style.outer_width)
691                .into_any()
692        })
693        .unwrap_or_else(|| {
694            Empty::new()
695                .constrained()
696                .with_width(avatar_style.outer_width)
697                .into_any()
698        })
699        .contained()
700        .with_style(theme.chat_panel.avatar_container)
701        .into_any()
702}
703
704fn render_remove(
705    message_id_to_remove: Option<u64>,
706    cx: &mut ViewContext<'_, '_, ChatPanel>,
707    theme: &Arc<Theme>,
708) -> AnyElement<ChatPanel> {
709    enum DeleteMessage {}
710
711    message_id_to_remove
712        .map(|id| {
713            MouseEventHandler::new::<DeleteMessage, _>(id as usize, cx, |mouse_state, _| {
714                let button_style = theme.chat_panel.icon_button.style_for(mouse_state);
715                render_icon_button(button_style, "icons/x.svg")
716                    .aligned()
717                    .into_any()
718            })
719            .with_padding(Padding::uniform(2.))
720            .with_cursor_style(CursorStyle::PointingHand)
721            .on_click(MouseButton::Left, move |_, this, cx| {
722                this.remove_message(id, cx);
723            })
724            .flex_float()
725            .into_any()
726        })
727        .unwrap_or_else(|| {
728            let style = theme.chat_panel.icon_button.default;
729
730            Empty::new()
731                .constrained()
732                .with_width(style.icon_width)
733                .aligned()
734                .constrained()
735                .with_width(style.button_width)
736                .with_height(style.button_width)
737                .contained()
738                .with_uniform_padding(2.)
739                .flex_float()
740                .into_any()
741        })
742}
743
744impl Entity for ChatPanel {
745    type Event = Event;
746}
747
748impl View for ChatPanel {
749    fn ui_name() -> &'static str {
750        "ChatPanel"
751    }
752
753    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
754        let theme = theme::current(cx);
755        let element = if self.client.user_id().is_some() {
756            self.render_channel(cx)
757        } else {
758            self.render_sign_in_prompt(&theme, cx)
759        };
760        element
761            .contained()
762            .with_style(theme.chat_panel.container)
763            .constrained()
764            .with_min_width(150.)
765            .into_any()
766    }
767
768    fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
769        self.has_focus = true;
770        if matches!(
771            *self.client.status().borrow(),
772            client::Status::Connected { .. }
773        ) {
774            cx.focus(&self.input_editor);
775        }
776    }
777
778    fn focus_out(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {
779        self.has_focus = false;
780    }
781}
782
783impl Panel for ChatPanel {
784    fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
785        settings::get::<ChatPanelSettings>(cx).dock
786    }
787
788    fn position_is_valid(&self, position: DockPosition) -> bool {
789        matches!(position, DockPosition::Left | DockPosition::Right)
790    }
791
792    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
793        settings::update_settings_file::<ChatPanelSettings>(self.fs.clone(), cx, move |settings| {
794            settings.dock = Some(position)
795        });
796    }
797
798    fn size(&self, cx: &gpui::WindowContext) -> f32 {
799        self.width
800            .unwrap_or_else(|| settings::get::<ChatPanelSettings>(cx).default_width)
801    }
802
803    fn set_size(&mut self, size: Option<f32>, cx: &mut ViewContext<Self>) {
804        self.width = size;
805        self.serialize(cx);
806        cx.notify();
807    }
808
809    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
810        self.active = active;
811        if active {
812            self.acknowledge_last_message(cx);
813            if !is_chat_feature_enabled(cx) {
814                cx.emit(Event::Dismissed);
815            }
816        }
817    }
818
819    fn icon_path(&self, cx: &gpui::WindowContext) -> Option<&'static str> {
820        (settings::get::<ChatPanelSettings>(cx).button && is_chat_feature_enabled(cx))
821            .then(|| "icons/conversations.svg")
822    }
823
824    fn icon_tooltip(&self) -> (String, Option<Box<dyn gpui::Action>>) {
825        ("Chat Panel".to_string(), Some(Box::new(ToggleFocus)))
826    }
827
828    fn should_change_position_on_event(event: &Self::Event) -> bool {
829        matches!(event, Event::DockPositionChanged)
830    }
831
832    fn should_close_on_event(event: &Self::Event) -> bool {
833        matches!(event, Event::Dismissed)
834    }
835
836    fn has_focus(&self, _cx: &gpui::WindowContext) -> bool {
837        self.has_focus
838    }
839
840    fn is_focus_event(event: &Self::Event) -> bool {
841        matches!(event, Event::Focus)
842    }
843}
844
845fn is_chat_feature_enabled(cx: &gpui::WindowContext<'_>) -> bool {
846    cx.is_staff() || cx.has_flag::<ChannelsAlpha>()
847}
848
849fn format_timestamp(
850    mut timestamp: OffsetDateTime,
851    mut now: OffsetDateTime,
852    local_timezone: UtcOffset,
853) -> String {
854    timestamp = timestamp.to_offset(local_timezone);
855    now = now.to_offset(local_timezone);
856
857    let today = now.date();
858    let date = timestamp.date();
859    let mut hour = timestamp.hour();
860    let mut part = "am";
861    if hour > 12 {
862        hour -= 12;
863        part = "pm";
864    }
865    if date == today {
866        format!("{:02}:{:02}{}", hour, timestamp.minute(), part)
867    } else if date.next_day() == Some(today) {
868        format!("yesterday at {:02}:{:02}{}", hour, timestamp.minute(), part)
869    } else {
870        format!("{:02}/{}/{}", date.month() as u32, date.day(), date.year())
871    }
872}
873
874fn render_icon_button<V: View>(style: &IconButton, svg_path: &'static str) -> impl Element<V> {
875    Svg::new(svg_path)
876        .with_color(style.color)
877        .constrained()
878        .with_width(style.icon_width)
879        .aligned()
880        .constrained()
881        .with_width(style.button_width)
882        .with_height(style.button_width)
883        .contained()
884        .with_style(style.container)
885}