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