BlueGit

ict rusty-teams

Files

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

toast.rs

toast.rs 22.5 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 .child(styled)
181 .into_any_element()
182}
183
184fn side_chip(label: String, mention: bool) -> Div {
185 div()
186 .h(px(20.))
187 .px(px(8.))
188 .flex()
189 .items_center()
190 .rounded(px(10.))
191 .bg(if mention {
192 theme::bubble_own()
193 } else {
194 theme::border_strong()
195 })
196 .text_color(if mention {
197 theme::accent_soft()
198 } else {
199 theme::text()
200 })
201 .text_size(px(11.))
202 .line_height(px(20.))
203 .font_weight(FontWeight::SEMIBOLD)
204 .child(label)
205}
206
207impl ToastView {
208 fn avatar(&self, model: &ToastModel, fill: Hsla, cx: &App) -> AnyElement {
209 let center = self.center.read(cx);
210 let directory = center.directory(cx);
211 let sender = Face {
212 user_id: model.sender_id.clone(),
213 name: model.sender_name.clone(),
214 };
215 match &model.kind {
216 ChatKind::Group { .. } => {
217 let chat = Face {
218 user_id: None,
219 name: model.chat_title.clone(),
220 };
221 spec_avatar(
222 directory,
223 &AvatarSpec::Pair(sender, chat),
224 AVATAR_SIZE,
225 fill,
226 )
227 }
228 _ => {
229 let presence = model
230 .sender_id
231 .as_deref()
232 .map(|user_id| directory.presence_of(user_id))
233 .unwrap_or(crate::data::Presence::Live(
234 crate::data::PresenceKind::Unknown,
235 ));
236 let face = spec_avatar(directory, &AvatarSpec::Single(sender), AVATAR_SIZE, fill);
237 with_presence(face, presence, AVATAR_SIZE, fill).into_any_element()
238 }
239 }
240 }
241
242 fn side_slot(&self, model: &ToastModel, hovered: bool) -> AnyElement {
243 let id = self.id;
244 if hovered {
245 let center = self.center.clone();
246 return div()
247 .id("toast-close")
248 .size(px(CLOSE_SIZE))
249 .flex_none()
250 .flex()
251 .items_center()
252 .justify_center()
253 .rounded_full()
254 .bg(theme::border_strong())
255 .cursor_pointer()
256 .hover(|button| button.bg(theme::text_faint()))
257 .child(symbol("close", 16., theme::text()))
258 .on_click(move |_, _, cx| {
259 cx.stop_propagation();
260 center.update(cx, |center, cx| center.dismiss(id, cx));
261 })
262 .into_any_element();
263 }
264 if model.mentions_me {
265 return side_chip("Mention".to_owned(), true).into_any_element();
266 }
267 if model.count > 1 {
268 return side_chip(format!("{} new", model.count), false).into_any_element();
269 }
270 div()
271 .text_size(px(12.))
272 .text_color(theme::text_muted())
273 .child(model.time.clone())
274 .into_any_element()
275 }
276
277 fn body(&self, model: &ToastModel, text: &ToastText, hovered: bool) -> Div {
278 let subtitle_icon = match &model.kind {
279 ChatKind::Group { .. } => Some("group"),
280 ChatKind::Channel { .. } => Some("tag"),
281 ChatKind::Direct => None,
282 };
283 let preview = if text.image_only {
284 h_flex()
285 .gap(px(6.))
286 .items_center()
287 .child(symbol("image", 16., theme::text_muted()))
288 .child(
289 div()
290 .text_size(px(13.))
291 .text_color(theme::text())
292 .child(text.preview.clone()),
293 )
294 .into_any_element()
295 } else {
296 highlighted_preview(&text.preview, model.mentions_me)
297 };
298 v_flex()
299 .flex_1()
300 .min_w_0()
301 .gap(px(2.))
302 .child(
303 h_flex()
304 .w_full()
305 .h(px(20.))
306 .gap(px(8.))
307 .items_center()
308 .justify_between()
309 .child(
310 div()
311 .flex_1()
312 .min_w_0()
313 .truncate()
314 .text_size(px(14.))
315 .line_height(px(20.))
316 .font_weight(FontWeight::SEMIBOLD)
317 .text_color(theme::text())
318 .child(text.title.clone()),
319 )
320 .child(div().flex_none().child(self.side_slot(model, hovered))),
321 )
322 .child(
323 h_flex()
324 .gap(px(4.))
325 .items_center()
326 .h(px(16.))
327 .text_size(px(12.))
328 .text_color(theme::text_muted())
329 .children(subtitle_icon.map(|name| symbol(name, 14., theme::text_muted())))
330 .child(div().truncate().child(text.subtitle.clone())),
331 )
332 .child(preview)
333 }
334
335 fn action_row(&self, mention: bool, cx: &mut Context<Self>) -> Div {
336 let id = self.id;
337 let center = self.center.clone();
338 h_flex()
339 .w_full()
340 .mt(px(4.))
341 .gap(px(4.))
342 .justify_end()
343 .child(
344 flat_button("Mark as read", "done", false, mention).on_click(move |_, _, cx| {
345 cx.stop_propagation();
346 center.update(cx, |center, cx| center.mark_read(id, cx));
347 }),
348 )
349 .child(
350 flat_button("Reply", "reply", true, mention).on_click(cx.listener(
351 |this, _, window, cx| {
352 cx.stop_propagation();
353 this.open_reply(window, cx);
354 },
355 )),
356 )
357 }
358
359 fn reply_field(&self, window: &Window, cx: &mut Context<Self>) -> Stateful<Div> {
360 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
361 let empty = self.input.read(cx).value().trim().is_empty();
362 let send = div()
363 .id("toast-send")
364 .size(px(SEND_BUTTON))
365 .flex_none()
366 .flex()
367 .items_center()
368 .justify_center()
369 .rounded(px(8.))
370 .child(symbol("keyboard_return", 20., theme::text()))
371 .when(empty, |button| button.opacity(0.4))
372 .when(!empty, |button| {
373 button
374 .cursor_pointer()
375 .hover(|button| button.bg(theme::popup_hover()))
376 .on_click(cx.listener(|this, _, window, cx| {
377 cx.stop_propagation();
378 this.submit(window, cx);
379 }))
380 });
381 let hint = |keys: &'static str, action: &'static str| {
382 h_flex()
383 .gap(px(4.))
384 .child(div().text_color(theme::text_soft()).child(keys))
385 .child(action)
386 };
387 keep_clicks_in_toast(v_flex().id("toast-reply-field"))
388 .w_full()
389 .mt(px(8.))
390 .gap(px(4.))
391 .child(
392 h_flex()
393 .w_full()
394 .items_end()
395 .gap(px(6.))
396 .py(px(6.))
397 .pl(px(12.))
398 .pr(px(6.))
399 .rounded(px(10.))
400 .bg(theme::surface())
401 .border_1()
402 .border_color(if focused {
403 theme::accent()
404 } else {
405 theme::border_strong()
406 })
407 .child(
408 div()
409 .flex_1()
410 .min_w_0()
411 .child(Textarea::new(&self.input).appearance(false).bordered(false)),
412 )
413 .child(send),
414 )
415 .child(
416 h_flex()
417 .h(px(16.))
418 .gap(px(12.))
419 .justify_end()
420 .text_size(px(11.))
421 .text_color(theme::text_muted())
422 .child(hint("Enter", "send"))
423 .child(hint("Shift+Enter", "new line"))
424 .child(hint("Esc", "close")),
425 )
426 }
427
428 fn confirmation(&self, model: &ToastModel, cx: &mut Context<Self>) -> Div {
429 let sent = model.reply == ReplyState::Sent;
430 let label = if sent {
431 format!("Sent to {}", target_name(model))
432 } else {
433 "Couldn't send".to_owned()
434 };
435 let (icon_name, tone) = if sent {
436 ("check_circle", theme::green())
437 } else {
438 ("error", theme::red_soft())
439 };
440 h_flex()
441 .size_full()
442 .gap(px(10.))
443 .items_center()
444 .child(symbol(icon_name, 22., tone))
445 .child(
446 div()
447 .flex_1()
448 .min_w_0()
449 .truncate()
450 .text_size(px(14.))
451 .font_weight(FontWeight::SEMIBOLD)
452 .text_color(theme::text())
453 .child(label),
454 )
455 .when(sent, |row| {
456 row.child(
457 div()
458 .text_size(px(12.))
459 .text_color(theme::text_muted())
460 .child(model.time.clone()),
461 )
462 })
463 .when(!sent, |row| {
464 row.child(
465 flat_button("Retry", "reply", true, false).on_click(cx.listener(
466 |this, _, _, cx| {
467 cx.stop_propagation();
468 this.retry(cx);
469 },
470 )),
471 )
472 })
473 }
474}
475
476fn target_name(model: &ToastModel) -> String {
477 match &model.kind {
478 ChatKind::Group { .. } => model.chat_title.clone(),
479 _ => model.sender_name.clone(),
480 }
481}
482
483impl Render for ToastView {
484 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
485 let id = self.id;
486 let (model, preview_on) = {
487 let center = self.center.read(cx);
488 (center.model(id).cloned(), center.settings().account.show_preview)
489 };
490 let Some(model) = model else {
491 return div().size_full().bg(theme::popup()).into_any_element();
492 };
493 let text = describe(&model, preview_on);
494 let narration = model
495 .agent
496 .as_ref()
497 .map_or_else(|| text.narration(), |agent| agent.title.clone());
498 if narration != self.last_title {
499 window.set_window_title(&narration);
500 self.last_title = narration;
501 }
502 let mention = model.mentions_me;
503 let fill = if mention {
504 theme::toast_mention_fill()
505 } else {
506 theme::popup()
507 };
508 let hovered = model.hovered;
509 let content = match model.reply {
510 _ if model.agent.is_some() => {
511 let agent = model.agent.as_ref().expect("checked above");
512 agent_toast_content(&self.center, id, agent, hovered)
513 }
514 ReplyState::Sent | ReplyState::Failed => self.confirmation(&model, cx),
515 ReplyState::Open => v_flex()
516 .w_full()
517 .child(
518 h_flex()
519 .w_full()
520 .gap(px(AVATAR_GAP))
521 .items_start()
522 .child(self.avatar(&model, fill, cx))
523 .child(self.body(&model, &text, true)),
524 )
525 .child(self.reply_field(window, cx)),
526 ReplyState::Closed => v_flex()
527 .w_full()
528 .child(
529 h_flex()
530 .w_full()
531 .gap(px(AVATAR_GAP))
532 .items_start()
533 .child(self.avatar(&model, fill, cx))
534 .child(self.body(&model, &text, hovered)),
535 )
536 .child(self.action_row(mention, cx)),
537 };
538 let center = self.center.clone();
539 let hover_center = self.center.clone();
540 div()
541 .id(("toast", id))
542 .track_focus(&self.focus_handle)
543 .relative()
544 .size_full()
545 .opacity(model.opacity(Instant::now()))
546 .rounded(toast_radius(window))
547 .bg(fill)
548 .overflow_hidden()
549 .cursor_pointer()
550 .on_hover(move |is_hovered, _, cx| {
551 hover_center.update(cx, |center, cx| center.set_hover(id, *is_hovered, cx));
552 })
553 .on_click(move |_, _, cx| {
554 center.update(cx, |center, cx| center.activate(id, cx));
555 })
556 .capture_action(cx.listener(
557 |this, _: &gpui_kit::component::input::Escape, window, cx| {
558 this.close_reply(window, cx);
559 cx.stop_propagation();
560 },
561 ))
562 .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {
563 if event.keystroke.key == "escape" {
564 let id = this.id;
565 this.center.update(cx, |center, cx| center.dismiss(id, cx));
566 }
567 }))
568 .child(div().size_full().p(px(TOAST_PADDING)).child(content))
569 .into_any_element()
570 }
571}
572
573pub struct PillView {
574 center: Entity<NotificationCenter>,
575 _subscription: Subscription,
576}
577
578impl PillView {
579 pub fn new(center: Entity<NotificationCenter>, cx: &mut Context<Self>) -> Self {
580 let subscription = cx.observe(&center, |_, _, cx| cx.notify());
581 PillView {
582 center,
583 _subscription: subscription,
584 }
585 }
586}
587
588impl Render for PillView {
589 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
590 let (queued, opacity) = {
591 let center = self.center.read(cx);
592 (center.queued_count(), center.stack_opacity())
593 };
594 let center = self.center.clone();
595 h_flex()
596 .id("toast-hide-all")
597 .size_full()
598 .gap(px(6.))
599 .items_center()
600 .justify_center()
601 .opacity(opacity)
602 .rounded(toast_radius(window))
603 .bg(theme::popup())
604 .cursor_pointer()
605 .hover(|bar| bar.bg(theme::popup_hover()))
606 .text_size(px(12.5))
607 .font_weight(FontWeight::SEMIBOLD)
608 .text_color(theme::text_soft())
609 .child("Hide all")
610 .when(queued > 0, |bar| {
611 bar.child(
612 div()
613 .text_color(theme::text_muted())
614 .child(format!("{queued} more waiting")),
615 )
616 })
617 .on_click(move |_, _, cx| {
618 center.update(cx, |center, cx| center.hide_all(cx));
619 })
620 }
621}
622
623#[cfg(test)]
624mod tests {
625 use std::cell::Cell;
626 use std::rc::Rc;
627
628 use gpui_kit::component::input::{Textarea, TextareaState};
629 use gpui_kit::{
630 AppContext as _, Context, Entity, Focusable as _, InteractiveElement as _, IntoElement,
631 Modifiers, ParentElement as _, Render, StatefulInteractiveElement as _, Styled as _,
632 TestAppContext, Window, div, point, px,
633 };
634
635 use super::keep_clicks_in_toast;
636
637 struct ToastHarness {
638 input: Entity<TextareaState>,
639 card_clicks: Rc<Cell<usize>>,
640 }
641
642 impl Render for ToastHarness {
643 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
644 let card_clicks = self.card_clicks.clone();
645 div()
646 .id("toast-card")
647 .size_full()
648 .on_click(move |_, _, _| card_clicks.set(card_clicks.get() + 1))
649 .child(
650 keep_clicks_in_toast(div().id("toast-reply-field"))
651 .w(px(300.))
652 .child(Textarea::new(&self.input)),
653 )
654 }
655 }
656
657 #[gpui_kit::test]
658 fn clicking_the_reply_input_does_not_open_the_chat(cx: &mut TestAppContext) {
659 cx.update(gpui_kit::init);
660 let card_clicks = Rc::new(Cell::new(0));
661 let (harness, window_cx) = cx.add_window_view({
662 let card_clicks = card_clicks.clone();
663 move |window, cx| ToastHarness {
664 input: cx.new(|cx| TextareaState::new(window, cx).auto_grow(1, 1)),
665 card_clicks,
666 }
667 });
668 window_cx.update(|window, cx| window.draw(cx).clear(cx));
669 window_cx.simulate_click(point(px(20.), px(12.)), Modifiers::default());
670 assert_eq!(card_clicks.get(), 0);
671 let focused = window_cx.update(|window, cx| {
672 let input = harness.read(cx).input.clone();
673 input.focus_handle(cx).contains_focused(window, cx)
674 });
675 assert!(focused);
676 window_cx.simulate_click(point(px(20.), px(200.)), Modifiers::default());
677 assert_eq!(card_clicks.get(), 1);
678 }
679}