BlueGit

ict rusty-teams

Files

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

composer.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
composer.rs 23.1 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 Enter, Escape, IndentInline, InlineToken, InputContent, InputEvent, MoveDown, MoveUp,
10 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::widgets::{icon, symbol};
20use crate::app_state::AppState;
21use crate::runtime;
22use crate::theme;
23
24const MIN_ROWS: usize = 1;
25const MAX_ROWS: usize = 8;
26const MENTION_DEBOUNCE: Duration = Duration::from_millis(150);
27const MENTION_LIMIT: usize = 8;
28const MENTION_QUERY_MAX_CHARS: usize = 32;
29const MENTION_QUERY_MAX_WORDS: usize = 3;
30const POPUP_WIDTH: f32 = 380.;
31const POPUP_ROW_HEIGHT: f32 = 44.;
32
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct ReplyPreview {
35 pub message_id: String,
36 pub author: String,
37 pub excerpt: String,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct Outgoing {
42 pub text: String,
43 pub mentions: Vec<MentionInput>,
44 pub reply: Option<ReplyPreview>,
45}
46
47pub enum ComposerEvent {
48 Submit(Outgoing),
49}
50
51struct MentionPopup {
52 range: Range<usize>,
53 query: String,
54 candidates: Vec<MentionCandidate>,
55 highlighted: usize,
56}
57
58pub struct Composer {
59 app: Entity<AppState>,
60 input: Entity<TextareaState>,
61 conversation_id: Option<String>,
62 reply: Option<ReplyPreview>,
63 mention_inputs: HashMap<String, MentionInput>,
64 mention_counter: usize,
65 popup: Option<MentionPopup>,
66 lookup: Option<Task<()>>,
67 _subscription: Subscription,
68}
69
70impl EventEmitter<ComposerEvent> for Composer {}
71
72/// Enter sends, Shift+Enter is a newline (handled by the input itself). Blank text never sends.
73pub fn submitted_text(event: &InputEvent, value: &str) -> Option<String> {
74 match event {
75 InputEvent::PressEnter { shift: false, .. } => {
76 let trimmed = value.trim();
77 (!trimmed.is_empty()).then(|| trimmed.to_owned())
78 }
79 _ => None,
80 }
81}
82
83pub fn active_mention(
84 text: &str,
85 cursor: usize,
86 tokens: &[Range<usize>],
87) -> Option<(Range<usize>, String)> {
88 if cursor > text.len() || !text.is_char_boundary(cursor) {
89 return None;
90 }
91 let before = &text[..cursor];
92 let at = before.rfind('@')?;
93 if before[..at]
94 .chars()
95 .next_back()
96 .is_some_and(|previous| !previous.is_whitespace())
97 {
98 return None;
99 }
100 let query = &before[at + 1..];
101 let rejected = query.contains('\n')
102 || query.starts_with(char::is_whitespace)
103 || query.ends_with(char::is_whitespace)
104 || query.chars().count() > MENTION_QUERY_MAX_CHARS
105 || query.split_whitespace().count() > MENTION_QUERY_MAX_WORDS
106 || tokens
107 .iter()
108 .any(|token| token.start < cursor && at < token.end);
109 (!rejected).then(|| (at..cursor, query.to_owned()))
110}
111
112fn candidate_subtitle(candidate: &MentionCandidate) -> String {
113 match candidate {
114 MentionCandidate::Person(person) => person
115 .job_title
116 .clone()
117 .filter(|title| !title.trim().is_empty())
118 .or_else(|| person.mail.clone())
119 .unwrap_or_default(),
120 MentionCandidate::Channel { .. } => "Channel".to_owned(),
121 MentionCandidate::Team { .. } => "Team".to_owned(),
122 }
123}
124
125fn candidate_key(candidate: &MentionCandidate) -> &str {
126 match candidate {
127 MentionCandidate::Person(person) => &person.user_id,
128 MentionCandidate::Channel { channel_id, .. } => channel_id,
129 MentionCandidate::Team { team_id, .. } => team_id,
130 }
131}
132
133impl Composer {
134 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
135 let input = cx.new(|cx| {
136 TextareaState::new(window, cx)
137 .auto_grow(MIN_ROWS, MAX_ROWS)
138 .submit_on_enter(true)
139 .placeholder("Nachricht")
140 });
141 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
142 Composer {
143 app,
144 input,
145 conversation_id: None,
146 reply: None,
147 mention_inputs: HashMap::new(),
148 mention_counter: 0,
149 popup: None,
150 lookup: None,
151 _subscription: subscription,
152 }
153 }
154
155 fn on_input_event(
156 &mut self,
157 input: &Entity<TextareaState>,
158 event: &InputEvent,
159 window: &mut Window,
160 cx: &mut Context<Self>,
161 ) {
162 cx.notify();
163 if matches!(event, InputEvent::Change) {
164 self.update_mention(cx);
165 }
166 let value = input.read(cx).value();
167 if submitted_text(event, &value).is_some() {
168 self.submit_current(window, cx);
169 }
170 }
171
172 fn update_mention(&mut self, cx: &mut Context<Self>) {
173 let state = self.input.read(cx);
174 let tokens: Vec<Range<usize>> = state.tokens().iter().map(|span| span.range()).collect();
175 let found = active_mention(&state.value(), state.cursor(), &tokens);
176 let Some((range, query)) = found else {
177 self.close_popup();
178 return;
179 };
180 let unchanged = self
181 .popup
182 .as_ref()
183 .is_some_and(|popup| popup.query == query && popup.range == range);
184 if unchanged {
185 return;
186 }
187 let previous = self.popup.take();
188 self.popup = Some(MentionPopup {
189 range,
190 query: query.clone(),
191 candidates: previous.map(|popup| popup.candidates).unwrap_or_default(),
192 highlighted: 0,
193 });
194 self.request_candidates(query, cx);
195 }
196
197 fn close_popup(&mut self) {
198 self.popup = None;
199 self.lookup = None;
200 }
201
202 fn request_candidates(&mut self, query: String, cx: &mut Context<Self>) {
203 let Some(conversation_id) = self.conversation_id.clone() else {
204 return;
205 };
206 let (demo, engine) = {
207 let state = self.app.read(cx);
208 (state.mode.demo, state.engine.clone())
209 };
210 if demo {
211 let candidates = crate::demo::mention_candidates(&conversation_id, &query);
212 self.apply_candidates(&query, candidates, cx);
213 return;
214 }
215 let Some(engine) = engine else {
216 return;
217 };
218 self.lookup = Some(cx.spawn(async move |this, cx| {
219 cx.background_executor().timer(MENTION_DEBOUNCE).await;
220 let task_query = query.clone();
221 let receiver = runtime::spawn(async move {
222 engine
223 .mention_candidates(&conversation_id, &task_query, MENTION_LIMIT)
224 .await
225 });
226 if let Ok(Ok(candidates)) = receiver.await {
227 this.update(cx, |this, cx| this.apply_candidates(&query, candidates, cx))
228 .ok();
229 }
230 }));
231 }
232
233 fn apply_candidates(
234 &mut self,
235 query: &str,
236 candidates: Vec<MentionCandidate>,
237 cx: &mut Context<Self>,
238 ) {
239 let Some(popup) = self.popup.as_mut().filter(|popup| popup.query == query) else {
240 return;
241 };
242 popup.candidates = candidates;
243 popup.highlighted = 0;
244 cx.notify();
245 }
246
247 fn popup_is_open(&self) -> bool {
248 self.popup
249 .as_ref()
250 .is_some_and(|popup| !popup.candidates.is_empty())
251 }
252
253 fn move_highlight(&mut self, delta: isize, cx: &mut Context<Self>) {
254 if let Some(popup) = self.popup.as_mut() {
255 let last = popup.candidates.len().saturating_sub(1) as isize;
256 popup.highlighted = (popup.highlighted as isize + delta).clamp(0, last) as usize;
257 cx.notify();
258 }
259 }
260
261 fn accept_mention(&mut self, window: &mut Window, cx: &mut Context<Self>) {
262 let Some(popup) = self.popup.take() else {
263 return;
264 };
265 self.lookup = None;
266 let Some(candidate) = popup.candidates.get(popup.highlighted) else {
267 return;
268 };
269 self.mention_counter += 1;
270 let token_id = format!(
271 "mention-{}-{}",
272 self.mention_counter,
273 candidate_key(candidate)
274 );
275 let label = format!("@{}", candidate.display_name());
276 self.mention_inputs
277 .insert(token_id.clone(), candidate.to_mention());
278 self.input.update(cx, |state, cx| {
279 let token = InlineToken::new(token_id, label);
280 if state
281 .replace_range_with_token(popup.range, token, window, cx)
282 .is_ok()
283 {
284 state.insert(" ", window, cx);
285 }
286 });
287 self.close_popup();
288 cx.notify();
289 }
290
291 pub fn set_conversation(
292 &mut self,
293 conversation_id: &str,
294 name: &str,
295 window: &mut Window,
296 cx: &mut Context<Self>,
297 ) {
298 let placeholder = format!("Nachricht an {name}");
299 self.input.update(cx, |state, cx| {
300 state.set_placeholder(placeholder, window, cx)
301 });
302 if self.conversation_id.as_deref() != Some(conversation_id) {
303 self.conversation_id = Some(conversation_id.to_owned());
304 self.reply = None;
305 self.mention_inputs.clear();
306 self.close_popup();
307 cx.notify();
308 }
309 }
310
311 pub fn set_reply(&mut self, reply: Option<ReplyPreview>, cx: &mut Context<Self>) {
312 self.reply = reply;
313 cx.notify();
314 }
315
316 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
317 let state = self.input.read(cx);
318 let text = state.value().trim().to_owned();
319 if text.is_empty() {
320 return None;
321 }
322 let mentions = state
323 .tokens()
324 .iter()
325 .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
326 .cloned()
327 .collect();
328 Some(Outgoing {
329 text,
330 mentions,
331 reply: self.reply.clone(),
332 })
333 }
334
335 pub fn submit_current(&mut self, window: &mut Window, cx: &mut Context<Self>) {
336 let Some(outgoing) = self.outgoing(cx) else {
337 return;
338 };
339 self.input
340 .update(cx, |state, cx| state.set_value("", window, cx));
341 self.mention_inputs.clear();
342 self.reply = None;
343 self.close_popup();
344 cx.emit(ComposerEvent::Submit(outgoing));
345 cx.notify();
346 }
347
348 pub fn restore(&mut self, outgoing: &Outgoing, window: &mut Window, cx: &mut Context<Self>) {
349 self.mention_inputs.clear();
350 let mut content = InputContent::new(outgoing.text.clone());
351 let mut cursor = 0;
352 for mention in &outgoing.mentions {
353 let needle = format!("@{}", mention.text);
354 let Some(offset) = outgoing.text[cursor..].find(&needle) else {
355 continue;
356 };
357 let range = cursor + offset..cursor + offset + needle.len();
358 self.mention_counter += 1;
359 let token_id = format!("mention-{}", self.mention_counter);
360 let token = InlineToken::new(token_id.clone(), needle);
361 if let Ok(next) = content.clone().with_token(range.clone(), token) {
362 content = next;
363 self.mention_inputs.insert(token_id, mention.clone());
364 cursor = range.end;
365 }
366 }
367 let end = outgoing.text.len();
368 self.input.update(cx, |state, cx| {
369 state.set_value(content, window, cx);
370 state.set_selected_range(end..end, cx);
371 });
372 self.reply = outgoing.reply.clone();
373 self.close_popup();
374 cx.notify();
375 }
376
377 pub fn set_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
378 let text = text.to_owned();
379 let end = text.len();
380 self.input.update(cx, |state, cx| {
381 state.set_value(text, window, cx);
382 state.set_selected_range(end..end, cx);
383 });
384 self.mention_inputs.clear();
385 self.update_mention(cx);
386 cx.notify();
387 }
388
389 pub fn is_empty(&self, cx: &App) -> bool {
390 self.input.read(cx).value().trim().is_empty()
391 }
392
393 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
394 self.input.update(cx, |state, cx| state.focus(window, cx));
395 }
396
397 fn render_popup(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
398 let popup = self
399 .popup
400 .as_ref()
401 .filter(|popup| !popup.candidates.is_empty())?;
402 let directory = &self.app.read(cx).directory;
403 let rows = popup
404 .candidates
405 .iter()
406 .enumerate()
407 .map(|(index, candidate)| {
408 let name = candidate.display_name().to_owned();
409 let avatar = match candidate {
410 MentionCandidate::Person(person) => {
411 person_avatar(directory, Some(&person.user_id), &name, 28.)
412 }
413 other => square_avatar(&name, candidate_key(other), 28., 7.).into_any_element(),
414 };
415 let subtitle = candidate_subtitle(candidate);
416 h_flex()
417 .id(ElementId::Name(format!("mention-row-{index}").into()))
418 .mx(px(6.))
419 .px(px(6.))
420 .h(px(POPUP_ROW_HEIGHT))
421 .gap(px(10.))
422 .items_center()
423 .rounded(px(6.))
424 .cursor_pointer()
425 .when(index == popup.highlighted, |row| {
426 row.bg(theme::surface_raised())
427 })
428 .hover(|row| row.bg(theme::row_hover()))
429 .child(avatar)
430 .child(
431 v_flex()
432 .flex_1()
433 .min_w_0()
434 .child(
435 div()
436 .truncate()
437 .text_size(px(13.5))
438 .text_color(theme::text())
439 .child(name),
440 )
441 .when(!subtitle.is_empty(), |column| {
442 column.child(
443 div()
444 .truncate()
445 .text_size(px(12.))
446 .text_color(theme::text_muted())
447 .child(subtitle),
448 )
449 }),
450 )
451 .on_click(cx.listener(move |this, _, window, cx| {
452 if let Some(popup) = this.popup.as_mut() {
453 popup.highlighted = index;
454 }
455 this.accept_mention(window, cx);
456 }))
457 });
458 Some(
459 v_flex()
460 .id("mention-popup")
461 .absolute()
462 .bottom(relative(1.))
463 .left_0()
464 .mb(px(6.))
465 .w(px(POPUP_WIDTH))
466 .py(px(6.))
467 .rounded(px(10.))
468 .border_1()
469 .border_color(theme::border_strong())
470 .bg(theme::surface())
471 .shadow_lg()
472 .occlude()
473 .children(rows)
474 .into_any_element(),
475 )
476 }
477
478 fn render_reply_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
479 let reply = self.reply.as_ref()?;
480 Some(
481 h_flex()
482 .w_full()
483 .mb(px(6.))
484 .gap(px(10.))
485 .items_center()
486 .pl(px(10.))
487 .pr(px(4.))
488 .py(px(6.))
489 .rounded(px(8.))
490 .bg(theme::surface())
491 .border_1()
492 .border_color(theme::border())
493 .child(icon(IconName::Undo2, 14., theme::accent_text()))
494 .child(
495 v_flex()
496 .flex_1()
497 .min_w_0()
498 .child(
499 div()
500 .truncate()
501 .text_size(px(12.))
502 .font_weight(FontWeight::SEMIBOLD)
503 .text_color(theme::accent_text())
504 .child(format!("Antwort an {}", reply.author)),
505 )
506 .child(
507 div()
508 .truncate()
509 .text_size(px(12.))
510 .text_color(theme::text_muted())
511 .child(reply.excerpt.clone()),
512 ),
513 )
514 .child(
515 div()
516 .id("reply-close")
517 .size(px(24.))
518 .flex()
519 .items_center()
520 .justify_center()
521 .rounded(px(6.))
522 .cursor_pointer()
523 .hover(|button| button.bg(theme::row_hover()))
524 .child(icon(IconName::Close, 14., theme::text_muted()))
525 .on_click(cx.listener(|this, _, _, cx| this.set_reply(None, cx))),
526 ),
527 )
528 }
529}
530
531impl Render for Composer {
532 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
533 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
534 let empty = self.is_empty(cx);
535 let send = div()
536 .id("composer-send")
537 .size(px(32.))
538 .flex_none()
539 .flex()
540 .items_center()
541 .justify_center()
542 .rounded(px(8.))
543 .child(symbol("keyboard_return", 20., white()))
544 .when(empty, |button| button.opacity(0.4))
545 .when(!empty, |button| {
546 button
547 .cursor_pointer()
548 .hover(|button| button.bg(white().opacity(0.1)))
549 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
550 });
551 let input = Textarea::new(&self.input)
552 .appearance(false)
553 .bordered(false)
554 .token(|context, _, _| {
555 div()
556 .h(context.line_height())
557 .px(px(5.))
558 .rounded(px(5.))
559 .bg(if context.is_selected() {
560 theme::accent().opacity(0.4)
561 } else {
562 theme::mention_background(false)
563 })
564 .text_color(theme::mention_text())
565 .font_weight(FontWeight::SEMIBOLD)
566 .child(context.token().label().clone())
567 });
568 v_flex()
569 .w_full()
570 .flex_none()
571 .px(px(24.))
572 .pt(px(8.))
573 .pb(px(12.))
574 .capture_action(cx.listener(|this, _: &MoveUp, _, cx| {
575 if this.popup_is_open() {
576 this.move_highlight(-1, cx);
577 cx.stop_propagation();
578 }
579 }))
580 .capture_action(cx.listener(|this, _: &MoveDown, _, cx| {
581 if this.popup_is_open() {
582 this.move_highlight(1, cx);
583 cx.stop_propagation();
584 }
585 }))
586 .capture_action(cx.listener(|this, _: &Enter, window, cx| {
587 if this.popup_is_open() {
588 this.accept_mention(window, cx);
589 cx.stop_propagation();
590 }
591 }))
592 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
593 if this.popup_is_open() {
594 this.accept_mention(window, cx);
595 cx.stop_propagation();
596 }
597 }))
598 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
599 if this.popup.is_some() {
600 this.close_popup();
601 cx.notify();
602 cx.stop_propagation();
603 }
604 }))
605 .children(self.render_reply_strip(cx))
606 .child(
607 div()
608 .relative()
609 .w_full()
610 .children(self.render_popup(cx))
611 .child(
612 h_flex()
613 .w_full()
614 .items_end()
615 .gap(px(6.))
616 .py(px(6.))
617 .pl(px(12.))
618 .pr(px(6.))
619 .rounded(px(10.))
620 .bg(theme::surface())
621 .border_1()
622 .border_color(if focused {
623 theme::accent()
624 } else {
625 theme::border_strong()
626 })
627 .child(div().flex_1().min_w_0().child(input))
628 .child(send),
629 ),
630 )
631 }
632}
633
634#[cfg(test)]
635mod tests {
636 use super::{active_mention, submitted_text};
637 use gpui_kit::component::input::InputEvent;
638
639 fn press(shift: bool) -> InputEvent {
640 InputEvent::PressEnter {
641 secondary: false,
642 shift,
643 }
644 }
645
646 #[test]
647 fn enter_sends_trimmed_text() {
648 assert_eq!(
649 submitted_text(&press(false), " hello \n"),
650 Some("hello".into())
651 );
652 }
653
654 #[test]
655 fn shift_enter_never_sends() {
656 assert_eq!(submitted_text(&press(true), "hello"), None);
657 }
658
659 #[test]
660 fn blank_text_never_sends() {
661 assert_eq!(submitted_text(&press(false), " \n "), None);
662 }
663
664 #[test]
665 fn other_events_never_send() {
666 assert_eq!(submitted_text(&InputEvent::Change, "hello"), None);
667 }
668
669 #[test]
670 fn at_sign_opens_a_mention_query() {
671 assert_eq!(active_mention("hi @Ma", 6, &[]), Some((3..6, "Ma".into())));
672 assert_eq!(active_mention("@", 1, &[]), Some((0..1, String::new())));
673 }
674
675 #[test]
676 fn names_with_a_space_keep_the_query_open() {
677 assert_eq!(
678 active_mention("@Mara Lin", 9, &[]),
679 Some((0..9, "Mara Lin".into()))
680 );
681 }
682
683 #[test]
684 fn mail_addresses_and_closed_queries_do_not_open() {
685 assert_eq!(active_mention("a@b", 3, &[]), None);
686 assert_eq!(active_mention("@Mara ", 6, &[]), None);
687 assert_eq!(active_mention("@ x", 3, &[]), None);
688 assert_eq!(active_mention("@Ma\nrest", 8, &[]), None);
689 }
690
691 #[test]
692 fn text_inside_a_token_does_not_reopen() {
693 let token = 0..15;
694 assert_eq!(
695 active_mention("@Mara Lindqvist", 15, std::slice::from_ref(&token)),
696 None
697 );
698 assert_eq!(
699 active_mention("@Mara Lindqvist @Pr", 19, std::slice::from_ref(&token)),
700 Some((16..19, "Pr".into()))
701 );
702 }
703}