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                    show_new_completions_on_confirm: false,
310                }
311            })
312            .collect()
313    }
314
315    fn completion_for_mention(mat: &StringMatch) -> (String, CodeLabel) {
316        let label = CodeLabel {
317            filter_range: 1..mat.string.len() + 1,
318            text: format!("@{}", mat.string),
319            runs: Vec::new(),
320        };
321        (mat.string.clone(), label)
322    }
323
324    fn completion_for_emoji(mat: &StringMatch) -> (String, CodeLabel) {
325        let emoji = emojis::get_by_shortcode(&mat.string).unwrap();
326        let label = CodeLabel {
327            filter_range: 1..mat.string.len() + 1,
328            text: format!(":{}: {}", mat.string, emoji),
329            runs: Vec::new(),
330        };
331        (emoji.to_string(), label)
332    }
333
334    fn collect_mention_candidates(
335        &mut self,
336        buffer: &Model<Buffer>,
337        end_anchor: Anchor,
338        cx: &mut ViewContext<Self>,
339    ) -> Option<(Anchor, String, Vec<StringMatchCandidate>)> {
340        let end_offset = end_anchor.to_offset(buffer.read(cx));
341
342        let Some(query) = buffer.update(cx, |buffer, _| {
343            let mut query = String::new();
344            for ch in buffer.reversed_chars_at(end_offset).take(100) {
345                if ch == '@' {
346                    return Some(query.chars().rev().collect::<String>());
347                }
348                if ch.is_whitespace() || !ch.is_ascii() {
349                    break;
350                }
351                query.push(ch);
352            }
353            None
354        }) else {
355            return None;
356        };
357
358        let start_offset = end_offset - query.len();
359        let start_anchor = buffer.read(cx).anchor_before(start_offset);
360
361        let mut names = HashSet::default();
362        if let Some(chat) = self.channel_chat.as_ref() {
363            let chat = chat.read(cx);
364            for participant in ChannelStore::global(cx)
365                .read(cx)
366                .channel_participants(chat.channel_id)
367            {
368                names.insert(participant.github_login.clone());
369            }
370            for message in chat
371                .messages_in_range(chat.message_count().saturating_sub(100)..chat.message_count())
372            {
373                names.insert(message.sender.github_login.clone());
374            }
375        }
376
377        let candidates = names
378            .into_iter()
379            .map(|user| StringMatchCandidate {
380                id: 0,
381                string: user.clone(),
382                char_bag: user.chars().collect(),
383            })
384            .collect::<Vec<_>>();
385
386        Some((start_anchor, query, candidates))
387    }
388
389    fn collect_emoji_candidates(
390        &mut self,
391        buffer: &Model<Buffer>,
392        end_anchor: Anchor,
393        cx: &mut ViewContext<Self>,
394    ) -> Option<(Anchor, String, &'static [StringMatchCandidate])> {
395        lazy_static! {
396            static ref EMOJI_FUZZY_MATCH_CANDIDATES: Vec<StringMatchCandidate> = {
397                let emojis = emojis::iter()
398                    .flat_map(|s| s.shortcodes())
399                    .map(|emoji| StringMatchCandidate {
400                        id: 0,
401                        string: emoji.to_string(),
402                        char_bag: emoji.chars().collect(),
403                    })
404                    .collect::<Vec<_>>();
405                emojis
406            };
407        }
408
409        let end_offset = end_anchor.to_offset(buffer.read(cx));
410
411        let Some(query) = buffer.update(cx, |buffer, _| {
412            let mut query = String::new();
413            for ch in buffer.reversed_chars_at(end_offset).take(100) {
414                if ch == ':' {
415                    let next_char = buffer
416                        .reversed_chars_at(end_offset - query.len() - 1)
417                        .next();
418                    // Ensure we are at the start of the message or that the previous character is a whitespace
419                    if next_char.is_none() || next_char.unwrap().is_whitespace() {
420                        return Some(query.chars().rev().collect::<String>());
421                    }
422
423                    // If the previous character is not a whitespace, we are in the middle of a word
424                    // and we only want to complete the shortcode if the word is made up of other emojis
425                    let mut containing_word = String::new();
426                    for ch in buffer
427                        .reversed_chars_at(end_offset - query.len() - 1)
428                        .take(100)
429                    {
430                        if ch.is_whitespace() {
431                            break;
432                        }
433                        containing_word.push(ch);
434                    }
435                    let containing_word = containing_word.chars().rev().collect::<String>();
436                    if util::word_consists_of_emojis(containing_word.as_str()) {
437                        return Some(query.chars().rev().collect::<String>());
438                    }
439                    break;
440                }
441                if ch.is_whitespace() || !ch.is_ascii() {
442                    break;
443                }
444                query.push(ch);
445            }
446            None
447        }) else {
448            return None;
449        };
450
451        let start_offset = end_offset - query.len() - 1;
452        let start_anchor = buffer.read(cx).anchor_before(start_offset);
453
454        Some((start_anchor, query, &EMOJI_FUZZY_MATCH_CANDIDATES))
455    }
456
457    async fn find_mentions(
458        this: WeakView<MessageEditor>,
459        buffer: BufferSnapshot,
460        mut cx: AsyncWindowContext,
461    ) {
462        let (buffer, ranges) = cx
463            .background_executor()
464            .spawn(async move {
465                let ranges = MENTIONS_SEARCH.search(&buffer, None).await;
466                (buffer, ranges)
467            })
468            .await;
469
470        this.update(&mut cx, |this, cx| {
471            let mut anchor_ranges = Vec::new();
472            let mut mentioned_user_ids = Vec::new();
473            let mut text = String::new();
474
475            this.editor.update(cx, |editor, cx| {
476                let multi_buffer = editor.buffer().read(cx).snapshot(cx);
477                for range in ranges {
478                    text.clear();
479                    text.extend(buffer.text_for_range(range.clone()));
480                    if let Some(username) = text.strip_prefix('@') {
481                        if let Some(user) = this
482                            .user_store
483                            .read(cx)
484                            .cached_user_by_github_login(username)
485                        {
486                            let start = multi_buffer.anchor_after(range.start);
487                            let end = multi_buffer.anchor_after(range.end);
488
489                            mentioned_user_ids.push(user.id);
490                            anchor_ranges.push(start..end);
491                        }
492                    }
493                }
494
495                editor.clear_highlights::<Self>(cx);
496                editor.highlight_text::<Self>(
497                    anchor_ranges,
498                    HighlightStyle {
499                        font_weight: Some(FontWeight::BOLD),
500                        ..Default::default()
501                    },
502                    cx,
503                )
504            });
505
506            this.mentions = mentioned_user_ids;
507            this.mentions_task.take();
508        })
509        .ok();
510    }
511
512    pub(crate) fn focus_handle(&self, cx: &gpui::AppContext) -> gpui::FocusHandle {
513        self.editor.read(cx).focus_handle(cx)
514    }
515}
516
517impl Render for MessageEditor {
518    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
519        let settings = ThemeSettings::get_global(cx);
520        let text_style = TextStyle {
521            color: if self.editor.read(cx).read_only(cx) {
522                cx.theme().colors().text_disabled
523            } else {
524                cx.theme().colors().text
525            },
526            font_family: settings.ui_font.family.clone(),
527            font_features: settings.ui_font.features.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            background_color: None,
533            underline: None,
534            strikethrough: None,
535            white_space: WhiteSpace::Normal,
536        };
537
538        div()
539            .w_full()
540            .px_2()
541            .py_1()
542            .bg(cx.theme().colors().editor_background)
543            .rounded_md()
544            .child(EditorElement::new(
545                &self.editor,
546                EditorStyle {
547                    local_player: cx.theme().players().local(),
548                    text: text_style,
549                    ..Default::default()
550                },
551            ))
552    }
553}