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