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