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