BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / notify / toast.rs

toast.rs

toast.rs 22.6 KiB Download Raw
1use std::time::Instant;
2
3use gpui_kit::component::{
4 h_flex,
5 input::{InputEvent, Textarea, TextareaState},
6 v_flex,
7};
8use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::*;
10
11use super::agent_toast::agent_toast_content;
12use super::center::NotificationCenter;
13use super::layout::{
14 ACTION_BUTTON, AVATAR_GAP, AVATAR_SIZE, PREVIEW_MAX_LINES, PREVIEW_SIZE, SEND_BUTTON,
15 TOAST_PADDING,
16};
17use super::platform;
18use super::ring_view::toast_radius;
19use super::rules::ChatKind;
20use super::stack::{ReplyState, ToastModel};
21use super::text::{ToastText, describe, mention_ranges};
22use crate::sidebar_model::{AvatarSpec, Face};
23use crate::theme;
24use crate::views::avatar::{spec_avatar, with_presence};
25use crate::views::composer::submitted_text;
26use crate::views::widgets::symbol;
27
28const CLOSE_SIZE: f32 = 24.;
29
30pub struct ToastView {
31 center: Entity<NotificationCenter>,
32 id: u64,
33 input: Entity<TextareaState>,
34 focus_handle: FocusHandle,
35 last_title: String,
36 _subscriptions: Vec<Subscription>,
37}
38
39impl ToastView {
40 pub fn new(
41 center: Entity<NotificationCenter>,
42 id: u64,
43 window: &mut Window,
44 cx: &mut Context<Self>,
45 ) -> Self {
46 let input = cx.new(|cx| {
47 TextareaState::new(window, cx)
48 .auto_grow(1, 1)
49 .submit_on_enter(true)
50 .placeholder("Reply ...")
51 });
52 let subscriptions = vec![
53 cx.subscribe_in(
54 &input,
55 window,
56 |this, input, event: &InputEvent, window, cx| {
57 let value = input.read(cx).value();
58 if submitted_text(event, &value).is_some() {
59 this.submit(window, cx);
60 }
61 },
62 ),
63 cx.observe(&center, |_, _, cx| cx.notify()),
64 ];
65 ToastView {
66 center,
67 id,
68 input,
69 focus_handle: cx.focus_handle(),
70 last_title: String::new(),
71 _subscriptions: subscriptions,
72 }
73 }
74
75 fn submit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
76 let text = self.input.read(cx).value().trim().to_owned();
77 if text.is_empty() {
78 return;
79 }
80 self.input
81 .update(cx, |state, cx| state.set_value("", window, cx));
82 let id = self.id;
83 self.center
84 .update(cx, |center, cx| center.submit_reply(id, text, cx));
85 }
86
87 fn open_reply(&mut self, window: &mut Window, cx: &mut Context<Self>) {
88 let id = self.id;
89 let draft = self
90 .center
91 .update(cx, |center, cx| center.open_reply(id, cx));
92 if let Some(native) = platform::native_handle(window) {
93 platform::set_activatable(native, true);
94 }
95 let input = self.input.clone();
96 cx.defer_in(window, move |_, window, cx| {
97 input.update(cx, |state, cx| {
98 if let Some(draft) = draft.filter(|draft| !draft.is_empty()) {
99 state.set_value(&draft, window, cx);
100 }
101 state.focus(window, cx);
102 });
103 });
104 }
105
106 fn close_reply(&mut self, window: &mut Window, cx: &mut Context<Self>) {
107 self.input
108 .update(cx, |state, cx| state.set_value("", window, cx));
109 let id = self.id;
110 self.center
111 .update(cx, |center, cx| center.close_reply(id, cx));
112 window.focus(&self.focus_handle, cx);
113 }
114
115 fn retry(&mut self, cx: &mut Context<Self>) {
116 let id = self.id;
117 self.center.update(cx, |center, cx| {
118 if let Some(text) = center.reply_text(id) {
119 center.submit_reply(id, text, cx);
120 }
121 });
122 }
123}
124
125fn flat_button(
126 label: &'static str,
127 symbol_name: &'static str,
128 accent: bool,
129 mention: bool,
130) -> Stateful<Div> {
131 let color = if accent {
132 theme::accent_text()
133 } else {
134 theme::text_soft()
135 };
136 let hover_fill = if mention {
137 theme::bubble_own()
138 } else {
139 theme::border_strong()
140 };
141 h_flex()
142 .id(label)
143 .h(px(ACTION_BUTTON))
144 .px(px(10.))
145 .gap(px(6.))
146 .items_center()
147 .rounded(px(6.))
148 .cursor_pointer()
149 .text_size(px(12.5))
150 .font_weight(FontWeight::SEMIBOLD)
151 .text_color(color)
152 .hover(move |button| button.bg(hover_fill))
153 .child(symbol(symbol_name, 15., color))
154 .child(label)
155}
156
157fn keep_clicks_in_toast(area: Stateful<Div>) -> Stateful<Div> {
158 area.on_click(|_, _, cx| cx.stop_propagation())
159}
160
161fn highlighted_preview(text: &str, mention: bool) -> AnyElement {
162 let mut styled = StyledText::new(text.to_owned());
163 if mention {
164 let style = HighlightStyle {
165 color: Some(theme::accent_soft()),
166 font_weight: Some(FontWeight::SEMIBOLD),
167 ..Default::default()
168 };
169 let highlights: Vec<_> = mention_ranges(text)
170 .into_iter()
171 .map(|range| (range, style))
172 .collect();
173 styled = styled.with_highlights(highlights);
174 }
175 div()
176 .text_size(px(PREVIEW_SIZE))
177 .line_height(px(18.))
178 .text_color(theme::text())
179 .line_clamp(PREVIEW_MAX_LINES)
180 .text_ellipsis()
181 .child(styled)
182 .into_any_element()
183}
184
185fn side_chip(label: String, mention: bool) -> Div {
186 div()
187 .h(px(20.))
188 .px(px(8.))
189 .flex()
190 .items_center()
191 .rounded(px(10.))
192 .bg(if mention {
193 theme::bubble_own()
194 } else {
195 theme::border_strong()
196 })
197 .text_color(if mention {
198 theme::accent_soft()
199 } else {
200 theme::text()
201 })
202 .text_size(px(11.))
203 .line_height(px(20.))
204 .font_weight(FontWeight::SEMIBOLD)
205 .child(label)
206}
207
208impl ToastView {
209 fn avatar(&self, model: &ToastModel, fill: Hsla, cx: &App) -> AnyElement {
210 let center = self.center.read(cx);
211 let directory = center.directory(cx);
212 let sender = Face {
213 user_id: model.sender_id.clone(),
214 name: model.sender_name.clone(),
215 };
216 match &model.kind {
217 ChatKind::Group { .. } => {
218 let chat = Face {
219 user_id: None,
220 name: model.chat_title.clone(),
221 };
222 spec_avatar(
223 directory,
224 &AvatarSpec::Pair(sender, chat),
225 AVATAR_SIZE,
226 fill,
227 )
228 }
229 _ => {
230 let presence = model
231 .sender_id
232 .as_deref()
233 .map(|user_id| directory.presence_of(user_id))
234 .unwrap_or(crate::data::Presence::Live(
235 crate::data::PresenceKind::Unknown,
236 ));
237 let face = spec_avatar(directory, &AvatarSpec::Single(sender), AVATAR_SIZE, fill);
238 with_presence(face, presence, AVATAR_SIZE, fill).into_any_element()
239 }
240 }
241 }
242
243 fn side_slot(&self, model: &ToastModel, hovered: bool) -> AnyElement {
244 let id = self.id;
245 if hovered {
246 let center = self.center.clone();
247 return div()
248 .id("toast-close")
249 .size(px(CLOSE_SIZE))
250 .flex_none()
251 .flex()
252 .items_center()
253 .justify_center()
254 .rounded_full()
255 .bg(theme::border_strong())
256 .cursor_pointer()
257 .hover(|button| button.bg(theme::text_faint()))
258 .child(symbol("close", 16., theme::text()))
259 .on_click(move |_, _, cx| {
260 cx.stop_propagation();
261 center.update(cx, |center, cx| center.dismiss(id, cx));
262 })
263 .into_any_element();
264 }
265 if model.mentions_me {
266 return side_chip("Mention".to_owned(), true).into_any_element();
267 }
268 if model.count > 1 {
269 return side_chip(format!("{} new", model.count), false).into_any_element();
270 }
271 div()
272 .text_size(px(12.))
273 .text_color(theme::text_muted())
274 .child(model.time.clone())
275 .into_any_element()
276 }
277
278 fn body(&self, model: &ToastModel, text: &ToastText, hovered: bool) -> Div {
279 let subtitle_icon = match &model.kind {
280 ChatKind::Group { .. } => Some("group"),
281 ChatKind::Channel { .. } => Some("tag"),
282 ChatKind::Direct => None,
283 };
284 let preview = if text.image_only {
285 h_flex()
286 .gap(px(6.))
287 .items_center()
288 .child(symbol("image", 16., theme::text_muted()))
289 .child(
290 div()
291 .text_size(px(13.))
292 .text_color(theme::text())
293 .child(text.preview.clone()),
294 )
295 .into_any_element()
296 } else {
297 highlighted_preview(&text.preview, model.mentions_me)
298 };
299 v_flex()
300 .flex_1()
301 .min_w_0()
302 .gap(px(2.))
303 .child(
304 h_flex()
305 .w_full()
306 .h(px(20.))
307 .gap(px(8.))
308 .items_center()
309 .justify_between()
310 .child(
311 div()
312 .flex_1()
313 .min_w_0()
314 .truncate()
315 .text_size(px(14.))
316 .line_height(px(20.))
317 .font_weight(FontWeight::SEMIBOLD)
318 .text_color(theme::text())
319 .child(text.title.clone()),
320 )
321 .child(div().flex_none().child(self.side_slot(model, hovered))),
322 )
323 .child(
324 h_flex()
325 .gap(px(4.))
326 .items_center()
327 .h(px(16.))
328 .text_size(px(12.))
329 .text_color(theme::text_muted())
330 .children(subtitle_icon.map(|name| symbol(name, 14., theme::text_muted())))
331 .child(div().truncate().child(text.subtitle.clone())),
332 )
333 .child(preview)
334 }
335
336 fn action_row(&self, mention: bool, cx: &mut Context<Self>) -> Div {
337 let id = self.id;
338 let center = self.center.clone();
339 h_flex()
340 .w_full()
341 .mt(px(4.))
342 .gap(px(4.))
343 .justify_end()
344 .child(
345 flat_button("Mark as read", "done", false, mention).on_click(move |_, _, cx| {
346 cx.stop_propagation();
347 center.update(cx, |center, cx| center.mark_read(id, cx));
348 }),
349 )
350 .child(
351 flat_button("Reply", "reply", true, mention).on_click(cx.listener(
352 |this, _, window, cx| {
353 cx.stop_propagation();
354 this.open_reply(window, cx);
355 },
356 )),
357 )
358 }
359
360 fn reply_field(&self, window: &Window, cx: &mut Context<Self>) -> Stateful<Div> {
361 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
362 let empty = self.input.read(cx).value().trim().is_empty();
363 let send = div()
364 .id("toast-send")
365 .size(px(SEND_BUTTON))
366 .flex_none()
367 .flex()
368 .items_center()
369 .justify_center()
370 .rounded(px(8.))
371 .child(symbol("send", 20., theme::text()))
372 .when(empty, |button| button.opacity(0.4))
373 .when(!empty, |button| {
374 button
375 .cursor_pointer()
376 .hover(|button| button.bg(theme::popup_hover()))
377 .on_click(cx.listener(|this, _, window, cx| {
378 cx.stop_propagation();
379 this.submit(window, cx);
380 }))
381 });
382 let hint = |keys: &'static str, action: &'static str| {
383 h_flex()
384 .gap(px(4.))
385 .child(div().text_color(theme::text_soft()).child(keys))
386 .child(action)
387 };
388 keep_clicks_in_toast(v_flex().id("toast-reply-field"))
389 .w_full()
390 .mt(px(8.))
391 .gap(px(4.))
392 .child(
393 h_flex()
394 .w_full()
395 .items_end()
396 .gap(px(6.))
397 .py(px(6.))
398 .pl(px(12.))
399 .pr(px(6.))
400 .rounded(px(10.))
401 .bg(theme::surface())
402 .border_1()
403 .border_color(if focused {
404 theme::accent()
405 } else {
406 theme::border_strong()
407 })
408 .child(
409 div()
410 .flex_1()
411 .min_w_0()
412 .child(Textarea::new(&self.input).appearance(false).bordered(false)),
413 )
414 .child(send),
415 )
416 .child(
417 h_flex()
418 .h(px(16.))
419 .gap(px(12.))
420 .justify_end()
421 .text_size(px(11.))
422 .text_color(theme::text_muted())
423 .child(hint("Enter", "send"))
424 .child(hint("Shift+Enter", "new line"))
425 .child(hint("Esc", "close")),
426 )
427 }
428
429 fn confirmation(&self, model: &ToastModel, cx: &mut Context<Self>) -> Div {
430 let sent = model.reply == ReplyState::Sent;
431 let label = if sent {
432 format!("Sent to {}", target_name(model))
433 } else {
434 "Couldn't send".to_owned()
435 };
436 let (icon_name, tone) = if sent {
437 ("check_circle", theme::green())
438 } else {
439 ("error", theme::red_soft())
440 };
441 h_flex()
442 .size_full()
443 .gap(px(10.))
444 .items_center()
445 .child(symbol(icon_name, 22., tone))
446 .child(
447 div()
448 .flex_1()
449 .min_w_0()
450 .truncate()
451 .text_size(px(14.))
452 .font_weight(FontWeight::SEMIBOLD)
453 .text_color(theme::text())
454 .child(label),
455 )
456 .when(sent, |row| {
457 row.child(
458 div()
459 .text_size(px(12.))
460 .text_color(theme::text_muted())
461 .child(model.time.clone()),
462 )
463 })
464 .when(!sent, |row| {
465 row.child(
466 flat_button("Retry", "reply", true, false).on_click(cx.listener(
467 |this, _, _, cx| {
468 cx.stop_propagation();
469 this.retry(cx);
470 },
471 )),
472 )
473 })
474 }
475}
476
477fn target_name(model: &ToastModel) -> String {
478 match &model.kind {
479 ChatKind::Group { .. } => model.chat_title.clone(),
480 _ => model.sender_name.clone(),
481 }
482}
483
484impl Render for ToastView {
485 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
486 let id = self.id;
487 let (model, preview_on) = {
488 let center = self.center.read(cx);
489 (
490 center.model(id).cloned(),
491 center.settings().account.show_preview,
492 )
493 };
494 let Some(model) = model else {
495 return div().size_full().bg(theme::popup()).into_any_element();
496 };
497 let text = describe(&model, preview_on);
498 let narration = model
499 .agent
500 .as_ref()
501 .map_or_else(|| text.narration(), |agent| agent.title.clone());
502 if narration != self.last_title {
503 window.set_window_title(&narration);
504 self.last_title = narration;
505 }
506 let mention = model.mentions_me;
507 let fill = if mention {
508 theme::toast_mention_fill()
509 } else {
510 theme::popup()
511 };
512 let hovered = model.hovered;
513 let content = match model.reply {
514 _ if model.agent.is_some() => {
515 let agent = model.agent.as_ref().expect("checked above");
516 agent_toast_content(&self.center, id, agent, hovered)
517 }
518 ReplyState::Sent | ReplyState::Failed => self.confirmation(&model, cx),
519 ReplyState::Open => v_flex()
520 .w_full()
521 .child(
522 h_flex()
523 .w_full()
524 .gap(px(AVATAR_GAP))
525 .items_start()
526 .child(self.avatar(&model, fill, cx))
527 .child(self.body(&model, &text, true)),
528 )
529 .child(self.reply_field(window, cx)),
530 ReplyState::Closed => v_flex()
531 .w_full()
532 .child(
533 h_flex()
534 .w_full()
535 .gap(px(AVATAR_GAP))
536 .items_start()
537 .child(self.avatar(&model, fill, cx))
538 .child(self.body(&model, &text, hovered)),
539 )
540 .when(!model.status_change && model.org.is_none(), |content| {
541 content.child(self.action_row(mention, cx))
542 }),
543 };
544 let center = self.center.clone();
545 let hover_center = self.center.clone();
546 div()
547 .id(("toast", id))
548 .track_focus(&self.focus_handle)
549 .relative()
550 .size_full()
551 .opacity(model.opacity(Instant::now()))
552 .rounded(toast_radius(window))
553 .bg(fill)
554 .overflow_hidden()
555 .cursor_pointer()
556 .on_hover(move |is_hovered, _, cx| {
557 hover_center.update(cx, |center, cx| center.set_hover(id, *is_hovered, cx));
558 })
559 .on_click(move |_, _, cx| {
560 center.update(cx, |center, cx| center.activate(id, cx));
561 })
562 .capture_action(cx.listener(
563 |this, _: &gpui_kit::component::input::Escape, window, cx| {
564 this.close_reply(window, cx);
565 cx.stop_propagation();
566 },
567 ))
568 .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {
569 if event.keystroke.key == "escape" {
570 let id = this.id;
571 this.center.update(cx, |center, cx| center.dismiss(id, cx));
572 }
573 }))
574 .child(div().size_full().p(px(TOAST_PADDING)).child(content))
575 .into_any_element()
576 }
577}
578
579pub struct PillView {
580 center: Entity<NotificationCenter>,
581 _subscription: Subscription,
582}
583
584impl PillView {
585 pub fn new(center: Entity<NotificationCenter>, cx: &mut Context<Self>) -> Self {
586 let subscription = cx.observe(&center, |_, _, cx| cx.notify());
587 PillView {
588 center,
589 _subscription: subscription,
590 }
591 }
592}
593
594impl Render for PillView {
595 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
596 let (queued, opacity) = {
597 let center = self.center.read(cx);
598 (center.queued_count(), center.stack_opacity())
599 };
600 let center = self.center.clone();
601 h_flex()
602 .id("toast-hide-all")
603 .size_full()
604 .gap(px(6.))
605 .items_center()
606 .justify_center()
607 .opacity(opacity)
608 .rounded(toast_radius(window))
609 .bg(theme::popup())
610 .cursor_pointer()
611 .hover(|bar| bar.bg(theme::popup_hover()))
612 .text_size(px(12.5))
613 .font_weight(FontWeight::SEMIBOLD)
614 .text_color(theme::text_soft())
615 .child("Hide all")
616 .when(queued > 0, |bar| {
617 bar.child(
618 div()
619 .text_color(theme::text_muted())
620 .child(format!("{queued} more waiting")),
621 )
622 })
623 .on_click(move |_, _, cx| {
624 center.update(cx, |center, cx| center.hide_all(cx));
625 })
626 }
627}
628
629#[cfg(test)]
630mod tests {
631 use std::cell::Cell;
632 use std::rc::Rc;
633
634 use gpui_kit::component::input::{Textarea, TextareaState};
635 use gpui_kit::{
636 AppContext as _, Context, Entity, Focusable as _, InteractiveElement as _, IntoElement,
637 Modifiers, ParentElement as _, Render, StatefulInteractiveElement as _, Styled as _,
638 TestAppContext, Window, div, point, px,
639 };
640
641 use super::keep_clicks_in_toast;
642
643 struct ToastHarness {
644 input: Entity<TextareaState>,
645 card_clicks: Rc<Cell<usize>>,
646 }
647
648 impl Render for ToastHarness {
649 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
650 let card_clicks = self.card_clicks.clone();
651 div()
652 .id("toast-card")
653 .size_full()
654 .on_click(move |_, _, _| card_clicks.set(card_clicks.get() + 1))
655 .child(
656 keep_clicks_in_toast(div().id("toast-reply-field"))
657 .w(px(300.))
658 .child(Textarea::new(&self.input)),
659 )
660 }
661 }
662
663 #[gpui_kit::test]
664 fn clicking_the_reply_input_does_not_open_the_chat(cx: &mut TestAppContext) {
665 cx.update(gpui_kit::init);
666 let card_clicks = Rc::new(Cell::new(0));
667 let (harness, window_cx) = cx.add_window_view({
668 let card_clicks = card_clicks.clone();
669 move |window, cx| ToastHarness {
670 input: cx.new(|cx| TextareaState::new(window, cx).auto_grow(1, 1)),
671 card_clicks,
672 }
673 });
674 window_cx.update(|window, cx| window.draw(cx).clear(cx));
675 window_cx.simulate_click(point(px(20.), px(12.)), Modifiers::default());
676 assert_eq!(card_clicks.get(), 0);
677 let focused = window_cx.update(|window, cx| {
678 let input = harness.read(cx).input.clone();
679 input.focus_handle(cx).contains_focused(window, cx)
680 });
681 assert!(focused);
682 window_cx.simulate_click(point(px(20.), px(200.)), Modifiers::default());
683 assert_eq!(card_clicks.get(), 1);
684 }
685}