message_editor.rs

  1use anyhow::{Context as _, Result};
  2use channel::{ChannelChat, ChannelStore, MessageParams};
  3use client::{UserId, UserStore};
  4use collections::HashSet;
  5use editor::{AnchorRangeExt, CompletionProvider, Editor, EditorElement, EditorStyle, ExcerptId};
  6use fuzzy::{StringMatch, StringMatchCandidate};
  7use gpui::{
  8    AsyncApp, AsyncWindowContext, Context, Entity, Focusable, FontStyle, FontWeight,
  9    HighlightStyle, IntoElement, Render, Task, TextStyle, WeakEntity, Window,
 10};
 11use language::{
 12    Anchor, Buffer, BufferSnapshot, CodeLabel, LanguageRegistry, ToOffset,
 13    language_settings::SoftWrap,
 14};
 15use project::{Completion, CompletionResponse, CompletionSource, search::SearchQuery};
 16use settings::Settings;
 17use std::{
 18    cell::RefCell,
 19    ops::Range,
 20    rc::Rc,
 21    sync::{Arc, LazyLock},
 22    time::Duration,
 23};
 24use theme::ThemeSettings;
 25use ui::{TextSize, prelude::*};
 26
 27use crate::panel_settings::MessageEditorSettings;
 28
 29const MENTIONS_DEBOUNCE_INTERVAL: Duration = Duration::from_millis(50);
 30
 31static MENTIONS_SEARCH: LazyLock<SearchQuery> = LazyLock::new(|| {
 32    SearchQuery::regex(
 33        "@[-_\\w]+",
 34        false,
 35        false,
 36        false,
 37        false,
 38        Default::default(),
 39        Default::default(),
 40        false,
 41        None,
 42    )
 43    .unwrap()
 44});
 45
 46pub struct MessageEditor {
 47    pub editor: Entity<Editor>,
 48    user_store: Entity<UserStore>,
 49    channel_chat: Option<Entity<ChannelChat>>,
 50    mentions: Vec<UserId>,
 51    mentions_task: Option<Task<()>>,
 52    reply_to_message_id: Option<u64>,
 53    edit_message_id: Option<u64>,
 54}
 55
 56struct MessageEditorCompletionProvider(WeakEntity<MessageEditor>);
 57
 58impl CompletionProvider for MessageEditorCompletionProvider {
 59    fn completions(
 60        &self,
 61        _excerpt_id: ExcerptId,
 62        buffer: &Entity<Buffer>,
 63        buffer_position: language::Anchor,
 64        _: editor::CompletionContext,
 65        _window: &mut Window,
 66        cx: &mut Context<Editor>,
 67    ) -> Task<Result<Vec<CompletionResponse>>> {
 68        let Some(handle) = self.0.upgrade() else {
 69            return Task::ready(Ok(Vec::new()));
 70        };
 71        handle.update(cx, |message_editor, cx| {
 72            message_editor.completions(buffer, buffer_position, cx)
 73        })
 74    }
 75
 76    fn resolve_completions(
 77        &self,
 78        _buffer: Entity<Buffer>,
 79        _completion_indices: Vec<usize>,
 80        _completions: Rc<RefCell<Box<[Completion]>>>,
 81        _cx: &mut Context<Editor>,
 82    ) -> Task<anyhow::Result<bool>> {
 83        Task::ready(Ok(false))
 84    }
 85
 86    fn is_completion_trigger(
 87        &self,
 88        _buffer: &Entity<Buffer>,
 89        _position: language::Anchor,
 90        text: &str,
 91        _trigger_in_words: bool,
 92        _menu_is_open: bool,
 93        _cx: &mut Context<Editor>,
 94    ) -> bool {
 95        text == "@"
 96    }
 97}
 98
 99impl MessageEditor {
100    pub fn new(
101        language_registry: Arc<LanguageRegistry>,
102        user_store: Entity<UserStore>,
103        channel_chat: Option<Entity<ChannelChat>>,
104        editor: Entity<Editor>,
105        window: &mut Window,
106        cx: &mut Context<Self>,
107    ) -> Self {
108        let this = cx.entity().downgrade();
109        editor.update(cx, |editor, cx| {
110            editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
111            editor.set_offset_content(false, cx);
112            editor.set_use_autoclose(false);
113            editor.set_show_gutter(false, cx);
114            editor.set_show_wrap_guides(false, cx);
115            editor.set_show_indent_guides(false, cx);
116            editor.set_completion_provider(Some(Rc::new(MessageEditorCompletionProvider(this))));
117            editor.set_auto_replace_emoji_shortcode(
118                MessageEditorSettings::get_global(cx)
119                    .auto_replace_emoji_shortcode
120                    .unwrap_or_default(),
121            );
122        });
123
124        let buffer = editor
125            .read(cx)
126            .buffer()
127            .read(cx)
128            .as_singleton()
129            .expect("message editor must be singleton");
130
131        cx.subscribe_in(&buffer, window, Self::on_buffer_event)
132            .detach();
133        cx.observe_global::<settings::SettingsStore>(|this, cx| {
134            this.editor.update(cx, |editor, cx| {
135                editor.set_auto_replace_emoji_shortcode(
136                    MessageEditorSettings::get_global(cx)
137                        .auto_replace_emoji_shortcode
138                        .unwrap_or_default(),
139                )
140            })
141        })
142        .detach();
143
144        let markdown = language_registry.language_for_name("Markdown");
145        cx.spawn_in(window, async move |_, cx| {
146            let markdown = markdown.await.context("failed to load Markdown language")?;
147            buffer.update(cx, |buffer, cx| buffer.set_language(Some(markdown), cx))
148        })
149        .detach_and_log_err(cx);
150
151        Self {
152            editor,
153            user_store,
154            channel_chat,
155            mentions: Vec::new(),
156            mentions_task: None,
157            reply_to_message_id: None,
158            edit_message_id: None,
159        }
160    }
161
162    pub fn reply_to_message_id(&self) -> Option<u64> {
163        self.reply_to_message_id
164    }
165
166    pub fn set_reply_to_message_id(&mut self, reply_to_message_id: u64) {
167        self.reply_to_message_id = Some(reply_to_message_id);
168    }
169
170    pub fn clear_reply_to_message_id(&mut self) {
171        self.reply_to_message_id = None;
172    }
173
174    pub fn edit_message_id(&self) -> Option<u64> {
175        self.edit_message_id
176    }
177
178    pub fn set_edit_message_id(&mut self, edit_message_id: u64) {
179        self.edit_message_id = Some(edit_message_id);
180    }
181
182    pub fn clear_edit_message_id(&mut self) {
183        self.edit_message_id = None;
184    }
185
186    pub fn set_channel_chat(&mut self, chat: Entity<ChannelChat>, cx: &mut Context<Self>) {
187        let channel_id = chat.read(cx).channel_id;
188        self.channel_chat = Some(chat);
189        let channel_name = ChannelStore::global(cx)
190            .read(cx)
191            .channel_for_id(channel_id)
192            .map(|channel| channel.name.clone());
193        self.editor.update(cx, |editor, cx| {
194            if let Some(channel_name) = channel_name {
195                editor.set_placeholder_text(format!("Message #{channel_name}"), cx);
196            } else {
197                editor.set_placeholder_text("Message Channel", cx);
198            }
199        });
200    }
201
202    pub fn take_message(&mut self, window: &mut Window, cx: &mut Context<Self>) -> MessageParams {
203        self.editor.update(cx, |editor, cx| {
204            let highlights = editor.text_highlights::<Self>(cx);
205            let text = editor.text(cx);
206            let snapshot = editor.buffer().read(cx).snapshot(cx);
207            let mentions = if let Some((_, ranges)) = highlights {
208                ranges
209                    .iter()
210                    .map(|range| range.to_offset(&snapshot))
211                    .zip(self.mentions.iter().copied())
212                    .collect()
213            } else {
214                Vec::new()
215            };
216
217            editor.clear(window, cx);
218            self.mentions.clear();
219            let reply_to_message_id = std::mem::take(&mut self.reply_to_message_id);
220
221            MessageParams {
222                text,
223                mentions,
224                reply_to_message_id,
225            }
226        })
227    }
228
229    fn on_buffer_event(
230        &mut self,
231        buffer: &Entity<Buffer>,
232        event: &language::BufferEvent,
233        window: &mut Window,
234        cx: &mut Context<Self>,
235    ) {
236        if let language::BufferEvent::Reparsed | language::BufferEvent::Edited = event {
237            let buffer = buffer.read(cx).snapshot();
238            self.mentions_task = Some(cx.spawn_in(window, async move |this, cx| {
239                cx.background_executor()
240                    .timer(MENTIONS_DEBOUNCE_INTERVAL)
241                    .await;
242                Self::find_mentions(this, buffer, cx).await;
243            }));
244        }
245    }
246
247    fn completions(
248        &mut self,
249        buffer: &Entity<Buffer>,
250        end_anchor: Anchor,
251        cx: &mut Context<Self>,
252    ) -> Task<Result<Vec<CompletionResponse>>> {
253        if let Some((start_anchor, query, candidates)) =
254            self.collect_mention_candidates(buffer, end_anchor, cx)
255        {
256            if !candidates.is_empty() {
257                return cx.spawn(async move |_, cx| {
258                    let completion_response = Self::resolve_completions_for_candidates(
259                        &cx,
260                        query.as_str(),
261                        &candidates,
262                        start_anchor..end_anchor,
263                        Self::completion_for_mention,
264                    )
265                    .await;
266                    Ok(vec![completion_response])
267                });
268            }
269        }
270
271        if let Some((start_anchor, query, candidates)) =
272            self.collect_emoji_candidates(buffer, end_anchor, cx)
273        {
274            if !candidates.is_empty() {
275                return cx.spawn(async move |_, cx| {
276                    let completion_response = Self::resolve_completions_for_candidates(
277                        &cx,
278                        query.as_str(),
279                        candidates,
280                        start_anchor..end_anchor,
281                        Self::completion_for_emoji,
282                    )
283                    .await;
284                    Ok(vec![completion_response])
285                });
286            }
287        }
288
289        Task::ready(Ok(vec![CompletionResponse {
290            completions: Vec::new(),
291            is_incomplete: false,
292        }]))
293    }
294
295    async fn resolve_completions_for_candidates(
296        cx: &AsyncApp,
297        query: &str,
298        candidates: &[StringMatchCandidate],
299        range: Range<Anchor>,
300        completion_fn: impl Fn(&StringMatch) -> (String, CodeLabel),
301    ) -> CompletionResponse {
302        const LIMIT: usize = 10;
303        let matches = fuzzy::match_strings(
304            candidates,
305            query,
306            true,
307            LIMIT,
308            &Default::default(),
309            cx.background_executor().clone(),
310        )
311        .await;
312
313        let completions = matches
314            .into_iter()
315            .map(|mat| {
316                let (new_text, label) = completion_fn(&mat);
317                Completion {
318                    replace_range: range.clone(),
319                    new_text,
320                    label,
321                    icon_path: None,
322                    confirm: None,
323                    documentation: None,
324                    insert_text_mode: None,
325                    source: CompletionSource::Custom,
326                }
327            })
328            .collect::<Vec<_>>();
329
330        CompletionResponse {
331            is_incomplete: completions.len() >= LIMIT,
332            completions,
333        }
334    }
335
336    fn completion_for_mention(mat: &StringMatch) -> (String, CodeLabel) {
337        let label = CodeLabel {
338            filter_range: 1..mat.string.len() + 1,
339            text: format!("@{}", mat.string),
340            runs: Vec::new(),
341        };
342        (mat.string.clone(), label)
343    }
344
345    fn completion_for_emoji(mat: &StringMatch) -> (String, CodeLabel) {
346        let emoji = emojis::get_by_shortcode(&mat.string).unwrap();
347        let label = CodeLabel {
348            filter_range: 1..mat.string.len() + 1,
349            text: format!(":{}: {}", mat.string, emoji),
350            runs: Vec::new(),
351        };
352        (emoji.to_string(), label)
353    }
354
355    fn collect_mention_candidates(
356        &mut self,
357        buffer: &Entity<Buffer>,
358        end_anchor: Anchor,
359        cx: &mut Context<Self>,
360    ) -> Option<(Anchor, String, Vec<StringMatchCandidate>)> {
361        let end_offset = end_anchor.to_offset(buffer.read(cx));
362
363        let query = buffer.read_with(cx, |buffer, _| {
364            let mut query = String::new();
365            for ch in buffer.reversed_chars_at(end_offset).take(100) {
366                if ch == '@' {
367                    return Some(query.chars().rev().collect::<String>());
368                }
369                if ch.is_whitespace() || !ch.is_ascii() {
370                    break;
371                }
372                query.push(ch);
373            }
374            None
375        })?;
376
377        let start_offset = end_offset - query.len();
378        let start_anchor = buffer.read(cx).anchor_before(start_offset);
379
380        let mut names = HashSet::default();
381        if let Some(chat) = self.channel_chat.as_ref() {
382            let chat = chat.read(cx);
383            for participant in ChannelStore::global(cx)
384                .read(cx)
385                .channel_participants(chat.channel_id)
386            {
387                names.insert(participant.github_login.clone());
388            }
389            for message in chat
390                .messages_in_range(chat.message_count().saturating_sub(100)..chat.message_count())
391            {
392                names.insert(message.sender.github_login.clone());
393            }
394        }
395
396        let candidates = names
397            .into_iter()
398            .map(|user| StringMatchCandidate::new(0, &user))
399            .collect::<Vec<_>>();
400
401        Some((start_anchor, query, candidates))
402    }
403
404    fn collect_emoji_candidates(
405        &mut self,
406        buffer: &Entity<Buffer>,
407        end_anchor: Anchor,
408        cx: &mut Context<Self>,
409    ) -> Option<(Anchor, String, &'static [StringMatchCandidate])> {
410        static EMOJI_FUZZY_MATCH_CANDIDATES: LazyLock<Vec<StringMatchCandidate>> =
411            LazyLock::new(|| {
412                let emojis = emojis::iter()
413                    .flat_map(|s| s.shortcodes())
414                    .map(|emoji| StringMatchCandidate::new(0, emoji))
415                    .collect::<Vec<_>>();
416                emojis
417            });
418
419        let end_offset = end_anchor.to_offset(buffer.read(cx));
420
421        let query = buffer.read_with(cx, |buffer, _| {
422            let mut query = String::new();
423            for ch in buffer.reversed_chars_at(end_offset).take(100) {
424                if ch == ':' {
425                    let next_char = buffer
426                        .reversed_chars_at(end_offset - query.len() - 1)
427                        .next();
428                    // Ensure we are at the start of the message or that the previous character is a whitespace
429                    if next_char.is_none() || next_char.unwrap().is_whitespace() {
430                        return Some(query.chars().rev().collect::<String>());
431                    }
432
433                    // If the previous character is not a whitespace, we are in the middle of a word
434                    // and we only want to complete the shortcode if the word is made up of other emojis
435                    let mut containing_word = String::new();
436                    for ch in buffer
437                        .reversed_chars_at(end_offset - query.len() - 1)
438                        .take(100)
439                    {
440                        if ch.is_whitespace() {
441                            break;
442                        }
443                        containing_word.push(ch);
444                    }
445                    let containing_word = containing_word.chars().rev().collect::<String>();
446                    if util::word_consists_of_emojis(containing_word.as_str()) {
447                        return Some(query.chars().rev().collect::<String>());
448                    }
449                    break;
450                }
451                if ch.is_whitespace() || !ch.is_ascii() {
452                    break;
453                }
454                query.push(ch);
455            }
456            None
457        })?;
458
459        let start_offset = end_offset - query.len() - 1;
460        let start_anchor = buffer.read(cx).anchor_before(start_offset);
461
462        Some((start_anchor, query, &EMOJI_FUZZY_MATCH_CANDIDATES))
463    }
464
465    async fn find_mentions(
466        this: WeakEntity<MessageEditor>,
467        buffer: BufferSnapshot,
468        cx: &mut AsyncWindowContext,
469    ) {
470        let (buffer, ranges) = cx
471            .background_spawn(async move {
472                let ranges = MENTIONS_SEARCH.search(&buffer, None).await;
473                (buffer, ranges)
474            })
475            .await;
476
477        this.update(cx, |this, cx| {
478            let mut anchor_ranges = Vec::new();
479            let mut mentioned_user_ids = Vec::new();
480            let mut text = String::new();
481
482            this.editor.update(cx, |editor, cx| {
483                let multi_buffer = editor.buffer().read(cx).snapshot(cx);
484                for range in ranges {
485                    text.clear();
486                    text.extend(buffer.text_for_range(range.clone()));
487                    if let Some(username) = text.strip_prefix('@') {
488                        if let Some(user) = this
489                            .user_store
490                            .read(cx)
491                            .cached_user_by_github_login(username)
492                        {
493                            let start = multi_buffer.anchor_after(range.start);
494                            let end = multi_buffer.anchor_after(range.end);
495
496                            mentioned_user_ids.push(user.id);
497                            anchor_ranges.push(start..end);
498                        }
499                    }
500                }
501
502                editor.clear_highlights::<Self>(cx);
503                editor.highlight_text::<Self>(
504                    anchor_ranges,
505                    HighlightStyle {
506                        font_weight: Some(FontWeight::BOLD),
507                        ..Default::default()
508                    },
509                    cx,
510                )
511            });
512
513            this.mentions = mentioned_user_ids;
514            this.mentions_task.take();
515        })
516        .ok();
517    }
518
519    pub(crate) fn focus_handle(&self, cx: &gpui::App) -> gpui::FocusHandle {
520        self.editor.read(cx).focus_handle(cx)
521    }
522}
523
524impl Render for MessageEditor {
525    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
526        let settings = ThemeSettings::get_global(cx);
527        let text_style = TextStyle {
528            color: if self.editor.read(cx).read_only(cx) {
529                cx.theme().colors().text_disabled
530            } else {
531                cx.theme().colors().text
532            },
533            font_family: settings.ui_font.family.clone(),
534            font_features: settings.ui_font.features.clone(),
535            font_fallbacks: settings.ui_font.fallbacks.clone(),
536            font_size: TextSize::Small.rems(cx).into(),
537            font_weight: settings.ui_font.weight,
538            font_style: FontStyle::Normal,
539            line_height: relative(1.3),
540            ..Default::default()
541        };
542
543        div()
544            .w_full()
545            .px_2()
546            .py_1()
547            .bg(cx.theme().colors().editor_background)
548            .rounded_sm()
549            .child(EditorElement::new(
550                &self.editor,
551                EditorStyle {
552                    local_player: cx.theme().players().local(),
553                    text: text_style,
554                    ..Default::default()
555                },
556            ))
557    }
558}