message_editor.rs

  1use anyhow::{Context, Result};
  2use channel::{ChannelChat, ChannelStore, MessageParams};
  3use client::{UserId, UserStore};
  4use collections::HashSet;
  5use editor::{AnchorRangeExt, CompletionProvider, Editor, EditorElement, EditorStyle};
  6use fuzzy::{StringMatch, StringMatchCandidate};
  7use gpui::{
  8    AsyncWindowContext, FocusableView, FontStyle, FontWeight, HighlightStyle, IntoElement, Model,
  9    Render, Task, TextStyle, View, ViewContext, WeakView,
 10};
 11use language::{
 12    language_settings::SoftWrap, Anchor, Buffer, BufferSnapshot, CodeLabel, LanguageRegistry,
 13    LanguageServerId, ToOffset,
 14};
 15use project::{search::SearchQuery, Completion};
 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::{prelude::*, TextSize};
 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: View<Editor>,
 46    user_store: Model<UserStore>,
 47    channel_chat: Option<Model<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(WeakView<MessageEditor>);
 55
 56impl CompletionProvider for MessageEditorCompletionProvider {
 57    fn completions(
 58        &self,
 59        buffer: &Model<Buffer>,
 60        buffer_position: language::Anchor,
 61        _: editor::CompletionContext,
 62        cx: &mut ViewContext<Editor>,
 63    ) -> Task<anyhow::Result<Vec<Completion>>> {
 64        let Some(handle) = self.0.upgrade() else {
 65            return Task::ready(Ok(Vec::new()));
 66        };
 67        handle.update(cx, |message_editor, cx| {
 68            message_editor.completions(buffer, buffer_position, cx)
 69        })
 70    }
 71
 72    fn resolve_completions(
 73        &self,
 74        _buffer: Model<Buffer>,
 75        _completion_indices: Vec<usize>,
 76        _completions: Rc<RefCell<Box<[Completion]>>>,
 77        _cx: &mut ViewContext<Editor>,
 78    ) -> Task<anyhow::Result<bool>> {
 79        Task::ready(Ok(false))
 80    }
 81
 82    fn apply_additional_edits_for_completion(
 83        &self,
 84        _buffer: Model<Buffer>,
 85        _completion: Completion,
 86        _push_to_history: bool,
 87        _cx: &mut ViewContext<Editor>,
 88    ) -> Task<Result<Option<language::Transaction>>> {
 89        Task::ready(Ok(None))
 90    }
 91
 92    fn is_completion_trigger(
 93        &self,
 94        _buffer: &Model<Buffer>,
 95        _position: language::Anchor,
 96        text: &str,
 97        _trigger_in_words: bool,
 98        _cx: &mut ViewContext<Editor>,
 99    ) -> bool {
100        text == "@"
101    }
102}
103
104impl MessageEditor {
105    pub fn new(
106        language_registry: Arc<LanguageRegistry>,
107        user_store: Model<UserStore>,
108        channel_chat: Option<Model<ChannelChat>>,
109        editor: View<Editor>,
110        cx: &mut ViewContext<Self>,
111    ) -> Self {
112        let this = cx.view().downgrade();
113        editor.update(cx, |editor, cx| {
114            editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
115            editor.set_use_autoclose(false);
116            editor.set_show_gutter(false, cx);
117            editor.set_show_wrap_guides(false, cx);
118            editor.set_show_indent_guides(false, cx);
119            editor.set_completion_provider(Some(Box::new(MessageEditorCompletionProvider(this))));
120            editor.set_auto_replace_emoji_shortcode(
121                MessageEditorSettings::get_global(cx)
122                    .auto_replace_emoji_shortcode
123                    .unwrap_or_default(),
124            );
125        });
126
127        let buffer = editor
128            .read(cx)
129            .buffer()
130            .read(cx)
131            .as_singleton()
132            .expect("message editor must be singleton");
133
134        cx.subscribe(&buffer, Self::on_buffer_event).detach();
135        cx.observe_global::<settings::SettingsStore>(|view, cx| {
136            view.editor.update(cx, |editor, cx| {
137                editor.set_auto_replace_emoji_shortcode(
138                    MessageEditorSettings::get_global(cx)
139                        .auto_replace_emoji_shortcode
140                        .unwrap_or_default(),
141                )
142            })
143        })
144        .detach();
145
146        let markdown = language_registry.language_for_name("Markdown");
147        cx.spawn(|_, mut cx| async move {
148            let markdown = markdown.await.context("failed to load Markdown language")?;
149            buffer.update(&mut cx, |buffer, cx| {
150                buffer.set_language(Some(markdown), cx)
151            })
152        })
153        .detach_and_log_err(cx);
154
155        Self {
156            editor,
157            user_store,
158            channel_chat,
159            mentions: Vec::new(),
160            mentions_task: None,
161            reply_to_message_id: None,
162            edit_message_id: None,
163        }
164    }
165
166    pub fn reply_to_message_id(&self) -> Option<u64> {
167        self.reply_to_message_id
168    }
169
170    pub fn set_reply_to_message_id(&mut self, reply_to_message_id: u64) {
171        self.reply_to_message_id = Some(reply_to_message_id);
172    }
173
174    pub fn clear_reply_to_message_id(&mut self) {
175        self.reply_to_message_id = None;
176    }
177
178    pub fn edit_message_id(&self) -> Option<u64> {
179        self.edit_message_id
180    }
181
182    pub fn set_edit_message_id(&mut self, edit_message_id: u64) {
183        self.edit_message_id = Some(edit_message_id);
184    }
185
186    pub fn clear_edit_message_id(&mut self) {
187        self.edit_message_id = None;
188    }
189
190    pub fn set_channel_chat(&mut self, chat: Model<ChannelChat>, cx: &mut ViewContext<Self>) {
191        let channel_id = chat.read(cx).channel_id;
192        self.channel_chat = Some(chat);
193        let channel_name = ChannelStore::global(cx)
194            .read(cx)
195            .channel_for_id(channel_id)
196            .map(|channel| channel.name.clone());
197        self.editor.update(cx, |editor, cx| {
198            if let Some(channel_name) = channel_name {
199                editor.set_placeholder_text(format!("Message #{channel_name}"), cx);
200            } else {
201                editor.set_placeholder_text("Message Channel", cx);
202            }
203        });
204    }
205
206    pub fn take_message(&mut self, cx: &mut ViewContext<Self>) -> MessageParams {
207        self.editor.update(cx, |editor, cx| {
208            let highlights = editor.text_highlights::<Self>(cx);
209            let text = editor.text(cx);
210            let snapshot = editor.buffer().read(cx).snapshot(cx);
211            let mentions = if let Some((_, ranges)) = highlights {
212                ranges
213                    .iter()
214                    .map(|range| range.to_offset(&snapshot))
215                    .zip(self.mentions.iter().copied())
216                    .collect()
217            } else {
218                Vec::new()
219            };
220
221            editor.clear(cx);
222            self.mentions.clear();
223            let reply_to_message_id = std::mem::take(&mut self.reply_to_message_id);
224
225            MessageParams {
226                text,
227                mentions,
228                reply_to_message_id,
229            }
230        })
231    }
232
233    fn on_buffer_event(
234        &mut self,
235        buffer: Model<Buffer>,
236        event: &language::BufferEvent,
237        cx: &mut ViewContext<Self>,
238    ) {
239        if let language::BufferEvent::Reparsed | language::BufferEvent::Edited = event {
240            let buffer = buffer.read(cx).snapshot();
241            self.mentions_task = Some(cx.spawn(|this, cx| async move {
242                cx.background_executor()
243                    .timer(MENTIONS_DEBOUNCE_INTERVAL)
244                    .await;
245                Self::find_mentions(this, buffer, cx).await;
246            }));
247        }
248    }
249
250    fn completions(
251        &mut self,
252        buffer: &Model<Buffer>,
253        end_anchor: Anchor,
254        cx: &mut ViewContext<Self>,
255    ) -> Task<Result<Vec<Completion>>> {
256        if let Some((start_anchor, query, candidates)) =
257            self.collect_mention_candidates(buffer, end_anchor, cx)
258        {
259            if !candidates.is_empty() {
260                return cx.spawn(|_, cx| async move {
261                    Ok(Self::resolve_completions_for_candidates(
262                        &cx,
263                        query.as_str(),
264                        &candidates,
265                        start_anchor..end_anchor,
266                        Self::completion_for_mention,
267                    )
268                    .await)
269                });
270            }
271        }
272
273        if let Some((start_anchor, query, candidates)) =
274            self.collect_emoji_candidates(buffer, end_anchor, cx)
275        {
276            if !candidates.is_empty() {
277                return cx.spawn(|_, cx| async move {
278                    Ok(Self::resolve_completions_for_candidates(
279                        &cx,
280                        query.as_str(),
281                        candidates,
282                        start_anchor..end_anchor,
283                        Self::completion_for_emoji,
284                    )
285                    .await)
286                });
287            }
288        }
289
290        Task::ready(Ok(vec![]))
291    }
292
293    async fn resolve_completions_for_candidates(
294        cx: &AsyncWindowContext,
295        query: &str,
296        candidates: &[StringMatchCandidate],
297        range: Range<Anchor>,
298        completion_fn: impl Fn(&StringMatch) -> (String, CodeLabel),
299    ) -> Vec<Completion> {
300        let matches = fuzzy::match_strings(
301            candidates,
302            query,
303            true,
304            10,
305            &Default::default(),
306            cx.background_executor().clone(),
307        )
308        .await;
309
310        matches
311            .into_iter()
312            .map(|mat| {
313                let (new_text, label) = completion_fn(&mat);
314                Completion {
315                    old_range: range.clone(),
316                    new_text,
317                    label,
318                    documentation: None,
319                    server_id: LanguageServerId(0), // TODO: Make this optional or something?
320                    lsp_completion: Default::default(), // TODO: Make this optional or something?
321                    confirm: None,
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: &Model<Buffer>,
349        end_anchor: Anchor,
350        cx: &mut ViewContext<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: &Model<Buffer>,
398        end_anchor: Anchor,
399        cx: &mut ViewContext<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: WeakView<MessageEditor>,
458        buffer: BufferSnapshot,
459        mut cx: AsyncWindowContext,
460    ) {
461        let (buffer, ranges) = cx
462            .background_executor()
463            .spawn(async move {
464                let ranges = MENTIONS_SEARCH.search(&buffer, None).await;
465                (buffer, ranges)
466            })
467            .await;
468
469        this.update(&mut cx, |this, cx| {
470            let mut anchor_ranges = Vec::new();
471            let mut mentioned_user_ids = Vec::new();
472            let mut text = String::new();
473
474            this.editor.update(cx, |editor, cx| {
475                let multi_buffer = editor.buffer().read(cx).snapshot(cx);
476                for range in ranges {
477                    text.clear();
478                    text.extend(buffer.text_for_range(range.clone()));
479                    if let Some(username) = text.strip_prefix('@') {
480                        if let Some(user) = this
481                            .user_store
482                            .read(cx)
483                            .cached_user_by_github_login(username)
484                        {
485                            let start = multi_buffer.anchor_after(range.start);
486                            let end = multi_buffer.anchor_after(range.end);
487
488                            mentioned_user_ids.push(user.id);
489                            anchor_ranges.push(start..end);
490                        }
491                    }
492                }
493
494                editor.clear_highlights::<Self>(cx);
495                editor.highlight_text::<Self>(
496                    anchor_ranges,
497                    HighlightStyle {
498                        font_weight: Some(FontWeight::BOLD),
499                        ..Default::default()
500                    },
501                    cx,
502                )
503            });
504
505            this.mentions = mentioned_user_ids;
506            this.mentions_task.take();
507        })
508        .ok();
509    }
510
511    pub(crate) fn focus_handle(&self, cx: &gpui::AppContext) -> gpui::FocusHandle {
512        self.editor.read(cx).focus_handle(cx)
513    }
514}
515
516impl Render for MessageEditor {
517    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
518        let settings = ThemeSettings::get_global(cx);
519        let text_style = TextStyle {
520            color: if self.editor.read(cx).read_only(cx) {
521                cx.theme().colors().text_disabled
522            } else {
523                cx.theme().colors().text
524            },
525            font_family: settings.ui_font.family.clone(),
526            font_features: settings.ui_font.features.clone(),
527            font_fallbacks: settings.ui_font.fallbacks.clone(),
528            font_size: TextSize::Small.rems(cx).into(),
529            font_weight: settings.ui_font.weight,
530            font_style: FontStyle::Normal,
531            line_height: relative(1.3),
532            ..Default::default()
533        };
534
535        div()
536            .w_full()
537            .px_2()
538            .py_1()
539            .bg(cx.theme().colors().editor_background)
540            .rounded_md()
541            .child(EditorElement::new(
542                &self.editor,
543                EditorStyle {
544                    local_player: cx.theme().players().local(),
545                    text: text_style,
546                    ..Default::default()
547                },
548            ))
549    }
550}