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