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 }
309 })
310 .collect()
311 }
312
313 fn completion_for_mention(mat: &StringMatch) -> (String, CodeLabel) {
314 let label = CodeLabel {
315 filter_range: 1..mat.string.len() + 1,
316 text: format!("@{}", mat.string),
317 runs: Vec::new(),
318 };
319 (mat.string.clone(), label)
320 }
321
322 fn completion_for_emoji(mat: &StringMatch) -> (String, CodeLabel) {
323 let emoji = emojis::get_by_shortcode(&mat.string).unwrap();
324 let label = CodeLabel {
325 filter_range: 1..mat.string.len() + 1,
326 text: format!(":{}: {}", mat.string, emoji),
327 runs: Vec::new(),
328 };
329 (emoji.to_string(), label)
330 }
331
332 fn collect_mention_candidates(
333 &mut self,
334 buffer: &Model<Buffer>,
335 end_anchor: Anchor,
336 cx: &mut ViewContext<Self>,
337 ) -> Option<(Anchor, String, Vec<StringMatchCandidate>)> {
338 let end_offset = end_anchor.to_offset(buffer.read(cx));
339
340 let Some(query) = buffer.update(cx, |buffer, _| {
341 let mut query = String::new();
342 for ch in buffer.reversed_chars_at(end_offset).take(100) {
343 if ch == '@' {
344 return Some(query.chars().rev().collect::<String>());
345 }
346 if ch.is_whitespace() || !ch.is_ascii() {
347 break;
348 }
349 query.push(ch);
350 }
351 None
352 }) else {
353 return None;
354 };
355
356 let start_offset = end_offset - query.len();
357 let start_anchor = buffer.read(cx).anchor_before(start_offset);
358
359 let mut names = HashSet::default();
360 if let Some(chat) = self.channel_chat.as_ref() {
361 let chat = chat.read(cx);
362 for participant in ChannelStore::global(cx)
363 .read(cx)
364 .channel_participants(chat.channel_id)
365 {
366 names.insert(participant.github_login.clone());
367 }
368 for message in chat
369 .messages_in_range(chat.message_count().saturating_sub(100)..chat.message_count())
370 {
371 names.insert(message.sender.github_login.clone());
372 }
373 }
374
375 let candidates = names
376 .into_iter()
377 .map(|user| StringMatchCandidate {
378 id: 0,
379 string: user.clone(),
380 char_bag: user.chars().collect(),
381 })
382 .collect::<Vec<_>>();
383
384 Some((start_anchor, query, candidates))
385 }
386
387 fn collect_emoji_candidates(
388 &mut self,
389 buffer: &Model<Buffer>,
390 end_anchor: Anchor,
391 cx: &mut ViewContext<Self>,
392 ) -> Option<(Anchor, String, &'static [StringMatchCandidate])> {
393 lazy_static! {
394 static ref EMOJI_FUZZY_MATCH_CANDIDATES: Vec<StringMatchCandidate> = {
395 let emojis = emojis::iter()
396 .flat_map(|s| s.shortcodes())
397 .map(|emoji| StringMatchCandidate {
398 id: 0,
399 string: emoji.to_string(),
400 char_bag: emoji.chars().collect(),
401 })
402 .collect::<Vec<_>>();
403 emojis
404 };
405 }
406
407 let end_offset = end_anchor.to_offset(buffer.read(cx));
408
409 let Some(query) = buffer.update(cx, |buffer, _| {
410 let mut query = String::new();
411 for ch in buffer.reversed_chars_at(end_offset).take(100) {
412 if ch == ':' {
413 let next_char = buffer
414 .reversed_chars_at(end_offset - query.len() - 1)
415 .next();
416 // Ensure we are at the start of the message or that the previous character is a whitespace
417 if next_char.is_none() || next_char.unwrap().is_whitespace() {
418 return Some(query.chars().rev().collect::<String>());
419 }
420
421 // If the previous character is not a whitespace, we are in the middle of a word
422 // and we only want to complete the shortcode if the word is made up of other emojis
423 let mut containing_word = String::new();
424 for ch in buffer
425 .reversed_chars_at(end_offset - query.len() - 1)
426 .take(100)
427 {
428 if ch.is_whitespace() {
429 break;
430 }
431 containing_word.push(ch);
432 }
433 let containing_word = containing_word.chars().rev().collect::<String>();
434 if util::word_consists_of_emojis(containing_word.as_str()) {
435 return Some(query.chars().rev().collect::<String>());
436 }
437 break;
438 }
439 if ch.is_whitespace() || !ch.is_ascii() {
440 break;
441 }
442 query.push(ch);
443 }
444 None
445 }) else {
446 return None;
447 };
448
449 let start_offset = end_offset - query.len() - 1;
450 let start_anchor = buffer.read(cx).anchor_before(start_offset);
451
452 Some((start_anchor, query, &EMOJI_FUZZY_MATCH_CANDIDATES))
453 }
454
455 async fn find_mentions(
456 this: WeakView<MessageEditor>,
457 buffer: BufferSnapshot,
458 mut cx: AsyncWindowContext,
459 ) {
460 let (buffer, ranges) = cx
461 .background_executor()
462 .spawn(async move {
463 let ranges = MENTIONS_SEARCH.search(&buffer, None).await;
464 (buffer, ranges)
465 })
466 .await;
467
468 this.update(&mut cx, |this, cx| {
469 let mut anchor_ranges = Vec::new();
470 let mut mentioned_user_ids = Vec::new();
471 let mut text = String::new();
472
473 this.editor.update(cx, |editor, cx| {
474 let multi_buffer = editor.buffer().read(cx).snapshot(cx);
475 for range in ranges {
476 text.clear();
477 text.extend(buffer.text_for_range(range.clone()));
478 if let Some(username) = text.strip_prefix('@') {
479 if let Some(user) = this
480 .user_store
481 .read(cx)
482 .cached_user_by_github_login(username)
483 {
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: settings.ui_font.weight,
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}