BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / composer.rs

composer.rs

271952ed History
composer.rs 34.8 KiB Download Raw
1use std::collections::HashMap;
2use std::ops::Range;
3use std::time::Duration;
4
5use gpui_kit::assets::IconName;
6use gpui_kit::component::{
7 h_flex,
8 input::{
9 Backspace, Enter, Escape, IndentInline, InlineToken, InputContent, InputEvent, MoveDown,
10 MoveUp, Textarea, TextareaState,
11 },
12 v_flex,
13};
14use gpui_kit::prelude::FluentBuilder as _;
15use gpui_kit::*;
16use teams_core::{MentionCandidate, MentionInput};
17
18use super::avatar::{person_avatar, square_avatar};
19use super::emoji_popup::{self, EmojiPopup};
20use super::widgets::{icon, symbol};
21use crate::app_state::AppState;
22use crate::emoji;
23use crate::runtime;
24use crate::theme;
25
26const MIN_ROWS: usize = 1;
27const MAX_ROWS: usize = 8;
28const MENTION_DEBOUNCE: Duration = Duration::from_millis(150);
29const MENTION_LIMIT: usize = 8;
30const MENTION_QUERY_MAX_CHARS: usize = 32;
31const MENTION_QUERY_MAX_WORDS: usize = 3;
32const POPUP_WIDTH: f32 = 380.;
33const POPUP_ROW_HEIGHT: f32 = 44.;
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct ReplyPreview {
37 pub message_id: String,
38 pub author: String,
39 pub excerpt: String,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct EditPreview {
44 pub message_id: String,
45 pub excerpt: String,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct Outgoing {
50 pub text: String,
51 pub mentions: Vec<MentionInput>,
52 pub reply: Option<ReplyPreview>,
53 pub edit: Option<EditPreview>,
54}
55
56pub enum ComposerEvent {
57 Submit(Outgoing),
58 EditLast,
59}
60
61struct MentionPopup {
62 range: Range<usize>,
63 query: String,
64 candidates: Vec<MentionCandidate>,
65 highlighted: usize,
66}
67
68struct Conversion {
69 value: String,
70 cursor: usize,
71 range: Range<usize>,
72 original: String,
73}
74
75pub struct Composer {
76 app: Entity<AppState>,
77 input: Entity<TextareaState>,
78 conversation_id: Option<String>,
79 reply: Option<ReplyPreview>,
80 editing: Option<EditPreview>,
81 mention_inputs: HashMap<String, MentionInput>,
82 mention_counter: usize,
83 popup: Option<MentionPopup>,
84 lookup: Option<Task<()>>,
85 emoji_popup: Option<EmojiPopup>,
86 emoji_dismissed_at: Option<usize>,
87 recent_emoji: emoji::Recent,
88 conversion: Option<Conversion>,
89 undone_value: Option<String>,
90 previous_value: String,
91 _subscription: Subscription,
92}
93
94impl EventEmitter<ComposerEvent> for Composer {}
95
96/// Enter sends, Shift+Enter is a newline (handled by the input itself). Blank text never sends.
97pub fn submitted_text(event: &InputEvent, value: &str) -> Option<String> {
98 match event {
99 InputEvent::PressEnter { shift: false, .. } => {
100 let trimmed = value.trim();
101 (!trimmed.is_empty()).then(|| trimmed.to_owned())
102 }
103 _ => None,
104 }
105}
106
107pub fn active_mention(
108 text: &str,
109 cursor: usize,
110 tokens: &[Range<usize>],
111) -> Option<(Range<usize>, String)> {
112 if cursor > text.len() || !text.is_char_boundary(cursor) {
113 return None;
114 }
115 let before = &text[..cursor];
116 let at = before.rfind('@')?;
117 if before[..at]
118 .chars()
119 .next_back()
120 .is_some_and(|previous| !previous.is_whitespace())
121 {
122 return None;
123 }
124 let query = &before[at + 1..];
125 let rejected = query.contains('\n')
126 || query.starts_with(char::is_whitespace)
127 || query.ends_with(char::is_whitespace)
128 || query.chars().count() > MENTION_QUERY_MAX_CHARS
129 || query.split_whitespace().count() > MENTION_QUERY_MAX_WORDS
130 || tokens
131 .iter()
132 .any(|token| token.start < cursor && at < token.end);
133 (!rejected).then(|| (at..cursor, query.to_owned()))
134}
135
136fn candidate_subtitle(candidate: &MentionCandidate) -> String {
137 match candidate {
138 MentionCandidate::Person(person) => person
139 .job_title
140 .clone()
141 .filter(|title| !title.trim().is_empty())
142 .or_else(|| person.mail.clone())
143 .unwrap_or_default(),
144 MentionCandidate::Channel { .. } => "Channel".to_owned(),
145 MentionCandidate::Team { .. } => "Team".to_owned(),
146 }
147}
148
149fn candidate_key(candidate: &MentionCandidate) -> &str {
150 match candidate {
151 MentionCandidate::Person(person) => &person.user_id,
152 MentionCandidate::Channel { channel_id, .. } => channel_id,
153 MentionCandidate::Team { team_id, .. } => team_id,
154 }
155}
156
157impl Composer {
158 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
159 let input = cx.new(|cx| {
160 TextareaState::new(window, cx)
161 .auto_grow(MIN_ROWS, MAX_ROWS)
162 .submit_on_enter(true)
163 .placeholder("Type a message")
164 });
165 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
166 let recent_emoji = emoji::Recent::load(&app.read(cx).store);
167 Composer {
168 app,
169 input,
170 conversation_id: None,
171 reply: None,
172 editing: None,
173 mention_inputs: HashMap::new(),
174 mention_counter: 0,
175 popup: None,
176 lookup: None,
177 emoji_popup: None,
178 emoji_dismissed_at: None,
179 recent_emoji,
180 conversion: None,
181 undone_value: None,
182 previous_value: String::new(),
183 _subscription: subscription,
184 }
185 }
186
187 fn on_input_event(
188 &mut self,
189 input: &Entity<TextareaState>,
190 event: &InputEvent,
191 window: &mut Window,
192 cx: &mut Context<Self>,
193 ) {
194 cx.notify();
195 if matches!(event, InputEvent::Change) {
196 self.convert_typed(window, cx);
197 self.update_emoji(cx);
198 self.update_mention(cx);
199 }
200 let value = input.read(cx).value();
201 if submitted_text(event, &value).is_some() {
202 self.submit_current(window, cx);
203 }
204 }
205
206 fn update_mention(&mut self, cx: &mut Context<Self>) {
207 let state = self.input.read(cx);
208 let tokens: Vec<Range<usize>> = state.tokens().iter().map(|span| span.range()).collect();
209 let found = active_mention(&state.value(), state.cursor(), &tokens);
210 let Some((range, query)) = found else {
211 self.close_mention_popup();
212 return;
213 };
214 let unchanged = self
215 .popup
216 .as_ref()
217 .is_some_and(|popup| popup.query == query && popup.range == range);
218 if unchanged {
219 return;
220 }
221 let previous = self.popup.take();
222 self.popup = Some(MentionPopup {
223 range,
224 query: query.clone(),
225 candidates: previous.map(|popup| popup.candidates).unwrap_or_default(),
226 highlighted: 0,
227 });
228 self.request_candidates(query, cx);
229 }
230
231 fn close_popup(&mut self) {
232 self.close_mention_popup();
233 self.emoji_popup = None;
234 }
235
236 fn close_mention_popup(&mut self) {
237 self.popup = None;
238 self.lookup = None;
239 }
240
241 fn convert_typed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
242 let state = self.input.read(cx);
243 let (value, cursor) = (state.value().to_string(), state.cursor());
244 let previous = std::mem::replace(&mut self.previous_value, value.clone());
245 let found = match emoji::typed_char(&previous, &value, cursor) {
246 Some(':') => emoji::closing_code(&value, cursor)
247 .and_then(|(range, code)| Some((range, emoji::lookup(code)?))),
248 Some(' ') => emoji::smiley_before_space(&value, cursor),
249 _ => None,
250 };
251 let Some((range, glyph)) = found else {
252 return;
253 };
254 let original = value[range.clone()].to_owned();
255 let cursor = self.replace_text(range.clone(), glyph, cursor, window, cx);
256 self.previous_value = self.input.read(cx).value().to_string();
257 self.conversion = Some(Conversion {
258 value: self.previous_value.clone(),
259 cursor,
260 range: range.start..range.start + glyph.len(),
261 original,
262 });
263 self.remember_emoji(glyph, cx);
264 }
265
266 /// Returns the cursor, kept at the same spot relative to the text after `range`.
267 fn replace_text(
268 &mut self,
269 range: Range<usize>,
270 text: &str,
271 cursor: usize,
272 window: &mut Window,
273 cx: &mut Context<Self>,
274 ) -> usize {
275 let cursor = cursor + text.len() - range.len();
276 self.input.update(cx, |state, cx| {
277 state.set_selected_range(range, cx);
278 state.replace(text.to_owned(), window, cx);
279 state.set_selected_range(cursor..cursor, cx);
280 });
281 cursor
282 }
283
284 fn undo_conversion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
285 let state = self.input.read(cx);
286 let unchanged = self.conversion.as_ref().is_some_and(|conversion| {
287 conversion.value == state.value().as_ref() && conversion.cursor == state.cursor()
288 });
289 let Some(conversion) = self.conversion.take().filter(|_| unchanged) else {
290 return false;
291 };
292 self.replace_text(
293 conversion.range,
294 &conversion.original,
295 conversion.cursor,
296 window,
297 cx,
298 );
299 self.undone_value = Some(self.input.read(cx).value().to_string());
300 self.update_emoji(cx);
301 true
302 }
303
304 fn remember_emoji(&mut self, glyph: &str, cx: &App) {
305 self.recent_emoji.push(glyph);
306 self.recent_emoji.save(&self.app.read(cx).store);
307 }
308
309 fn update_emoji(&mut self, cx: &mut Context<Self>) {
310 let state = self.input.read(cx);
311 let found = emoji::active_query(&state.value(), state.cursor());
312 if found.as_ref().map(|(range, _)| range.start) != self.emoji_dismissed_at {
313 self.emoji_dismissed_at = None;
314 }
315 let found = found.filter(|_| self.emoji_dismissed_at.is_none());
316 let Some((range, query)) = found else {
317 self.emoji_popup = None;
318 return;
319 };
320 let unchanged = self
321 .emoji_popup
322 .as_ref()
323 .is_some_and(|popup| popup.query == query && popup.range == range);
324 if unchanged {
325 return;
326 }
327 let matches = emoji::search(&query, self.recent_emoji.glyphs(), emoji_popup::LIMIT);
328 self.emoji_popup = (!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches));
329 }
330
331 fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {
332 let Some(popup) = self.emoji_popup.take() else {
333 return;
334 };
335 let Some(glyph) = popup.selected().map(|found| found.glyph) else {
336 return;
337 };
338 let cursor = popup.range.end;
339 self.replace_text(popup.range, glyph, cursor, window, cx);
340 self.remember_emoji(glyph, cx);
341 cx.notify();
342 }
343
344 fn request_candidates(&mut self, query: String, cx: &mut Context<Self>) {
345 let Some(conversation_id) = self.conversation_id.clone() else {
346 return;
347 };
348 let (demo, engine) = {
349 let state = self.app.read(cx);
350 (state.mode.demo, state.engine.clone())
351 };
352 if demo {
353 let candidates = crate::demo::mention_candidates(&conversation_id, &query);
354 self.apply_candidates(&query, candidates, cx);
355 return;
356 }
357 let Some(engine) = engine else {
358 return;
359 };
360 self.lookup = Some(cx.spawn(async move |this, cx| {
361 cx.background_executor().timer(MENTION_DEBOUNCE).await;
362 let task_query = query.clone();
363 let receiver = runtime::spawn(async move {
364 engine
365 .mention_candidates(&conversation_id, &task_query, MENTION_LIMIT)
366 .await
367 });
368 if let Ok(Ok(candidates)) = receiver.await {
369 this.update(cx, |this, cx| this.apply_candidates(&query, candidates, cx))
370 .ok();
371 }
372 }));
373 }
374
375 fn apply_candidates(
376 &mut self,
377 query: &str,
378 candidates: Vec<MentionCandidate>,
379 cx: &mut Context<Self>,
380 ) {
381 let Some(popup) = self.popup.as_mut().filter(|popup| popup.query == query) else {
382 return;
383 };
384 popup.candidates = candidates;
385 popup.highlighted = 0;
386 cx.notify();
387 }
388
389 fn popup_is_open(&self) -> bool {
390 self.emoji_popup.is_some()
391 || self
392 .popup
393 .as_ref()
394 .is_some_and(|popup| !popup.candidates.is_empty())
395 }
396
397 fn move_highlight(&mut self, delta: isize, cx: &mut Context<Self>) {
398 if let Some(popup) = self.emoji_popup.as_mut() {
399 popup.move_highlight(delta);
400 cx.notify();
401 } else if let Some(popup) = self.popup.as_mut() {
402 let last = popup.candidates.len().saturating_sub(1) as isize;
403 popup.highlighted = (popup.highlighted as isize + delta).clamp(0, last) as usize;
404 cx.notify();
405 }
406 }
407
408 fn accept_popup(&mut self, window: &mut Window, cx: &mut Context<Self>) {
409 if self.emoji_popup.is_some() {
410 self.accept_emoji(window, cx);
411 } else {
412 self.accept_mention(window, cx);
413 }
414 }
415
416 fn accept_mention(&mut self, window: &mut Window, cx: &mut Context<Self>) {
417 let Some(popup) = self.popup.take() else {
418 return;
419 };
420 self.lookup = None;
421 let Some(candidate) = popup.candidates.get(popup.highlighted) else {
422 return;
423 };
424 self.mention_counter += 1;
425 let token_id = format!(
426 "mention-{}-{}",
427 self.mention_counter,
428 candidate_key(candidate)
429 );
430 let label = format!("@{}", candidate.display_name());
431 self.mention_inputs
432 .insert(token_id.clone(), candidate.to_mention());
433 self.input.update(cx, |state, cx| {
434 let token = InlineToken::new(token_id, label);
435 if state
436 .replace_range_with_token(popup.range, token, window, cx)
437 .is_ok()
438 {
439 state.insert(" ", window, cx);
440 }
441 });
442 self.close_popup();
443 cx.notify();
444 }
445
446 pub fn set_placeholder(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
447 let text = text.to_owned();
448 self.input
449 .update(cx, |state, cx| state.set_placeholder(text, window, cx));
450 }
451
452 pub fn set_conversation(
453 &mut self,
454 conversation_id: &str,
455 name: &str,
456 window: &mut Window,
457 cx: &mut Context<Self>,
458 ) {
459 self.set_placeholder(&format!("Message {name}"), window, cx);
460 if self.conversation_id.as_deref() != Some(conversation_id) {
461 self.conversation_id = Some(conversation_id.to_owned());
462 self.reply = None;
463 if self.editing.take().is_some() {
464 self.input
465 .update(cx, |state, cx| state.set_value("", window, cx));
466 }
467 self.mention_inputs.clear();
468 self.close_popup();
469 cx.notify();
470 }
471 }
472
473 pub fn set_reply(&mut self, reply: Option<ReplyPreview>, cx: &mut Context<Self>) {
474 self.reply = reply;
475 if self.reply.is_some() {
476 self.editing = None;
477 }
478 cx.notify();
479 }
480
481 pub fn begin_edit(&mut self, draft: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
482 self.restore(&draft, window, cx);
483 self.focus(window, cx);
484 }
485
486 fn cancel_edit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
487 self.editing = None;
488 self.set_text("", window, cx);
489 }
490
491 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
492 let state = self.input.read(cx);
493 let mut text = state.value().trim().to_owned();
494 if text.is_empty() {
495 return None;
496 }
497 if self.undone_value.as_deref() != Some(state.value().as_ref())
498 && let Some((range, glyph)) = emoji::trailing_smiley(&text)
499 {
500 text.replace_range(range, glyph);
501 }
502 let mentions = state
503 .tokens()
504 .iter()
505 .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
506 .cloned()
507 .collect();
508 Some(Outgoing {
509 text,
510 mentions,
511 reply: self.reply.clone(),
512 edit: self.editing.clone(),
513 })
514 }
515
516 pub fn submit_current(&mut self, window: &mut Window, cx: &mut Context<Self>) {
517 let Some(outgoing) = self.outgoing(cx) else {
518 return;
519 };
520 self.input
521 .update(cx, |state, cx| state.set_value("", window, cx));
522 self.mention_inputs.clear();
523 self.reply = None;
524 self.editing = None;
525 self.close_popup();
526 cx.emit(ComposerEvent::Submit(outgoing));
527 cx.notify();
528 }
529
530 pub fn restore(&mut self, outgoing: &Outgoing, window: &mut Window, cx: &mut Context<Self>) {
531 self.mention_inputs.clear();
532 let mut content = InputContent::new(outgoing.text.clone());
533 let mut cursor = 0;
534 for mention in &outgoing.mentions {
535 let needle = format!("@{}", mention.text);
536 let Some(offset) = outgoing.text[cursor..].find(&needle) else {
537 continue;
538 };
539 let range = cursor + offset..cursor + offset + needle.len();
540 self.mention_counter += 1;
541 let token_id = format!("mention-{}", self.mention_counter);
542 let token = InlineToken::new(token_id.clone(), needle);
543 if let Ok(next) = content.clone().with_token(range.clone(), token) {
544 content = next;
545 self.mention_inputs.insert(token_id, mention.clone());
546 cursor = range.end;
547 }
548 }
549 let end = outgoing.text.len();
550 self.input.update(cx, |state, cx| {
551 state.set_value(content, window, cx);
552 state.set_selected_range(end..end, cx);
553 });
554 self.reply = outgoing.reply.clone();
555 self.editing = outgoing.edit.clone();
556 self.close_popup();
557 cx.notify();
558 }
559
560 pub fn set_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
561 let text = text.to_owned();
562 let end = text.len();
563 self.input.update(cx, |state, cx| {
564 state.set_value(text, window, cx);
565 state.set_selected_range(end..end, cx);
566 });
567 self.mention_inputs.clear();
568 self.update_emoji(cx);
569 self.update_mention(cx);
570 cx.notify();
571 }
572
573 pub fn is_empty(&self, cx: &App) -> bool {
574 self.input.read(cx).value().trim().is_empty()
575 }
576
577 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
578 self.input.update(cx, |state, cx| state.focus(window, cx));
579 }
580
581 fn render_popup(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
582 let popup = self
583 .popup
584 .as_ref()
585 .filter(|popup| !popup.candidates.is_empty())?;
586 let directory = &self.app.read(cx).directory;
587 let rows = popup
588 .candidates
589 .iter()
590 .enumerate()
591 .map(|(index, candidate)| {
592 let name = candidate.display_name().to_owned();
593 let avatar = match candidate {
594 MentionCandidate::Person(person) => {
595 person_avatar(directory, Some(&person.user_id), &name, 28.)
596 }
597 other => square_avatar(&name, candidate_key(other), 28., 7.).into_any_element(),
598 };
599 let subtitle = candidate_subtitle(candidate);
600 h_flex()
601 .id(ElementId::Name(format!("mention-row-{index}").into()))
602 .mx(px(6.))
603 .px(px(6.))
604 .h(px(POPUP_ROW_HEIGHT))
605 .gap(px(10.))
606 .items_center()
607 .rounded(px(6.))
608 .cursor_pointer()
609 .when(index == popup.highlighted, |row| {
610 row.bg(theme::surface_raised())
611 })
612 .hover(|row| row.bg(theme::row_hover()))
613 .child(avatar)
614 .child(
615 v_flex()
616 .flex_1()
617 .min_w_0()
618 .child(
619 div()
620 .truncate()
621 .text_size(px(13.5))
622 .text_color(theme::text())
623 .child(name),
624 )
625 .when(!subtitle.is_empty(), |column| {
626 column.child(
627 div()
628 .truncate()
629 .text_size(px(12.))
630 .text_color(theme::text_muted())
631 .child(subtitle),
632 )
633 }),
634 )
635 .on_click(cx.listener(move |this, _, window, cx| {
636 if let Some(popup) = this.popup.as_mut() {
637 popup.highlighted = index;
638 }
639 this.accept_mention(window, cx);
640 }))
641 });
642 Some(
643 v_flex()
644 .id("mention-popup")
645 .absolute()
646 .bottom(relative(1.))
647 .left_0()
648 .mb(px(6.))
649 .w(px(POPUP_WIDTH))
650 .py(px(6.))
651 .rounded(px(10.))
652 .border_1()
653 .border_color(theme::border_strong())
654 .bg(theme::surface())
655 .shadow_lg()
656 .occlude()
657 .children(rows)
658 .into_any_element(),
659 )
660 }
661
662 fn render_emoji_popup(
663 &self,
664 window: &mut Window,
665 cx: &mut Context<Self>,
666 ) -> Option<AnyElement> {
667 let popup = self.emoji_popup.as_ref()?;
668 let colon = popup.range.start..popup.range.start + 1;
669 let anchor = self
670 .input
671 .read(cx)
672 .range_to_bounds(&colon)
673 .map(|bounds| bounds.origin);
674 if anchor.is_none() {
675 window.request_animation_frame();
676 }
677 let composer = cx.entity().downgrade();
678 Some(emoji_popup::render(
679 popup,
680 anchor,
681 move |index, window, cx| {
682 composer
683 .update(cx, |this, cx| {
684 if let Some(popup) = this.emoji_popup.as_mut() {
685 popup.highlighted = index;
686 }
687 this.accept_emoji(window, cx);
688 })
689 .ok();
690 },
691 ))
692 }
693
694 fn render_edit_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
695 let edit = self.editing.as_ref()?;
696 Some(
697 h_flex()
698 .w_full()
699 .mb(px(6.))
700 .gap(px(10.))
701 .items_center()
702 .pl(px(10.))
703 .pr(px(4.))
704 .py(px(6.))
705 .rounded(px(8.))
706 .bg(theme::surface())
707 .border_1()
708 .border_color(theme::border())
709 .child(icon(IconName::Pencil, 14., theme::accent_text()))
710 .child(
711 v_flex()
712 .flex_1()
713 .min_w_0()
714 .child(
715 div()
716 .truncate()
717 .text_size(px(12.))
718 .font_weight(FontWeight::SEMIBOLD)
719 .text_color(theme::accent_text())
720 .child("Editing message"),
721 )
722 .child(
723 div()
724 .truncate()
725 .text_size(px(12.))
726 .text_color(theme::text_muted())
727 .child(edit.excerpt.clone()),
728 ),
729 )
730 .child(
731 div()
732 .id("edit-close")
733 .size(px(24.))
734 .flex()
735 .items_center()
736 .justify_center()
737 .rounded(px(6.))
738 .cursor_pointer()
739 .hover(|button| button.bg(theme::row_hover()))
740 .child(icon(IconName::Close, 14., theme::text_muted()))
741 .on_click(cx.listener(|this, _, window, cx| this.cancel_edit(window, cx))),
742 ),
743 )
744 }
745
746 fn render_reply_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
747 let reply = self.reply.as_ref()?;
748 Some(
749 h_flex()
750 .w_full()
751 .mb(px(6.))
752 .gap(px(10.))
753 .items_center()
754 .pl(px(10.))
755 .pr(px(4.))
756 .py(px(6.))
757 .rounded(px(8.))
758 .bg(theme::surface())
759 .border_1()
760 .border_color(theme::border())
761 .child(icon(IconName::Undo2, 14., theme::accent_text()))
762 .child(
763 v_flex()
764 .flex_1()
765 .min_w_0()
766 .child(
767 div()
768 .truncate()
769 .text_size(px(12.))
770 .font_weight(FontWeight::SEMIBOLD)
771 .text_color(theme::accent_text())
772 .child(format!("Replying to {}", reply.author)),
773 )
774 .child(
775 div()
776 .truncate()
777 .text_size(px(12.))
778 .text_color(theme::text_muted())
779 .child(reply.excerpt.clone()),
780 ),
781 )
782 .child(
783 div()
784 .id("reply-close")
785 .size(px(24.))
786 .flex()
787 .items_center()
788 .justify_center()
789 .rounded(px(6.))
790 .cursor_pointer()
791 .hover(|button| button.bg(theme::row_hover()))
792 .child(icon(IconName::Close, 14., theme::text_muted()))
793 .on_click(cx.listener(|this, _, _, cx| this.set_reply(None, cx))),
794 ),
795 )
796 }
797}
798
799impl Render for Composer {
800 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
801 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
802 let empty = self.is_empty(cx);
803 let send = div()
804 .id("composer-send")
805 .size(px(32.))
806 .flex_none()
807 .flex()
808 .items_center()
809 .justify_center()
810 .rounded(px(8.))
811 .child(symbol("keyboard_return", 20., white()))
812 .when(empty, |button| button.opacity(0.4))
813 .when(!empty, |button| {
814 button
815 .cursor_pointer()
816 .hover(|button| button.bg(white().opacity(0.1)))
817 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
818 });
819 let input = Textarea::new(&self.input)
820 .appearance(false)
821 .bordered(false)
822 .token(|context, _, _| {
823 div()
824 .h(context.line_height())
825 .px(px(5.))
826 .rounded(px(5.))
827 .bg(if context.is_selected() {
828 theme::accent().opacity(0.4)
829 } else {
830 theme::mention_background(false)
831 })
832 .text_color(theme::mention_text())
833 .font_weight(FontWeight::SEMIBOLD)
834 .child(context.token().label().clone())
835 });
836 v_flex()
837 .w_full()
838 .flex_none()
839 .px(px(24.))
840 .pt(px(8.))
841 .pb(px(12.))
842 .capture_action(cx.listener(|this, _: &MoveUp, _, cx| {
843 if this.popup_is_open() {
844 this.move_highlight(-1, cx);
845 cx.stop_propagation();
846 } else if this.editing.is_none() && this.is_empty(cx) {
847 cx.emit(ComposerEvent::EditLast);
848 cx.stop_propagation();
849 }
850 }))
851 .capture_action(cx.listener(|this, _: &MoveDown, _, cx| {
852 if this.popup_is_open() {
853 this.move_highlight(1, cx);
854 cx.stop_propagation();
855 }
856 }))
857 .capture_action(cx.listener(|this, _: &Enter, window, cx| {
858 if this.popup_is_open() {
859 this.accept_popup(window, cx);
860 cx.stop_propagation();
861 }
862 }))
863 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
864 if this.popup_is_open() {
865 this.accept_popup(window, cx);
866 cx.stop_propagation();
867 }
868 }))
869 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
870 if this.undo_conversion(window, cx) {
871 cx.stop_propagation();
872 }
873 }))
874 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
875 if let Some(popup) = &this.emoji_popup {
876 this.emoji_dismissed_at = Some(popup.range.start);
877 }
878 if this.popup.is_some() || this.emoji_popup.is_some() {
879 this.close_popup();
880 cx.notify();
881 cx.stop_propagation();
882 } else if this.editing.is_some() {
883 this.cancel_edit(window, cx);
884 cx.stop_propagation();
885 }
886 }))
887 .children(self.render_reply_strip(cx))
888 .children(self.render_edit_strip(cx))
889 .child(
890 div()
891 .relative()
892 .w_full()
893 .children(self.render_popup(cx))
894 .children(self.render_emoji_popup(window, cx))
895 .child(
896 h_flex()
897 .w_full()
898 .items_end()
899 .gap(px(6.))
900 .py(px(6.))
901 .pl(px(12.))
902 .pr(px(6.))
903 .rounded(px(10.))
904 .bg(theme::surface())
905 .border_1()
906 .border_color(if focused {
907 theme::accent()
908 } else {
909 theme::border_strong()
910 })
911 .child(div().flex_1().min_w_0().child(input))
912 .child(send),
913 ),
914 )
915 }
916}
917
918#[cfg(test)]
919mod tests {
920 use super::{active_mention, submitted_text};
921 use gpui_kit::component::input::InputEvent;
922
923 fn press(shift: bool) -> InputEvent {
924 InputEvent::PressEnter {
925 secondary: false,
926 shift,
927 }
928 }
929
930 #[test]
931 fn enter_sends_trimmed_text() {
932 assert_eq!(
933 submitted_text(&press(false), " hello \n"),
934 Some("hello".into())
935 );
936 }
937
938 #[test]
939 fn shift_enter_never_sends() {
940 assert_eq!(submitted_text(&press(true), "hello"), None);
941 }
942
943 #[test]
944 fn blank_text_never_sends() {
945 assert_eq!(submitted_text(&press(false), " \n "), None);
946 }
947
948 #[test]
949 fn other_events_never_send() {
950 assert_eq!(submitted_text(&InputEvent::Change, "hello"), None);
951 }
952
953 #[test]
954 fn at_sign_opens_a_mention_query() {
955 assert_eq!(active_mention("hi @Ma", 6, &[]), Some((3..6, "Ma".into())));
956 assert_eq!(active_mention("@", 1, &[]), Some((0..1, String::new())));
957 }
958
959 #[test]
960 fn names_with_a_space_keep_the_query_open() {
961 assert_eq!(
962 active_mention("@Mara Lin", 9, &[]),
963 Some((0..9, "Mara Lin".into()))
964 );
965 }
966
967 #[test]
968 fn mail_addresses_and_closed_queries_do_not_open() {
969 assert_eq!(active_mention("a@b", 3, &[]), None);
970 assert_eq!(active_mention("@Mara ", 6, &[]), None);
971 assert_eq!(active_mention("@ x", 3, &[]), None);
972 assert_eq!(active_mention("@Ma\nrest", 8, &[]), None);
973 }
974
975 #[test]
976 fn text_inside_a_token_does_not_reopen() {
977 let token = 0..15;
978 assert_eq!(
979 active_mention("@Mara Lindqvist", 15, std::slice::from_ref(&token)),
980 None
981 );
982 assert_eq!(
983 active_mention("@Mara Lindqvist @Pr", 19, std::slice::from_ref(&token)),
984 Some((16..19, "Pr".into()))
985 );
986 }
987
988 mod keys {
989 use std::sync::Arc;
990
991 use gpui_kit::test::TestWindowExt as _;
992 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
993 use store::Store;
994
995 use super::super::Composer;
996 use crate::app_state::{AppState, Mode};
997
998 #[gpui_kit::test]
999 fn ctrl_a_selects_the_whole_draft(cx: &mut TestAppContext) {
1000 cx.update(gpui_kit::init);
1001 let store = Arc::new(Store::open_in_memory().unwrap());
1002 let mode = Mode {
1003 demo: true,
1004 read_only: false,
1005 demo_sync: None,
1006 };
1007 let (handle, composer) = cx.update(|cx| {
1008 let app = cx.new(|_| AppState::new(store, mode));
1009 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
1010 cx.new(|cx| Composer::new(app, window, cx))
1011 })
1012 .unwrap()
1013 });
1014 let value = cx
1015 .update_window(handle, |_, window, cx| {
1016 composer.update(cx, |composer, cx| composer.focus(window, cx));
1017 window.render_frame(cx);
1018 window.input("first line", cx);
1019 window.press("shift-enter", cx);
1020 window.input("second line", cx);
1021 window.press("ctrl-a", cx);
1022 window.input("X", cx);
1023 composer.read(cx).input.read(cx).value()
1024 })
1025 .unwrap();
1026 assert_eq!(value, "X");
1027 }
1028 }
1029}