message_editor.rs

  1use anyhow::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, WhiteSpace,
 10};
 11use language::{
 12    language_settings::SoftWrap, Anchor, Buffer, BufferSnapshot, CodeLabel, LanguageRegistry,
 13    LanguageServerId, ToOffset,
 14};
 15use lazy_static::lazy_static;
 16use parking_lot::RwLock;
 17use project::{search::SearchQuery, Completion};
 18use settings::Settings;
 19use std::{ops::Range, sync::Arc, time::Duration};
 20use theme::ThemeSettings;
 21use ui::{prelude::*, TextSize};
 22
 23use crate::panel_settings::MessageEditorSettings;
 24
 25const MENTIONS_DEBOUNCE_INTERVAL: Duration = Duration::from_millis(50);
 26
 27lazy_static! {
 28    static ref MENTIONS_SEARCH: SearchQuery =
 29        SearchQuery::regex("@[-_\\w]+", false, false, false, Vec::new(), Vec::new()).unwrap();
 30}
 31
 32pub struct MessageEditor {
 33    pub editor: View<Editor>,
 34    user_store: Model<UserStore>,
 35    channel_chat: Option<Model<ChannelChat>>,
 36    mentions: Vec<UserId>,
 37    mentions_task: Option<Task<()>>,
 38    reply_to_message_id: Option<u64>,
 39    edit_message_id: Option<u64>,
 40}
 41
 42struct MessageEditorCompletionProvider(WeakView<MessageEditor>);
 43
 44impl CompletionProvider for MessageEditorCompletionProvider {
 45    fn completions(
 46        &self,
 47        buffer: &Model<Buffer>,
 48        buffer_position: language::Anchor,
 49        cx: &mut ViewContext<Editor>,
 50    ) -> Task<anyhow::Result<Vec<Completion>>> {
 51        let Some(handle) = self.0.upgrade() else {
 52            return Task::ready(Ok(Vec::new()));
 53        };
 54        handle.update(cx, |message_editor, cx| {
 55            message_editor.completions(buffer, buffer_position, cx)
 56        })
 57    }
 58
 59    fn resolve_completions(
 60        &self,
 61        _buffer: Model<Buffer>,
 62        _completion_indices: Vec<usize>,
 63        _completions: Arc<RwLock<Box<[Completion]>>>,
 64        _cx: &mut ViewContext<Editor>,
 65    ) -> Task<anyhow::Result<bool>> {
 66        Task::ready(Ok(false))
 67    }
 68
 69    fn apply_additional_edits_for_completion(
 70        &self,
 71        _buffer: Model<Buffer>,
 72        _completion: Completion,
 73        _push_to_history: bool,
 74        _cx: &mut ViewContext<Editor>,
 75    ) -> Task<Result<Option<language::Transaction>>> {
 76        Task::ready(Ok(None))
 77    }
 78
 79    fn is_completion_trigger(
 80        &self,
 81        _buffer: &Model<Buffer>,
 82        _position: language::Anchor,
 83        text: &str,
 84        _trigger_in_words: bool,
 85        _cx: &mut ViewContext<Editor>,
 86    ) -> bool {
 87        text == "@"
 88    }
 89}
 90
 91impl MessageEditor {
 92    pub fn new(
 93        language_registry: Arc<LanguageRegistry>,
 94        user_store: Model<UserStore>,
 95        channel_chat: Option<Model<ChannelChat>>,
 96        editor: View<Editor>,
 97        cx: &mut ViewContext<Self>,
 98    ) -> Self {
 99        let this = cx.view().downgrade();
100        editor.update(cx, |editor, cx| {
101            editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
102            editor.set_use_autoclose(false);
103            editor.set_show_gutter(false, cx);
104            editor.set_show_wrap_guides(false, cx);
105            editor.set_show_indent_guides(false, cx);
106            editor.set_completion_provider(Box::new(MessageEditorCompletionProvider(this)));
107            editor.set_auto_replace_emoji_shortcode(
108                MessageEditorSettings::get_global(cx)
109                    .auto_replace_emoji_shortcode
110                    .unwrap_or_default(),
111            );
112        });
113
114        let buffer = editor
115            .read(cx)
116            .buffer()
117            .read(cx)
118            .as_singleton()
119            .expect("message editor must be singleton");
120
121        cx.subscribe(&buffer, Self::on_buffer_event).detach();
122        cx.observe_global::<settings::SettingsStore>(|view, cx| {
123            view.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(|_, mut cx| async move {
135            let markdown = markdown.await?;
136            buffer.update(&mut cx, |buffer, cx| {
137                buffer.set_language(Some(markdown), cx)
138            })
139        })
140        .detach_and_log_err(cx);
141
142        Self {
143            editor,
144            user_store,
145            channel_chat,
146            mentions: Vec::new(),
147            mentions_task: None,
148            reply_to_message_id: None,
149            edit_message_id: None,
150        }
151    }
152
153    pub fn reply_to_message_id(&self) -> Option<u64> {
154        self.reply_to_message_id
155    }
156
157    pub fn set_reply_to_message_id(&mut self, reply_to_message_id: u64) {
158        self.reply_to_message_id = Some(reply_to_message_id);
159    }
160
161    pub fn clear_reply_to_message_id(&mut self) {
162        self.reply_to_message_id = None;
163    }
164
165    pub fn edit_message_id(&self) -> Option<u64> {
166        self.edit_message_id
167    }
168
169    pub fn set_edit_message_id(&mut self, edit_message_id: u64) {
170        self.edit_message_id = Some(edit_message_id);
171    }
172
173    pub fn clear_edit_message_id(&mut self) {
174        self.edit_message_id = None;
175    }
176
177    pub fn set_channel_chat(&mut self, chat: Model<ChannelChat>, cx: &mut ViewContext<Self>) {
178        let channel_id = chat.read(cx).channel_id;
179        self.channel_chat = Some(chat);
180        let channel_name = ChannelStore::global(cx)
181            .read(cx)
182            .channel_for_id(channel_id)
183            .map(|channel| channel.name.clone());
184        self.editor.update(cx, |editor, cx| {
185            if let Some(channel_name) = channel_name {
186                editor.set_placeholder_text(format!("Message #{channel_name}"), cx);
187            } else {
188                editor.set_placeholder_text("Message Channel", cx);
189            }
190        });
191    }
192
193    pub fn take_message(&mut self, cx: &mut ViewContext<Self>) -> MessageParams {
194        self.editor.update(cx, |editor, cx| {
195            let highlights = editor.text_highlights::<Self>(cx);
196            let text = editor.text(cx);
197            let snapshot = editor.buffer().read(cx).snapshot(cx);
198            let mentions = if let Some((_, ranges)) = highlights {
199                ranges
200                    .iter()
201                    .map(|range| range.to_offset(&snapshot))
202                    .zip(self.mentions.iter().copied())
203                    .collect()
204            } else {
205                Vec::new()
206            };
207
208            editor.clear(cx);
209            self.mentions.clear();
210            let reply_to_message_id = std::mem::take(&mut self.reply_to_message_id);
211
212            MessageParams {
213                text,
214                mentions,
215                reply_to_message_id,
216            }
217        })
218    }
219
220    fn on_buffer_event(
221        &mut self,
222        buffer: Model<Buffer>,
223        event: &language::Event,
224        cx: &mut ViewContext<Self>,
225    ) {
226        if let language::Event::Reparsed | language::Event::Edited = event {
227            let buffer = buffer.read(cx).snapshot();
228            self.mentions_task = Some(cx.spawn(|this, cx| async move {
229                cx.background_executor()
230                    .timer(MENTIONS_DEBOUNCE_INTERVAL)
231                    .await;
232                Self::find_mentions(this, buffer, cx).await;
233            }));
234        }
235    }
236
237    fn completions(
238        &mut self,
239        buffer: &Model<Buffer>,
240        end_anchor: Anchor,
241        cx: &mut ViewContext<Self>,
242    ) -> Task<Result<Vec<Completion>>> {
243        if let Some((start_anchor, query, candidates)) =
244            self.collect_mention_candidates(buffer, end_anchor, cx)
245        {
246            if !candidates.is_empty() {
247                return cx.spawn(|_, cx| async move {
248                    Ok(Self::resolve_completions_for_candidates(
249                        &cx,
250                        query.as_str(),
251                        &candidates,
252                        start_anchor..end_anchor,
253                        Self::completion_for_mention,
254                    )
255                    .await)
256                });
257            }
258        }
259
260        if let Some((start_anchor, query, candidates)) =
261            self.collect_emoji_candidates(buffer, end_anchor, cx)
262        {
263            if !candidates.is_empty() {
264                return cx.spawn(|_, cx| async move {
265                    Ok(Self::resolve_completions_for_candidates(
266                        &cx,
267                        query.as_str(),
268                        candidates,
269                        start_anchor..end_anchor,
270                        Self::completion_for_emoji,
271                    )
272                    .await)
273                });
274            }
275        }
276
277        Task::ready(Ok(vec![]))
278    }
279
280    async fn resolve_completions_for_candidates(
281        cx: &AsyncWindowContext,
282        query: &str,
283        candidates: &[StringMatchCandidate],
284        range: Range<Anchor>,
285        completion_fn: impl Fn(&StringMatch) -> (String, CodeLabel),
286    ) -> Vec<Completion> {
287        let matches = fuzzy::match_strings(
288            &candidates,
289            &query,
290            true,
291            10,
292            &Default::default(),
293            cx.background_executor().clone(),
294        )
295        .await;
296
297        matches
298            .into_iter()
299            .map(|mat| {
300                let (new_text, label) = completion_fn(&mat);
301                Completion {
302                    old_range: range.clone(),
303                    new_text,
304                    label,
305                    documentation: None,
306                    server_id: LanguageServerId(0), // TODO: Make this optional or something?
307                    lsp_completion: Default::default(), // TODO: Make this optional or something?
308                    confirm: None,
309                }
310            })
311            .collect()
312    }
313
314    fn completion_for_mention(mat: &StringMatch) -> (String, CodeLabel) {
315        let label = CodeLabel {
316            filter_range: 1..mat.string.len() + 1,
317            text: format!("@{}", mat.string),
318            runs: Vec::new(),
319        };
320        (mat.string.clone(), label)
321    }
322
323    fn completion_for_emoji(mat: &StringMatch) -> (String, CodeLabel) {
324        let emoji = emojis::get_by_shortcode(&mat.string).unwrap();
325        let label = CodeLabel {
326            filter_range: 1..mat.string.len() + 1,
327            text: format!(":{}: {}", mat.string, emoji),
328            runs: Vec::new(),
329        };
330        (emoji.to_string(), label)
331    }
332
333    fn collect_mention_candidates(
334        &mut self,
335        buffer: &Model<Buffer>,
336        end_anchor: Anchor,
337        cx: &mut ViewContext<Self>,
338    ) -> Option<(Anchor, String, Vec<StringMatchCandidate>)> {
339        let end_offset = end_anchor.to_offset(buffer.read(cx));
340
341        let Some(query) = buffer.update(cx, |buffer, _| {
342            let mut query = String::new();
343            for ch in buffer.reversed_chars_at(end_offset).take(100) {
344                if ch == '@' {
345                    return Some(query.chars().rev().collect::<String>());
346                }
347                if ch.is_whitespace() || !ch.is_ascii() {
348                    break;
349                }
350                query.push(ch);
351            }
352            None
353        }) else {
354            return None;
355        };
356
357        let start_offset = end_offset - query.len();
358        let start_anchor = buffer.read(cx).anchor_before(start_offset);
359
360        let mut names = HashSet::default();
361        if let Some(chat) = self.channel_chat.as_ref() {
362            let chat = chat.read(cx);
363            for participant in ChannelStore::global(cx)
364                .read(cx)
365                .channel_participants(chat.channel_id)
366            {
367                names.insert(participant.github_login.clone());
368            }
369            for message in chat
370                .messages_in_range(chat.message_count().saturating_sub(100)..chat.message_count())
371            {
372                names.insert(message.sender.github_login.clone());
373            }
374        }
375
376        let candidates = names
377            .into_iter()
378            .map(|user| StringMatchCandidate {
379                id: 0,
380                string: user.clone(),
381                char_bag: user.chars().collect(),
382            })
383            .collect::<Vec<_>>();
384
385        Some((start_anchor, query, candidates))
386    }
387
388    fn collect_emoji_candidates(
389        &mut self,
390        buffer: &Model<Buffer>,
391        end_anchor: Anchor,
392        cx: &mut ViewContext<Self>,
393    ) -> Option<(Anchor, String, &'static [StringMatchCandidate])> {
394        lazy_static! {
395            static ref EMOJI_FUZZY_MATCH_CANDIDATES: Vec<StringMatchCandidate> = {
396                let emojis = emojis::iter()
397                    .flat_map(|s| s.shortcodes())
398                    .map(|emoji| StringMatchCandidate {
399                        id: 0,
400                        string: emoji.to_string(),
401                        char_bag: emoji.chars().collect(),
402                    })
403                    .collect::<Vec<_>>();
404                emojis
405            };
406        }
407
408        let end_offset = end_anchor.to_offset(buffer.read(cx));
409
410        let Some(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        }) else {
447            return 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_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            background_color: None,
532            underline: None,
533            strikethrough: None,
534            white_space: WhiteSpace::Normal,
535        };
536
537        div()
538            .w_full()
539            .px_2()
540            .py_1()
541            .bg(cx.theme().colors().editor_background)
542            .rounded_md()
543            .child(EditorElement::new(
544                &self.editor,
545                EditorStyle {
546                    local_player: cx.theme().players().local(),
547                    text: text_style,
548                    ..Default::default()
549                },
550            ))
551    }
552}