arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/toast/toast.tsx` & `.module.css`
//!
//! P3 Component #17: `toast`
//!
//! - Single standalone notification card (`width: min(100%, 26rem / 416px)`) with a 30×30px
//!   success badge that draws its checkmark stroke after a `120ms` delay (`ease.enter`),
//!   a height-morphing copy frame (`spring.smooth`) that crossfades title/description swaps,
//!   and a 32×32px close button (`scale(0.96)` on press).
//! - Rises from `+16px` (`scale: 0.96 -> 1.0`) along `motion.spring.morph`.
//! - Bidirectional horizontal swipe-to-dismiss: dragging left or right past `80px` or `480 px/s`
//!   throws the toast off-screen (`direction * (width + 48)`) with release velocity on a
//!   `SpringSpec::visual(0.30, 0.0)` spring while fading out over `duration.exit`; shorter swipes
//!   snap back home on `motion.spring.snappy` preserving release velocity.
//! - Auto-dismiss timer (`duration`, default `4500ms`, `0` disables auto-dismiss).

use std::rc::Rc;

use arc_motion::{
    ArcPresence, ArcPresenceConfig, CubicBezier, DragTracker, PathPoint, PolylinePath, arc_spring,
    arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
    App, ElementId, Hsla, IntoElement, MouseButton, MouseMoveEvent, MouseUpEvent, ParentElement,
    RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window, assets::IconName,
    base::Button as BaseButton, base::StyledExt as _, canvas, div, prelude::*, px,
};

type OpenChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App)>;

/// Minimum width of a standalone [`Toast`] so short copy still breathes comfortably.
pub const TOAST_MIN_WIDTH: f32 = 220.0;

/// Maximum width of a standalone [`Toast`] (`26rem = 416px`).
pub const TOAST_MAX_WIDTH: f32 = 416.0;

/// Horizontal swipe distance threshold (`80px`) that triggers a throw dismissal.
pub const TOAST_SWIPE_DISTANCE: f32 = 80.0;

/// Horizontal swipe speed threshold (`480 px/s`) that triggers a throw dismissal.
pub const TOAST_SWIPE_VELOCITY: f32 = 480.0;

/// Default auto-dismiss duration in seconds (`4500ms`).
pub const TOAST_DEFAULT_DURATION_SECS: f64 = 4.5;

const TOAST_THROW_SPRING: SpringSpec = SpringSpec::visual(0.30, 0.0);

/// Estimates the preferred pixel width of a standalone [`Toast`] from its `title` and optional
/// `description`, clamped between [`TOAST_MIN_WIDTH`] and [`TOAST_MAX_WIDTH`] so short toasts hug
/// their copy instead of stretching to a fixed full width while long copy wraps cleanly at `416px`.
pub fn toast_target_width(title: &str, description: Option<&str>) -> f32 {
    // 16px left pad + 30px badge + 12px gap + 12px gap + 32px close + 14px right pad + 2px border
    const CHROME_W: f32 = 16.0 + 30.0 + 12.0 + 12.0 + 32.0 + 14.0 + 2.0 + 8.0;
    let measure = |s: &str, char_px: f32| -> f32 {
        s.lines()
            .map(|line| {
                line.chars()
                    .map(|c| {
                        if c.is_ascii() {
                            if c.is_ascii_uppercase() || c == 'W' || c == 'M' {
                                char_px * 1.12
                            } else {
                                char_px
                            }
                        } else {
                            char_px * 1.85
                        }
                    })
                    .sum::<f32>()
            })
            .fold(0.0_f32, f32::max)
    };
    let title_w = measure(title, 8.2);
    let desc_w = description
        .filter(|d| !d.is_empty())
        .map(|d| measure(d, 7.6))
        .unwrap_or(0.0);
    (CHROME_W + title_w.max(desc_w)).clamp(TOAST_MIN_WIDTH, TOAST_MAX_WIDTH)
}

/// Resolves whether a horizontal drag release should throw-dismiss the toast (`Some(target_x)`)
/// or snap back to center (`None`).
pub fn resolve_toast_swipe_release(
    offset_x: f32,
    velocity_x: f32,
    toast_width: f32,
) -> Option<f32> {
    if offset_x.abs() < TOAST_SWIPE_DISTANCE && velocity_x.abs() < TOAST_SWIPE_VELOCITY {
        return None;
    }
    let dir_src = if offset_x.abs() > 1e-3 {
        offset_x
    } else {
        velocity_x
    };
    let direction = if dir_src >= 0.0 { 1.0 } else { -1.0 };
    Some(direction * (toast_width.max(TOAST_MIN_WIDTH) + 48.0))
}

/// Estimates the copy column height in pixels from `title` and `description` so the `HeightFrame`
/// springs smoothly on `motion.spring.smooth` when copy grows or shrinks.
pub fn toast_copy_target_height(description: Option<&str>) -> f32 {
    toast_copy_target_height_for_width(description, TOAST_MAX_WIDTH)
}

/// Estimates the copy column height given the resolved toast outer width.
pub fn toast_copy_target_height_for_width(description: Option<&str>, toast_width: f32) -> f32 {
    match description {
        None | Some("") => 26.0,
        Some(desc) => {
            let copy_w = (toast_width - 126.0).max(96.0);
            let units_per_line = (copy_w / 7.6).max(12.0);
            let char_units: f32 = desc
                .chars()
                .map(|c| if c.is_ascii() { 1.0 } else { 1.85 })
                .sum();
            let lines = ((char_units / units_per_line).ceil() as usize).max(1);
            26.0 + 4.0 + (lines as f32) * 20.0
        }
    }
}

fn toast_check_path() -> PolylinePath {
    let s = 16.0 / 24.0;
    PolylinePath::new(vec![
        PathPoint::new(4.0 * s, 12.5 * s),
        PathPoint::new(9.0 * s, 17.5 * s),
        PathPoint::new(20.0 * s, 6.5 * s),
    ])
}

#[derive(Clone)]
struct ToastInternal {
    last_open_prop: bool,
    dismissed: bool,
    opened_at_secs: f64,
    drag_active: bool,
    drag_start_x: f32,
    drag_offset_x: f32,
    throw_target_x: f32,
    release_velocity_x: f32,
    tracker: DragTracker,
    last_width: f32,
    last_morph_key: SharedString,
    morph_changed_at_secs: f64,
}

impl ToastInternal {
    fn new(open: bool, now: f64) -> Self {
        Self {
            last_open_prop: open,
            dismissed: false,
            opened_at_secs: now,
            drag_active: false,
            drag_start_x: 0.0,
            drag_offset_x: 0.0,
            throw_target_x: 0.0,
            release_velocity_x: 0.0,
            tracker: DragTracker::new(0.0),
            last_width: TOAST_MAX_WIDTH,
            last_morph_key: SharedString::default(),
            morph_changed_at_secs: now,
        }
    }
}

/// Arc standalone `Toast`: single status notification card with a drawn checkmark badge,
/// smooth height-morphing text frame, auto-dismiss timer, and bidirectional swipe-to-throw dismissal.
#[derive(IntoElement)]
pub struct Toast {
    id: ElementId,
    title: SharedString,
    description: Option<SharedString>,
    open: bool,
    duration_secs: f64,
    on_open_change: Option<OpenChangeHandler>,
}

impl Toast {
    pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            description: None,
            open: true,
            duration_secs: TOAST_DEFAULT_DURATION_SECS,
            on_open_change: None,
        }
    }

    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
        self.description = Some(description.into());
        self
    }

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

    /// Sets auto-dismiss timeout in milliseconds (`0` disables auto-dismiss).
    pub fn duration_ms(mut self, ms: u64) -> Self {
        self.duration_secs = (ms as f64) / 1000.0;
        self
    }

    pub fn on_open_change(
        mut self,
        handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_open_change = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for Toast {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let motion = theme.motion;
        let reduced = is_reduced_motion(cx);
        let now = motion_now(cx);

        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-toast-state".into());
        let internal =
            window.use_keyed_state(state_id, cx, |_, _| ToastInternal::new(self.open, now));

        let morph_key = SharedString::from(format!(
            "{}\n{}",
            self.title,
            self.description.as_deref().unwrap_or("")
        ));

        let mut auto_timed_out = false;
        internal.update(cx, |s, _| {
            if self.open != s.last_open_prop {
                s.last_open_prop = self.open;
                if self.open {
                    s.dismissed = false;
                    s.opened_at_secs = now;
                    s.drag_active = false;
                    s.drag_offset_x = 0.0;
                    s.throw_target_x = 0.0;
                    s.release_velocity_x = 0.0;
                }
            }
            if s.last_morph_key != morph_key {
                if !s.last_morph_key.is_empty() {
                    s.morph_changed_at_secs = now;
                }
                s.last_morph_key = morph_key.clone();
            }
            let currently_visible = self.open && !s.dismissed;
            if currently_visible
                && !s.drag_active
                && self.duration_secs > 0.0
                && self.on_open_change.is_some()
            {
                let elapsed = (now - s.opened_at_secs).max(0.0);
                if elapsed >= self.duration_secs {
                    s.dismissed = true;
                    s.throw_target_x = 0.0;
                    auto_timed_out = true;
                } else {
                    window.request_animation_frame();
                }
            }
        });

        if auto_timed_out && let Some(cb) = self.on_open_change.clone() {
            window.defer(cx, move |window, cx| {
                cb(&false, window, cx);
            });
        }

        let snap = internal.read(cx).clone();
        let visible = self.open && !snap.dismissed;

        let presence = ArcPresence::new((self.id.clone(), "toast-presence"), visible)
            .animate_initial(true)
            .config(ArcPresenceConfig {
                enter_duration: motion.duration.standard,
                exit_duration: motion.duration.exit,
                enter_ease: motion.ease.enter,
                exit_ease: motion.ease.standard,
                fade_on_reduced_motion: true,
            })
            .sample(window, cx);

        if !presence.should_render() {
            return div().id(self.id).into_any_element();
        }

        let opacity = presence.progress.clamp(0.0, 1.0);
        let y_target = if visible { 0.0 } else { 8.0 };
        let y_offset = if reduced {
            0.0
        } else if visible {
            arc_spring(
                (self.id.clone(), "toast-y"),
                y_target,
                motion.spring.morph,
                window,
                cx,
            )
        } else {
            (1.0 - opacity) * 8.0
        };

        let x_offset = if snap.drag_active {
            snap.drag_offset_x
        } else if reduced {
            0.0
        } else if snap.throw_target_x.abs() > 0.5 && !visible {
            arc_spring_with_options(
                (self.id.clone(), "toast-x"),
                snap.throw_target_x,
                SpringOptions::new(TOAST_THROW_SPRING)
                    .with_initial_velocity(snap.release_velocity_x),
                window,
                cx,
            )
            .value
        } else {
            arc_spring_with_options(
                (self.id.clone(), "toast-x"),
                0.0,
                SpringOptions::new(motion.spring.snappy)
                    .with_initial_velocity(snap.release_velocity_x),
                window,
                cx,
            )
            .value
        };

        // Drawn checkmark progress (120ms delay, standard duration, ease.enter)
        let check_progress = if reduced {
            1.0
        } else {
            let elapsed = (now - snap.opened_at_secs - 0.12).max(0.0);
            let dur = motion.duration.standard.as_secs_f64();
            if elapsed < dur {
                window.request_animation_frame();
            }
            let t = (elapsed / dur).clamp(0.0, 1.0) as f32;
            CubicBezier::from_spec(motion.ease.enter).sample(t)
        };

        // Dynamic width & HeightFrame smooth springs + swap text crossfade
        let target_w = toast_target_width(self.title.as_ref(), self.description.as_deref());
        let animated_w = if reduced {
            target_w
        } else {
            arc_spring_with_options(
                (self.id.clone(), "toast-w"),
                target_w,
                SpringOptions::new(motion.spring.smooth).with_initial_value(target_w),
                window,
                cx,
            )
            .value
        };
        let target_copy_h =
            toast_copy_target_height_for_width(self.description.as_deref(), target_w);
        let copy_h = if reduced {
            target_copy_h
        } else {
            arc_spring(
                (self.id.clone(), "toast-copy-h"),
                target_copy_h,
                motion.spring.smooth,
                window,
                cx,
            )
        };

        let swap_progress = if reduced {
            1.0
        } else {
            let elapsed = (now - snap.morph_changed_at_secs).max(0.0);
            let dur = motion.duration.standard.as_secs_f64();
            if elapsed < dur {
                window.request_animation_frame();
            }
            let t = (elapsed / dur).clamp(0.0, 1.0) as f32;
            CubicBezier::from_spec(motion.ease.enter).sample(t)
        };
        let swap_y = if reduced {
            0.0
        } else {
            (1.0 - swap_progress) * 4.0
        };

        let card_bg = oklab_mix(colors.surface, colors.background, 0.94);
        let badge_border = oklab_mix(colors.success, colors.border, 0.24);
        let badge_bg = oklab_mix(colors.success, colors.surface, 0.10);
        let icon_fg = Hsla {
            a: colors.success.a * opacity,
            ..colors.success
        };
        let check_path = toast_check_path();

        let int_measure = internal.clone();
        let int_drag = internal.clone();
        let on_change_drag = self.on_open_change.clone();
        let drag_active = snap.drag_active;

        let drag_probe = canvas(
            move |rect, _, cx| {
                int_measure.update(cx, |s, _| {
                    s.last_width = f32::from(rect.size.width).max(TOAST_MIN_WIDTH);
                });
            },
            move |_, _, window, _| {
                if !drag_active {
                    return;
                }
                let st_move = int_drag.clone();
                window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
                    if !phase.bubble() {
                        return;
                    }
                    let t_now = motion_now(cx);
                    let cur_x = f32::from(event.position.x);
                    let cur_y = f32::from(event.position.y);
                    st_move.update(cx, |s, _| {
                        if !s.drag_active {
                            return;
                        }
                        if let Some(next_x) = s.tracker.update_x(cur_x, cur_y, t_now, false) {
                            s.drag_offset_x = next_x;
                        }
                    });
                    window.refresh();
                });

                let st_up = int_drag.clone();
                let cb_up = on_change_drag.clone();
                window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
                    if !phase.bubble() || event.button != MouseButton::Left {
                        return;
                    }
                    let t_now = motion_now(cx);
                    let mut dismissed_now = false;
                    st_up.update(cx, |s, _| {
                        if !s.drag_active {
                            return;
                        }
                        s.drag_active = false;
                        let vel_x = s.tracker.release_velocity(t_now);
                        s.release_velocity_x = vel_x;
                        if let Some(target_x) =
                            resolve_toast_swipe_release(s.drag_offset_x, vel_x, s.last_width)
                        {
                            s.throw_target_x = target_x;
                            s.dismissed = true;
                            dismissed_now = true;
                        } else {
                            s.throw_target_x = 0.0;
                        }
                    });
                    if dismissed_now && let Some(cb) = &cb_up {
                        cb(&false, window, cx);
                    }
                    window.refresh();
                });
            },
        )
        .absolute()
        .inset_0();

        let int_down = internal.clone();
        let int_close = internal.clone();
        let on_change_close = self.on_open_change.clone();
        let close_id = ElementId::NamedChild(self.id.clone().into(), "toast-close".into());

        div()
            .id(self.id)
            .test_support()
            .role(Role::Status)
            .aria_label(self.title.clone())
            .relative()
            .w(px(animated_w))
            .max_w_full()
            .ml(px(x_offset))
            .mt(px(y_offset))
            .opacity(opacity)
            .flex()
            .flex_row()
            .items_start()
            .gap(px(12.0))
            .pt(px(14.0))
            .pr(px(14.0))
            .pb(px(14.0))
            .pl(px(16.0))
            .rounded(Radii::PANEL)
            .border_1()
            .border_color(colors.border)
            .bg(card_bg)
            .text_color(colors.foreground)
            .shadow(Shadows::floating(theme.mode))
            .when(!reduced, |this| this.cursor_grab())
            .on_mouse_down(MouseButton::Left, move |event, window, cx| {
                if reduced {
                    return;
                }
                let t_now = motion_now(cx);
                let start_x = f32::from(event.position.x);
                let start_y = f32::from(event.position.y);
                int_down.update(cx, |s, _| {
                    s.drag_active = true;
                    s.drag_start_x = start_x - s.drag_offset_x;
                    s.tracker.begin(start_x, start_y, s.drag_offset_x, t_now);
                });
                window.refresh();
            })
            .child(drag_probe)
            .child(
                div()
                    .size(px(30.0))
                    .flex_none()
                    .rounded(Radii::PILL)
                    .border_1()
                    .border_color(badge_border)
                    .bg(badge_bg)
                    .flex()
                    .items_center()
                    .justify_center()
                    .child(
                        canvas(
                            |_, _, _| {},
                            move |rect, _, window, _| {
                                let sliced = check_path.slice(0.0, check_progress);
                                if let Some(builder) =
                                    sliced.to_stroke_builder(rect.origin.x, rect.origin.y, px(2.25))
                                    && let Ok(built) = builder.build()
                                {
                                    window.paint_path(built, icon_fg);
                                }
                            },
                        )
                        .size(px(16.0)),
                    ),
            )
            .child(
                div()
                    .flex_1()
                    .min_w_0()
                    .min_h(px(copy_h))
                    .pt(px(5.0))
                    .flex()
                    .flex_col()
                    .gap(px(2.0))
                    .opacity(swap_progress)
                    .mt(px(swap_y))
                    .child(
                        div()
                            .text_size(Typography::TEXT_SM)
                            .font_medium()
                            .text_color(colors.foreground)
                            .child(self.title),
                    )
                    .when_some(self.description, |this, desc| {
                        this.child(
                            div()
                                .text_size(Typography::TEXT_SM)
                                .text_color(colors.text_secondary)
                                .child(desc),
                        )
                    }),
            )
            .child(
                BaseButton::new(close_id)
                    .accessibility_label("Dismiss notification")
                    .on_click(move |_, window, cx| {
                        int_close.update(cx, |s, _| {
                            s.throw_target_x = 0.0;
                            s.dismissed = true;
                        });
                        if let Some(cb) = &on_change_close {
                            cb(&false, window, cx);
                        }
                        window.refresh();
                    })
                    .size(px(32.0))
                    .flex_none()
                    .rounded(Radii::PILL)
                    .flex()
                    .items_center()
                    .justify_center()
                    .text_color(colors.text_muted)
                    .hover(|s| s.bg(colors.surface_muted).text_color(colors.foreground))
                    .cursor_pointer()
                    .child(IconName::Close),
            )
            .into_any_element()
    }
}

#[cfg(test)]
mod tests {
    use std::{cell::Cell, rc::Rc};

    use arc_tokens::{Accent, Spacing, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, MouseButton, Render, Role, TestAppContext, div,
        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
    };

    use super::*;

    #[test]
    fn swipe_release_and_height_target_behave_as_expected() {
        // Short and slow swipe snaps back
        assert_eq!(resolve_toast_swipe_release(32.0, 120.0, 360.0), None);
        // Past 80px throws right
        assert_eq!(resolve_toast_swipe_release(95.0, 60.0, 360.0), Some(408.0));
        // Fast left flick throws left
        assert_eq!(
            resolve_toast_swipe_release(-24.0, -520.0, 360.0),
            Some(-408.0)
        );

        let h_short = toast_copy_target_height(None);
        let h_desc = toast_copy_target_height(Some("Changes have been synced to production."));
        let h_long = toast_copy_target_height(Some(
            "Your deployment finished across 4 regions and all health checks passed without errors.",
        ));
        assert!(h_desc > h_short);
        assert!(h_long > h_desc);

        // Dynamic width scales with copy length within [TOAST_MIN_WIDTH, TOAST_MAX_WIDTH]
        let w_short = toast_target_width("Saved", None);
        let w_mid = toast_target_width("Workspace preferences saved", None);
        let w_long = toast_target_width(
            "Deployment published to production",
            Some("All 4 edge regions passed health checks and your live URL is ready."),
        );
        assert!((w_short - TOAST_MIN_WIDTH).abs() < 1e-3);
        assert!(w_mid > w_short && w_mid < TOAST_MAX_WIDTH);
        assert!((w_long - TOAST_MAX_WIDTH).abs() < 1e-3);
    }

    struct Host {
        open: Rc<Cell<bool>>,
    }

    impl Render for Host {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let open = self.open.clone();
            div().p(Spacing::S6).child(
                Toast::new("single-toast", "Project published")
                    .description("Your live link is ready to share.")
                    .open(open.get())
                    .duration_ms(0)
                    .on_open_change(cx.listener(move |_, is_open: &bool, _, cx| {
                        open.set(*is_open);
                        cx.notify();
                    })),
            )
        }
    }

    #[gpui_kit::test]
    fn toast_dismiss_button_invokes_on_open_change(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
        });
        let open = Rc::new(Cell::new(true));
        let (_view, cx) = cx.add_window_view(|_, _| Host { open: open.clone() });

        cx.update(|window, cx| {
            window.render_frame(cx);
            let close_btn = window.find_by_label("Dismiss notification");
            assert_eq!(close_btn.role(), Some(Role::Button));
            let pos = close_btn.bounds().center();
            window.pointer_down(pos, MouseButton::Left, cx);
            window.pointer_up(pos, MouseButton::Left, cx);
            assert!(!open.get());
        });
    }
}