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