gpui-material-components 0.3.1

Material 3 Expressive desktop components for GPUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
use std::{cell::Cell, collections::VecDeque, rc::Rc, time::Duration};

use crate::SemanticTone;
use crate::motion::{OverlayMotion, ScaledOverlay};
use gpui::{
    AnyElement, App, ClickEvent, Context, EntityId, FocusHandle, Hsla, InteractiveElement,
    IntoElement, KeyDownEvent, ParentElement, Render, Role, SharedString,
    StatefulInteractiveElement, Styled, Subscription, Task, WeakFocusHandle, Window, canvas, div,
    point, prelude::FluentBuilder, px,
};
use gpui_base::TestSupportExt as _;
use gpui_material_foundation::{color, current_material_theme, elevation_shadows};
use gpui_material_theme::{ColorRole, CornerShape, Direction, Elevation, TypeRole};

const MAX_WIDTH: gpui::Pixels = px(672.);
const MAX_EXITING: usize = 4;

type Action = Rc<dyn Fn(&mut Window, &mut App)>;
type Content = Box<dyn Fn(&mut Window, &mut App) -> AnyElement>;
type Completion = Rc<dyn Fn(SnackbarResult, &mut Window, &mut App)>;
type HostRenderer = Box<dyn Fn(&Snackbar, SnackbarParts, &mut Window, &mut App) -> AnyElement>;

/// How a current snackbar left its host's queue.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SnackbarResult {
    ActionPerformed,
    Dismissed,
}

/// An entry in one snackbar host's queue.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct SnackbarId {
    host: EntityId,
    sequence: usize,
}

/// Optional per-region colors. Omitted fields use the window's inverse palette.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct SnackbarColors {
    pub container: Option<Hsla>,
    pub content: Option<Hsla>,
    pub action: Option<Hsla>,
    pub dismiss: Option<Hsla>,
}

/// Host-owned status and activation elements for a custom layout.
#[non_exhaustive]
pub struct SnackbarParts {
    pub message: AnyElement,
    pub action: Option<AnyElement>,
    pub dismiss: Option<AnyElement>,
    /// Scale to apply to dimensions in the custom container.
    pub scale: f32,
}

/// A message for a window's snackbar queue. The default timeout is four seconds.
pub struct Snackbar {
    message: SharedString,
    timeout: Option<Duration>,
    action: Option<(SharedString, Action)>,
    message_content: Option<Content>,
    action_content: Option<Content>,
    dismiss_label: Option<SharedString>,
    dismiss_content: Option<(SharedString, Content)>,
    show_dismiss: bool,
    action_on_new_line: bool,
    shape: CornerShape,
    tone: SemanticTone,
    colors: SnackbarColors,
    on_dismiss: Option<Action>,
    on_result: Option<Completion>,
}

impl Snackbar {
    pub fn new(message: impl Into<SharedString>) -> Self {
        Self {
            message: message.into(),
            timeout: Some(Duration::from_secs(4)),
            action: None,
            message_content: None,
            action_content: None,
            dismiss_label: None,
            dismiss_content: None,
            show_dismiss: true,
            action_on_new_line: false,
            shape: CornerShape::Radii([4.; 4]),
            tone: SemanticTone::Default,
            colors: SnackbarColors::default(),
            on_dismiss: None,
            on_result: None,
        }
    }

    /// Sets how long the message is visible. `None` waits for explicit dismissal.
    pub fn timeout(mut self, timeout: Option<Duration>) -> Self {
        self.timeout = timeout;
        self
    }

    /// Adds a keyboard-accessible action. By default, messages with an action
    /// persist. Call `timeout` after this method to set a duration explicitly.
    pub fn action(
        mut self,
        label: impl Into<SharedString>,
        action: impl Fn(&mut Window, &mut App) + 'static,
    ) -> Self {
        self.action = Some((label.into(), Rc::new(action)));
        self.timeout = None;
        self
    }

    /// Returns the plain message used as the status announcement.
    pub fn message(&self) -> &SharedString {
        &self.message
    }

    /// Returns the accessible name of the optional action.
    pub fn action_label(&self) -> Option<&SharedString> {
        self.action.as_ref().map(|(label, _)| label)
    }

    /// Replaces the visible message with repeatable decorative content.
    pub fn message_content<E: IntoElement>(
        mut self,
        content: impl Fn(&mut Window, &mut App) -> E + 'static,
    ) -> Self {
        self.message_content = Some(Box::new(move |window, cx| {
            content(window, cx).into_any_element()
        }));
        self
    }

    /// Replaces the visible content of the named action supplied by [`Self::action`].
    pub fn action_content<E: IntoElement>(
        mut self,
        content: impl Fn(&mut Window, &mut App) -> E + 'static,
    ) -> Self {
        self.action_content = Some(Box::new(move |window, cx| {
            content(window, cx).into_any_element()
        }));
        self
    }

    /// Overrides the accessible name of the default dismiss button (default `"Dismiss message"`).
    pub fn dismiss_label(mut self, label: impl Into<SharedString>) -> Self {
        self.dismiss_label = Some(label.into());
        self
    }

    /// Supplies the accessible name and decorative content of the close affordance.
    pub fn dismiss_content<E: IntoElement>(
        mut self,
        label: impl Into<SharedString>,
        content: impl Fn(&mut Window, &mut App) -> E + 'static,
    ) -> Self {
        self.dismiss_content = Some((
            label.into(),
            Box::new(move |window, cx| content(window, cx).into_any_element()),
        ));
        self
    }

    /// Shows or hides the explicit dismiss button. It is shown by default.
    pub fn show_dismiss(mut self, show: bool) -> Self {
        self.show_dismiss = show;
        self
    }

    /// Places the action below the message for a long action label.
    pub fn action_on_new_line(mut self, enabled: bool) -> Self {
        self.action_on_new_line = enabled;
        self
    }

    pub fn shape(mut self, shape: CornerShape) -> Self {
        self.shape = shape;
        self
    }

    /// Applies a Material 3 semantic tone shortcut.
    ///
    /// [`SemanticTone::Default`] keeps the M3 inverse palette; semantic tones
    /// use `(Container, OnContainer, Role)` while explicit [`Self::colors`]
    /// overrides still take precedence.
    pub fn tone(mut self, tone: SemanticTone) -> Self {
        self.tone = tone;
        self
    }

    pub fn colors(mut self, colors: SnackbarColors) -> Self {
        self.colors = colors;
        self
    }

    /// Runs on timeout, user dismissal, or explicit dismissal by the caller.
    pub fn on_dismiss(mut self, dismissed: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_dismiss = Some(Rc::new(dismissed));
        self
    }

    /// Receives one completion after any action or dismissal callback has run.
    pub fn on_result(
        mut self,
        complete: impl Fn(SnackbarResult, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_result = Some(Rc::new(complete));
        self
    }
}

struct Entry {
    id: SnackbarId,
    message: Snackbar,
    controls: [FocusHandle; 2],
    return_focus: Option<WeakFocusHandle>,
}

/// One FIFO message queue per host. Mount the entity in the window layout.
/// A new message leaves keyboard focus wherever it is.
#[derive(Default)]
pub struct SnackbarHost {
    active: Option<Entry>,
    exiting: Vec<Entry>,
    pending: VecDeque<(SnackbarId, Snackbar)>,
    next_id: usize,
    timer: Option<Task<()>>,
    hovered: bool,
    focused: bool,
    _focus_subscriptions: Vec<Subscription>,
    renderer: Option<HostRenderer>,
}

impl SnackbarHost {
    /// Uses a custom container and layout for the host-owned message and controls.
    pub fn renderer<E: IntoElement>(
        mut self,
        render: impl Fn(&Snackbar, SnackbarParts, &mut Window, &mut App) -> E + 'static,
    ) -> Self {
        self.renderer = Some(Box::new(move |message, parts, window, cx| {
            render(message, parts, window, cx).into_any_element()
        }));
        self
    }

    /// Queues the message after any already pending messages.
    pub fn push(&mut self, snackbar: Snackbar, window: &mut Window, cx: &mut Context<Self>) {
        self.enqueue(snackbar, window, cx);
    }

    /// Queues a plain message snackbar and returns its opaque identity.
    pub fn push_message(
        &mut self,
        message: impl Into<SharedString>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> SnackbarId {
        self.enqueue(Snackbar::new(message), window, cx)
    }

    /// Dismisses the currently active snackbar (if any, firing its dismissal
    /// completion cleanly) and immediately presents the new snackbar ahead of
    /// any pending entries.
    pub fn replace(
        &mut self,
        snackbar: Snackbar,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> SnackbarId {
        self.next_id += 1;
        let id = SnackbarId {
            host: cx.entity_id(),
            sequence: self.next_id,
        };
        self.pending.push_front((id, snackbar));
        if let Some((active_id, _)) = self.current() {
            self.finish(active_id, SnackbarResult::Dismissed, window, cx);
        } else {
            self.show_next(window, cx);
        }
        id
    }

    /// Queues the message and returns an opaque identity scoped to this host.
    pub fn enqueue(
        &mut self,
        snackbar: Snackbar,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> SnackbarId {
        self.next_id += 1;
        let id = SnackbarId {
            host: cx.entity_id(),
            sequence: self.next_id,
        };
        self.pending.push_back((id, snackbar));
        if self.active.is_none() {
            self.show_next(window, cx);
        }
        id
    }

    /// Returns the active entry. Pending and exiting entries are excluded.
    pub fn current(&self) -> Option<(SnackbarId, &Snackbar)> {
        self.active.as_ref().map(|entry| (entry.id, &entry.message))
    }

    /// Returns the number of queued snackbars waiting behind the active entry.
    pub fn pending_len(&self) -> usize {
        self.pending.len()
    }

    /// Discards all queued snackbars waiting behind the active entry without
    /// disturbing the currently visible snackbar.
    pub fn clear_queue(&mut self, cx: &mut Context<Self>) {
        if !self.pending.is_empty() {
            self.pending.clear();
            cx.notify();
        }
    }

    /// Dismisses the active message. If any are queued, the next begins its own timeout.
    pub fn dismiss(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        if let Some((id, _)) = self.current() {
            self.dismiss_message(id, window, cx);
        }
    }

    /// Dismisses the entry if it is still current.
    pub fn dismiss_message(
        &mut self,
        id: SnackbarId,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> bool {
        self.finish(id, SnackbarResult::Dismissed, window, cx)
    }

    /// Performs the entry's action if it is current and has an action.
    pub fn perform_action(
        &mut self,
        id: SnackbarId,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> bool {
        self.finish(id, SnackbarResult::ActionPerformed, window, cx)
    }

    fn show_next(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.hovered = false;
        self.focused = false;
        self._focus_subscriptions.clear();
        self.timer = None;
        self.active = self.pending.pop_front().map(|(id, message)| Entry {
            id,
            message,
            controls: [cx.focus_handle(), cx.focus_handle()],
            return_focus: window.focused(cx).map(|focus| focus.downgrade()),
        });
        if let Some(entry) = &self.active {
            let controls = entry.controls.clone();
            for handle in &controls {
                let enter = cx.weak_entity();
                let leave = enter.clone();
                self._focus_subscriptions.push(window.on_focus_in(
                    handle,
                    cx,
                    move |window, cx| {
                        let _ = enter.update(cx, |host, cx| host.refresh_focus(window, cx));
                    },
                ));
                self._focus_subscriptions.push(window.on_focus_out(
                    handle,
                    cx,
                    move |_, window, cx| {
                        let _ = leave.update(cx, |host, cx| host.refresh_focus(window, cx));
                    },
                ));
            }
        }
        self.sync_timer(window, cx);
        cx.notify();
    }

    fn set_hovered(&mut self, hovered: bool, window: &mut Window, cx: &mut Context<Self>) {
        if self.hovered != hovered {
            self.hovered = hovered;
            self.sync_timer(window, cx);
        }
    }

    fn refresh_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let focused = self
            .active
            .as_ref()
            .is_some_and(|entry| entry.controls.iter().any(|focus| focus.is_focused(window)));
        if self.focused != focused {
            self.focused = focused;
            self.sync_timer(window, cx);
        }
    }

    fn sync_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        if self.hovered || self.focused {
            self.timer = None;
            return;
        }
        if self.timer.is_some() {
            return;
        }
        self.timer = self.active.as_ref().and_then(|entry| {
            let id = entry.id;
            let timeout = entry.message.timeout?;
            Some(cx.spawn_in(window, async move |this, cx| {
                cx.background_executor().timer(timeout).await;
                let _ = this.update_in(cx, |this, window, cx| {
                    this.dismiss_message(id, window, cx);
                });
            }))
        });
    }

    fn finish(
        &mut self,
        id: SnackbarId,
        result: SnackbarResult,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> bool {
        let Some(active) = self.active.as_ref().filter(|entry| entry.id == id) else {
            return false;
        };
        let callback = match result {
            SnackbarResult::ActionPerformed => {
                let Some((_, callback)) = &active.message.action else {
                    return false;
                };
                Some(callback.clone())
            }
            SnackbarResult::Dismissed => active.message.on_dismiss.clone(),
        };
        let mut entry = self.active.take().expect("current entry checked above");
        let complete = entry.message.on_result.take();
        if entry.controls.iter().any(|focus| focus.is_focused(window)) {
            if let Some(restore) = entry.return_focus.take().and_then(|focus| focus.upgrade()) {
                restore.focus(window, cx);
            } else {
                window.blur(cx);
            }
        }
        if !cx.reduce_motion() {
            if self.exiting.len() >= MAX_EXITING {
                self.exiting.remove(0);
            }
            self.exiting.push(entry);
        }
        self.show_next(window, cx);
        if callback.is_some() || complete.is_some() {
            window.defer(cx, move |window, cx| {
                if let Some(callback) = callback {
                    callback(window, cx);
                }
                if let Some(complete) = complete {
                    complete(result, window, cx);
                }
            });
        }
        true
    }
}

impl Render for SnackbarHost {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let host_width = window
            .use_keyed_state("snackbar-host-width", cx, |_, _| Rc::new(Cell::new(px(0.))))
            .read(cx)
            .clone();
        let measured_width = host_width.get();
        let width = if measured_width > px(0.) {
            measured_width
        } else {
            (window.viewport_size().width - px(32.)).clamp(px(0.), MAX_WIDTH)
        };
        let mut root = div().relative().w_full().child(
            canvas(
                move |bounds, window, _| {
                    if host_width.replace(bounds.size.width) != bounds.size.width {
                        window.request_animation_frame();
                    }
                },
                |_, _, _, _| {},
            )
            .absolute()
            .inset_0(),
        );
        let mut has_layout = self.active.is_some();
        let renderer = self.renderer.as_ref();
        self.exiting.retain(|entry| {
            let Some(motion) =
                OverlayMotion::sample(&("snackbar", entry.id.sequence).into(), false, window, cx)
            else {
                return false;
            };
            let content = snackbar_surface(entry, motion, width, false, renderer, window, cx);
            let scaled = ScaledOverlay::new(content, motion, |_| point(0.5, 0.5)).width(width);
            let slot = div().when(has_layout, |div| div.absolute().inset_0());
            root.extend([slot.child(scaled).into_any_element()]);
            has_layout = true;
            true
        });
        if let Some(entry) = &self.active {
            let motion =
                OverlayMotion::sample(&("snackbar", entry.id.sequence).into(), true, window, cx)
                    .expect("active snackbar has motion");
            let content = snackbar_surface(entry, motion, width, true, renderer, window, cx);
            root =
                root.child(ScaledOverlay::new(content, motion, |_| point(0.5, 0.5)).width(width));
        }
        root
    }
}

fn snackbar_tone_roles(tone: SemanticTone) -> (ColorRole, ColorRole, ColorRole) {
    tone.roles().map_or(
        (
            ColorRole::InverseSurface,
            ColorRole::InverseOnSurface,
            ColorRole::InversePrimary,
        ),
        |(role, _, container, on_container)| (container, on_container, role),
    )
}

fn snackbar_surface(
    entry: &Entry,
    motion: OverlayMotion,
    width: gpui::Pixels,
    active: bool,
    renderer: Option<&HostRenderer>,
    window: &mut Window,
    cx: &mut Context<SnackbarHost>,
) -> impl IntoElement {
    let id = entry.id;
    let serial = id.sequence;
    let message = &entry.message;
    let theme = current_material_theme(window, cx);
    let tone = |role| color(theme.colors.color(role));
    let (_, content_role, action_role) = snackbar_tone_roles(message.tone);
    let default_content = tone(content_role);
    let default_action = tone(action_role);
    let content_color = message.colors.content.unwrap_or(default_content);
    let action_color = message.colors.action.unwrap_or(default_action);
    let dismiss_color = message.colors.dismiss.unwrap_or(default_content);
    let dismiss_feedback = message.colors.dismiss.unwrap_or(default_action);
    let spacing = motion.px(16.);
    let message_content = message.message_content.as_ref().map_or_else(
        || message.message.clone().into_any_element(),
        |content| content(window, cx),
    );
    let message_part = div()
        .id(("snackbar-message", serial))
        .test_support()
        .when(active, |label| {
            label
                .role(Role::Status)
                .aria_label(message.message.clone())
                .a11y_synthetic_children(|tree| {
                    let node = tree.parent_node();
                    node.set_live(gpui::accesskit::Live::Polite);
                    node.set_live_atomic();
                })
        })
        .min_w_0()
        .flex_1()
        .py(motion.px(14.))
        .text_color(content_color)
        .child(message_content)
        .into_any_element();

    let render_control = |index,
                          id_name,
                          label,
                          content,
                          foreground: Hsla,
                          feedback: Hsla,
                          result,
                          cx: &Context<SnackbarHost>| {
        if active {
            gpui_base::Button::new(id_name)
                .min_h(motion.px(48.))
                .px(spacing * 0.5)
                .rounded(spacing * 0.375)
                .text_color(foreground)
                .font_weight(gpui::FontWeight::MEDIUM)
                .hover(move |style| {
                    style.bg(feedback.opacity(gpui_material_theme::StateLayer::Hover.opacity()))
                })
                .active(move |style| {
                    style.bg(feedback.opacity(gpui_material_theme::StateLayer::Pressed.opacity()))
                })
                .focus_visible(move |style| style.border(motion.px(2.)).border_color(feedback))
                .track_focus(&entry.controls[index])
                .accessibility_label(label)
                .on_click(cx.listener(move |host, _: &ClickEvent, window, cx| {
                    host.finish(id, result, window, cx);
                }))
                .child(content)
                .into_any_element()
        } else {
            div()
                .min_h(motion.px(48.))
                .px(spacing * 0.5)
                .flex()
                .items_center()
                .line_height(gpui::relative(1.))
                .text_color(foreground)
                .font_weight(gpui::FontWeight::MEDIUM)
                .child(content)
                .into_any_element()
        }
    };
    let action_part = message.action_label().map(|label| {
        let content = message.action_content.as_ref().map_or_else(
            || label.clone().into_any_element(),
            |content| content(window, cx),
        );
        let control = render_control(
            0,
            "snackbar-action",
            label.clone(),
            content,
            action_color,
            action_color,
            SnackbarResult::ActionPerformed,
            cx,
        );
        if active {
            div()
                .id("snackbar-action-region")
                .test_support()
                .child(control)
                .into_any_element()
        } else {
            control
        }
    });
    let dismiss_part = message.show_dismiss.then(|| {
        let (label, content) = message.dismiss_content.as_ref().map_or_else(
            || {
                (
                    message
                        .dismiss_label
                        .clone()
                        .unwrap_or_else(|| "Dismiss message".into()),
                    crate::Icon::new(crate::IconName::Close)
                        .size(motion.px(24.))
                        .into_any_element(),
                )
            },
            |(label, content)| (label.clone(), content(window, cx)),
        );
        render_control(
            1,
            "snackbar-dismiss",
            label,
            content,
            dismiss_color,
            dismiss_feedback,
            SnackbarResult::Dismissed,
            cx,
        )
    });
    let parts = SnackbarParts {
        message: message_part,
        action: action_part,
        dismiss: dismiss_part,
        scale: motion.scale,
    };
    let rendered = match renderer {
        Some(render) => render(message, parts, window, cx),
        None => default_layout(message, parts, motion, window, cx).into_any_element(),
    };
    let surface = div()
        .id((if active { "snackbar" } else { "snackbar-exit" }, serial))
        .test_support()
        .w(width * motion.scale)
        .opacity(motion.alpha)
        .when(active, |surface| {
            surface
                .on_hover(cx.listener(move |host, hovering: &bool, window, cx| {
                    if host.active.as_ref().is_some_and(|entry| entry.id == id) {
                        host.set_hovered(*hovering, window, cx);
                    }
                }))
                .capture_key_down(cx.listener(move |host, event: &KeyDownEvent, window, cx| {
                    if event.keystroke.key == "escape" && host.dismiss_message(id, window, cx) {
                        cx.stop_propagation();
                    }
                }))
        })
        .child(rendered);
    super::text_style(surface, TypeRole::BodyMedium, motion.scale, window, cx)
}

fn default_layout(
    message: &Snackbar,
    parts: SnackbarParts,
    motion: OverlayMotion,
    window: &Window,
    cx: &App,
) -> gpui::Div {
    let SnackbarParts {
        message: content,
        action,
        dismiss,
        ..
    } = parts;
    let theme = current_material_theme(window, cx);
    let direction = theme.layout.direction;
    let rtl = direction == Direction::Rtl;
    let tone = |role| color(theme.colors.color(role));
    let spacing = motion.px(16.);
    let (container_role, _, _) = snackbar_tone_roles(message.tone);
    let mut surface = div()
        .bg(message
            .colors
            .container
            .unwrap_or_else(|| tone(container_role)))
        .shadow(elevation_shadows(
            Elevation::Level3.dp(),
            motion.scale,
            tone(ColorRole::Shadow),
        ))
        .flex()
        .min_h(motion.px(48.))
        .gap(spacing * 0.5)
        .px(spacing)
        .when(rtl, Styled::flex_row_reverse);
    if message.shape == CornerShape::Full {
        surface = surface.rounded_full();
    } else {
        // GPUI further clamps these radii against the actual laid-out quad.
        let [top_left, top_right, bottom_right, bottom_left] =
            message.shape.radii(f32::MAX / 2., f32::MAX / 2., direction);
        let radii = &mut surface.style().corner_radii;
        radii.top_left = Some(motion.px(top_left).into());
        radii.top_right = Some(motion.px(top_right).into());
        radii.bottom_right = Some(motion.px(bottom_right).into());
        radii.bottom_left = Some(motion.px(bottom_left).into());
    }
    match (message.action_on_new_line, action) {
        (true, Some(action)) => surface
            .flex_col()
            .items_stretch()
            .gap_0()
            .child(content)
            .child(
                div()
                    .flex()
                    .items_center()
                    .justify_end()
                    .gap(spacing * 0.5)
                    .when(rtl, Styled::flex_row_reverse)
                    .child(action)
                    .children(dismiss),
            ),
        (_, action) => surface
            .items_center()
            .child(content)
            .children(action)
            .children(dismiss),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn snackbar_tone_roles_map_inverse_default_and_semantic_palettes() {
        use ColorRole::*;
        assert_eq!(
            snackbar_tone_roles(SemanticTone::Default),
            (InverseSurface, InverseOnSurface, InversePrimary)
        );
        assert_eq!(
            snackbar_tone_roles(SemanticTone::Danger),
            (ErrorContainer, OnErrorContainer, Error)
        );
        assert_eq!(
            snackbar_tone_roles(SemanticTone::Success),
            (SuccessContainer, OnSuccessContainer, Success)
        );
        assert_eq!(
            snackbar_tone_roles(SemanticTone::Warning),
            (WarningContainer, OnWarningContainer, Warning)
        );
        assert_eq!(
            snackbar_tone_roles(SemanticTone::Info),
            (InfoContainer, OnInfoContainer, Info)
        );
    }
}