message_editor.rs

  1use anyhow::Result;
  2use channel::{ChannelMembership, ChannelStore, MessageParams};
  3use client::{ChannelId, UserId};
  4use collections::{HashMap, HashSet};
  5use editor::{AnchorRangeExt, CompletionProvider, Editor, EditorElement, EditorStyle};
  6use fuzzy::{StringMatch, StringMatchCandidate};
  7use gpui::{
  8    AsyncWindowContext, FocusableView, FontStyle, FontWeight, HighlightStyle, IntoElement, Model,
  9    Render, SharedString, 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    channel_store: Model<ChannelStore>,
 35    channel_members: HashMap<String, UserId>,
 36    mentions: Vec<UserId>,
 37    mentions_task: Option<Task<()>>,
 38    channel_id: Option<ChannelId>,
 39    reply_to_message_id: Option<u64>,
 40    edit_message_id: Option<u64>,
 41}
 42
 43struct MessageEditorCompletionProvider(WeakView<MessageEditor>);
 44
 45impl CompletionProvider for MessageEditorCompletionProvider {
 46    fn completions(
 47        &self,
 48        buffer: &Model<Buffer>,
 49        buffer_position: language::Anchor,
 50        cx: &mut ViewContext<Editor>,
 51    ) -> Task<anyhow::Result<Vec<Completion>>> {
 52        let Some(handle) = self.0.upgrade() else {
 53            return Task::ready(Ok(Vec::new()));
 54        };
 55        handle.update(cx, |message_editor, cx| {
 56            message_editor.completions(buffer, buffer_position, cx)
 57        })
 58    }
 59
 60    fn resolve_completions(
 61        &self,
 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
 80impl MessageEditor {
 81    pub fn new(
 82        language_registry: Arc<LanguageRegistry>,
 83        channel_store: Model<ChannelStore>,
 84        editor: View<Editor>,
 85        cx: &mut ViewContext<Self>,
 86    ) -> Self {
 87        let this = cx.view().downgrade();
 88        editor.update(cx, |editor, cx| {
 89            editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
 90            editor.set_use_autoclose(false);
 91            editor.set_completion_provider(Box::new(MessageEditorCompletionProvider(this)));
 92            editor.set_auto_replace_emoji_shortcode(
 93                MessageEditorSettings::get_global(cx)
 94                    .auto_replace_emoji_shortcode
 95                    .unwrap_or_default(),
 96            );
 97        });
 98
 99        let buffer = editor
100            .read(cx)
101            .buffer()
102            .read(cx)
103            .as_singleton()
104            .expect("message editor must be singleton");
105
106        cx.subscribe(&buffer, Self::on_buffer_event).detach();
107        cx.observe_global::<settings::SettingsStore>(|view, cx| {
108            view.editor.update(cx, |editor, cx| {
109                editor.set_auto_replace_emoji_shortcode(
110                    MessageEditorSettings::get_global(cx)
111                        .auto_replace_emoji_shortcode
112                        .unwrap_or_default(),
113                )
114            })
115        })
116        .detach();
117
118        let markdown = language_registry.language_for_name("Markdown");
119        cx.spawn(|_, mut cx| async move {
120            let markdown = markdown.await?;
121            buffer.update(&mut cx, |buffer, cx| {
122                buffer.set_language(Some(markdown), cx)
123            })
124        })
125        .detach_and_log_err(cx);
126
127        Self {
128            editor,
129            channel_store,
130            channel_members: HashMap::default(),
131            channel_id: None,
132            mentions: Vec::new(),
133            mentions_task: None,
134            reply_to_message_id: None,
135            edit_message_id: None,
136        }
137    }
138
139    pub fn reply_to_message_id(&self) -> Option<u64> {
140        self.reply_to_message_id
141    }
142
143    pub fn set_reply_to_message_id(&mut self, reply_to_message_id: u64) {
144        self.reply_to_message_id = Some(reply_to_message_id);
145    }
146
147    pub fn clear_reply_to_message_id(&mut self) {
148        self.reply_to_message_id = None;
149    }
150
151    pub fn edit_message_id(&self) -> Option<u64> {
152        self.edit_message_id
153    }
154
155    pub fn set_edit_message_id(&mut self, edit_message_id: u64) {
156        self.edit_message_id = Some(edit_message_id);
157    }
158
159    pub fn clear_edit_message_id(&mut self) {
160        self.edit_message_id = None;
161    }
162
163    pub fn set_channel(
164        &mut self,
165        channel_id: ChannelId,
166        channel_name: Option<SharedString>,
167        cx: &mut ViewContext<Self>,
168    ) {
169        self.editor.update(cx, |editor, cx| {
170            if let Some(channel_name) = channel_name {
171                editor.set_placeholder_text(format!("Message #{channel_name}"), cx);
172            } else {
173                editor.set_placeholder_text("Message Channel", cx);
174            }
175        });
176        self.channel_id = Some(channel_id);
177        self.refresh_users(cx);
178    }
179
180    pub fn refresh_users(&mut self, cx: &mut ViewContext<Self>) {
181        if let Some(channel_id) = self.channel_id {
182            let members = self.channel_store.update(cx, |store, cx| {
183                store.get_channel_member_details(channel_id, cx)
184            });
185            cx.spawn(|this, mut cx| async move {
186                let members = members.await?;
187                this.update(&mut cx, |this, cx| this.set_members(members, cx))?;
188                anyhow::Ok(())
189            })
190            .detach_and_log_err(cx);
191        }
192    }
193
194    pub fn set_members(&mut self, members: Vec<ChannelMembership>, _: &mut ViewContext<Self>) {
195        self.channel_members.clear();
196        self.channel_members.extend(
197            members
198                .into_iter()
199                .map(|member| (member.user.github_login.clone(), member.user.id)),
200        );
201    }
202
203    pub fn take_message(&mut self, cx: &mut ViewContext<Self>) -> MessageParams {
204        self.editor.update(cx, |editor, cx| {
205            let highlights = editor.text_highlights::<Self>(cx);
206            let text = editor.text(cx);
207            let snapshot = editor.buffer().read(cx).snapshot(cx);
208            let mentions = if let Some((_, ranges)) = highlights {
209                ranges
210                    .iter()
211                    .map(|range| range.to_offset(&snapshot))
212                    .zip(self.mentions.iter().copied())
213                    .collect()
214            } else {
215                Vec::new()
216            };
217
218            editor.clear(cx);
219            self.mentions.clear();
220            let reply_to_message_id = std::mem::take(&mut self.reply_to_message_id);
221
222            MessageParams {
223                text,
224                mentions,
225                reply_to_message_id,
226            }
227        })
228    }
229
230    fn on_buffer_event(
231        &mut self,
232        buffer: Model<Buffer>,
233        event: &language::Event,
234        cx: &mut ViewContext<Self>,
235    ) {
236        if let language::Event::Reparsed | language::Event::Edited = event {
237            let buffer = buffer.read(cx).snapshot();
238            self.mentions_task = Some(cx.spawn(|this, cx| async move {
239                cx.background_executor()
240                    .timer(MENTIONS_DEBOUNCE_INTERVAL)
241                    .await;
242                Self::find_mentions(this, buffer, cx).await;
243            }));
244        }
245    }
246
247    fn completions(
248        &mut self,
249        buffer: &Model<Buffer>,
250        end_anchor: Anchor,
251        cx: &mut ViewContext<Self>,
252    ) -> Task<Result<Vec<Completion>>> {
253        if let Some((start_anchor, query, candidates)) =
254            self.collect_mention_candidates(buffer, end_anchor, cx)
255        {
256            if !candidates.is_empty() {
257                return cx.spawn(|_, cx| async move {
258                    Ok(Self::resolve_completions_for_candidates(
259                        &cx,
260                        query.as_str(),
261                        &candidates,
262                        start_anchor..end_anchor,
263                        Self::completion_for_mention,
264                    )
265                    .await)
266                });
267            }
268        }
269
270        if let Some((start_anchor, query, candidates)) =
271            self.collect_emoji_candidates(buffer, end_anchor, cx)
272        {
273            if !candidates.is_empty() {
274                return cx.spawn(|_, cx| async move {
275                    Ok(Self::resolve_completions_for_candidates(
276                        &cx,
277                        query.as_str(),
278                        candidates,
279                        start_anchor..end_anchor,
280                        Self::completion_for_emoji,
281                    )
282                    .await)
283                });
284            }
285        }
286
287        Task::ready(Ok(vec![]))
288    }
289
290    async fn resolve_completions_for_candidates(
291        cx: &AsyncWindowContext,
292        query: &str,
293        candidates: &[StringMatchCandidate],
294        range: Range<Anchor>,
295        completion_fn: impl Fn(&StringMatch) -> (String, CodeLabel),
296    ) -> Vec<Completion> {
297        let matches = fuzzy::match_strings(
298            &candidates,
299            &query,
300            true,
301            10,
302            &Default::default(),
303            cx.background_executor().clone(),
304        )
305        .await;
306
307        matches
308            .into_iter()
309            .map(|mat| {
310                let (new_text, label) = completion_fn(&mat);
311                Completion {
312                    old_range: range.clone(),
313                    new_text,
314                    label,
315                    documentation: None,
316                    server_id: LanguageServerId(0), // TODO: Make this optional or something?
317                    lsp_completion: Default::default(), // TODO: Make this optional or something?
318                }
319            })
320            .collect()
321    }
322
323    fn completion_for_mention(mat: &StringMatch) -> (String, CodeLabel) {
324        let label = CodeLabel {
325            filter_range: 1..mat.string.len() + 1,
326            text: format!("@{}", mat.string),
327            runs: Vec::new(),
328        };
329        (mat.string.clone(), label)
330    }
331
332    fn completion_for_emoji(mat: &StringMatch) -> (String, CodeLabel) {
333        let emoji = emojis::get_by_shortcode(&mat.string).unwrap();
334        let label = CodeLabel {
335            filter_range: 1..mat.string.len() + 1,
336            text: format!(":{}: {}", mat.string, emoji),
337            runs: Vec::new(),
338        };
339        (emoji.to_string(), label)
340    }
341
342    fn collect_mention_candidates(
343        &mut self,
344        buffer: &Model<Buffer>,
345        end_anchor: Anchor,
346        cx: &mut ViewContext<Self>,
347    ) -> Option<(Anchor, String, Vec<StringMatchCandidate>)> {
348        let end_offset = end_anchor.to_offset(buffer.read(cx));
349
350        let Some(query) = buffer.update(cx, |buffer, _| {
351            let mut query = String::new();
352            for ch in buffer.reversed_chars_at(end_offset).take(100) {
353                if ch == '@' {
354                    return Some(query.chars().rev().collect::<String>());
355                }
356                if ch.is_whitespace() || !ch.is_ascii() {
357                    break;
358                }
359                query.push(ch);
360            }
361            None
362        }) else {
363            return None;
364        };
365
366        let start_offset = end_offset - query.len();
367        let start_anchor = buffer.read(cx).anchor_before(start_offset);
368
369        let mut names = HashSet::default();
370        for (github_login, _) in self.channel_members.iter() {
371            names.insert(github_login.clone());
372        }
373        if let Some(channel_id) = self.channel_id {
374            for participant in self.channel_store.read(cx).channel_participants(channel_id) {
375                names.insert(participant.github_login.clone());
376            }
377        }
378
379        let candidates = names
380            .into_iter()
381            .map(|user| StringMatchCandidate {
382                id: 0,
383                string: user.clone(),
384                char_bag: user.chars().collect(),
385            })
386            .collect::<Vec<_>>();
387
388        Some((start_anchor, query, candidates))
389    }
390
391    fn collect_emoji_candidates(
392        &mut self,
393        buffer: &Model<Buffer>,
394        end_anchor: Anchor,
395        cx: &mut ViewContext<Self>,
396    ) -> Option<(Anchor, String, &'static [StringMatchCandidate])> {
397        lazy_static! {
398            static ref EMOJI_FUZZY_MATCH_CANDIDATES: Vec<StringMatchCandidate> = {
399                let emojis = emojis::iter()
400                    .flat_map(|s| s.shortcodes())
401                    .map(|emoji| StringMatchCandidate {
402                        id: 0,
403                        string: emoji.to_string(),
404                        char_bag: emoji.chars().collect(),
405                    })
406                    .collect::<Vec<_>>();
407                emojis
408            };
409        }
410
411        let end_offset = end_anchor.to_offset(buffer.read(cx));
412
413        let Some(query) = buffer.update(cx, |buffer, _| {
414            let mut query = String::new();
415            for ch in buffer.reversed_chars_at(end_offset).take(100) {
416                if ch == ':' {
417                    let next_char = buffer
418                        .reversed_chars_at(end_offset - query.len() - 1)
419                        .next();
420                    // Ensure we are at the start of the message or that the previous character is a whitespace
421                    if next_char.is_none() || next_char.unwrap().is_whitespace() {
422                        return Some(query.chars().rev().collect::<String>());
423                    }
424
425                    // If the previous character is not a whitespace, we are in the middle of a word
426                    // and we only want to complete the shortcode if the word is made up of other emojis
427                    let mut containing_word = String::new();
428                    for ch in buffer
429                        .reversed_chars_at(end_offset - query.len() - 1)
430                        .take(100)
431                    {
432                        if ch.is_whitespace() {
433                            break;
434                        }
435                        containing_word.push(ch);
436                    }
437                    let containing_word = containing_word.chars().rev().collect::<String>();
438                    if util::word_consists_of_emojis(containing_word.as_str()) {
439                        return Some(query.chars().rev().collect::<String>());
440                    }
441                    break;
442                }
443                if ch.is_whitespace() || !ch.is_ascii() {
444                    break;
445                }
446                query.push(ch);
447            }
448            None
449        }) else {
450            return None;
451        };
452
453        let start_offset = end_offset - query.len() - 1;
454        let start_anchor = buffer.read(cx).anchor_before(start_offset);
455
456        Some((start_anchor, query, &EMOJI_FUZZY_MATCH_CANDIDATES))
457    }
458
459    async fn find_mentions(
460        this: WeakView<MessageEditor>,
461        buffer: BufferSnapshot,
462        mut cx: AsyncWindowContext,
463    ) {
464        let (buffer, ranges) = cx
465            .background_executor()
466            .spawn(async move {
467                let ranges = MENTIONS_SEARCH.search(&buffer, None).await;
468                (buffer, ranges)
469            })
470            .await;
471
472        this.update(&mut cx, |this, cx| {
473            let mut anchor_ranges = Vec::new();
474            let mut mentioned_user_ids = Vec::new();
475            let mut text = String::new();
476
477            this.editor.update(cx, |editor, cx| {
478                let multi_buffer = editor.buffer().read(cx).snapshot(cx);
479                for range in ranges {
480                    text.clear();
481                    text.extend(buffer.text_for_range(range.clone()));
482                    if let Some(username) = text.strip_prefix('@') {
483                        if let Some(user_id) = this.channel_members.get(username) {
484                            let start = multi_buffer.anchor_after(range.start);
485                            let end = multi_buffer.anchor_after(range.end);
486
487                            mentioned_user_ids.push(*user_id);
488                            anchor_ranges.push(start..end);
489                        }
490                    }
491                }
492
493                editor.clear_highlights::<Self>(cx);
494                editor.highlight_text::<Self>(
495                    anchor_ranges,
496                    HighlightStyle {
497                        font_weight: Some(FontWeight::BOLD),
498                        ..Default::default()
499                    },
500                    cx,
501                )
502            });
503
504            this.mentions = mentioned_user_ids;
505            this.mentions_task.take();
506        })
507        .ok();
508    }
509
510    pub(crate) fn focus_handle(&self, cx: &gpui::AppContext) -> gpui::FocusHandle {
511        self.editor.read(cx).focus_handle(cx)
512    }
513}
514
515impl Render for MessageEditor {
516    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
517        let settings = ThemeSettings::get_global(cx);
518        let text_style = TextStyle {
519            color: if self.editor.read(cx).read_only(cx) {
520                cx.theme().colors().text_disabled
521            } else {
522                cx.theme().colors().text
523            },
524            font_family: settings.ui_font.family.clone(),
525            font_features: settings.ui_font.features.clone(),
526            font_size: TextSize::Small.rems(cx).into(),
527            font_weight: FontWeight::NORMAL,
528            font_style: FontStyle::Normal,
529            line_height: relative(1.3),
530            background_color: None,
531            underline: None,
532            strikethrough: None,
533            white_space: WhiteSpace::Normal,
534        };
535
536        div()
537            .w_full()
538            .px_2()
539            .py_1()
540            .bg(cx.theme().colors().editor_background)
541            .rounded_md()
542            .child(EditorElement::new(
543                &self.editor,
544                EditorStyle {
545                    local_player: cx.theme().players().local(),
546                    text: text_style,
547                    ..Default::default()
548                },
549            ))
550    }
551}
552
553#[cfg(test)]
554mod tests {
555    use super::*;
556    use client::{Client, User, UserStore};
557    use clock::FakeSystemClock;
558    use gpui::TestAppContext;
559    use language::{Language, LanguageConfig};
560    use project::Project;
561    use rpc::proto;
562    use settings::SettingsStore;
563    use util::{http::FakeHttpClient, test::marked_text_ranges};
564
565    #[gpui::test]
566    async fn test_message_editor(cx: &mut TestAppContext) {
567        let language_registry = init_test(cx);
568
569        let (editor, cx) = cx.add_window_view(|cx| {
570            MessageEditor::new(
571                language_registry,
572                ChannelStore::global(cx),
573                cx.new_view(|cx| Editor::auto_height(4, cx)),
574                cx,
575            )
576        });
577        cx.executor().run_until_parked();
578
579        editor.update(cx, |editor, cx| {
580            editor.set_members(
581                vec![
582                    ChannelMembership {
583                        user: Arc::new(User {
584                            github_login: "a-b".into(),
585                            id: 101,
586                            avatar_uri: "avatar_a-b".into(),
587                        }),
588                        kind: proto::channel_member::Kind::Member,
589                        role: proto::ChannelRole::Member,
590                    },
591                    ChannelMembership {
592                        user: Arc::new(User {
593                            github_login: "C_D".into(),
594                            id: 102,
595                            avatar_uri: "avatar_C_D".into(),
596                        }),
597                        kind: proto::channel_member::Kind::Member,
598                        role: proto::ChannelRole::Member,
599                    },
600                ],
601                cx,
602            );
603
604            editor.editor.update(cx, |editor, cx| {
605                editor.set_text("Hello, @a-b! Have you met @C_D?", cx)
606            });
607        });
608
609        cx.executor().advance_clock(MENTIONS_DEBOUNCE_INTERVAL);
610
611        editor.update(cx, |editor, cx| {
612            let (text, ranges) = marked_text_ranges("Hello, «@a-b»! Have you met «@C_D»?", false);
613            assert_eq!(
614                editor.take_message(cx),
615                MessageParams {
616                    text,
617                    mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
618                    reply_to_message_id: None
619                }
620            );
621        });
622    }
623
624    fn init_test(cx: &mut TestAppContext) -> Arc<LanguageRegistry> {
625        cx.update(|cx| {
626            let settings = SettingsStore::test(cx);
627            cx.set_global(settings);
628
629            let clock = Arc::new(FakeSystemClock::default());
630            let http = FakeHttpClient::with_404_response();
631            let client = Client::new(clock, http.clone(), cx);
632            let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
633            theme::init(theme::LoadThemes::JustBase, cx);
634            Project::init_settings(cx);
635            language::init(cx);
636            editor::init(cx);
637            client::init(&client, cx);
638            channel::init(&client, user_store, cx);
639
640            MessageEditorSettings::register(cx);
641        });
642
643        let language_registry = Arc::new(LanguageRegistry::test(cx.executor()));
644        language_registry.add(Arc::new(Language::new(
645            LanguageConfig {
646                name: "Markdown".into(),
647                ..Default::default()
648            },
649            Some(tree_sitter_markdown::language()),
650        )));
651        language_registry
652    }
653}