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
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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/dialog/dialog.tsx` & `.module.css`
//!
//! P3 Component #7: `dialog`
//!
//! - Modal dialog with optional trigger child, full-window backdrop overlay (`oklch(10% 0 0 / .46)`),
//!   and centered `440px` max-width floating surface (`Radii::SURFACE`, `surface_raised`, `floating`
//!   shadow).
//! - Overlay fades in over `duration.standard` (`220ms`) with `ease.enter` and fades out over
//!   `duration.fast` (`160ms`) with `ease.standard` (or `duration.instant = 120ms` under reduced
//!   motion).
//! - Content card fades in over `duration.fast` (`160ms`, `ease.enter`) while rising `8px -> 0px` on
//!   `motion.spring.smooth` (`duration: 0.35, bounce: 0`); exits over `duration.fast` (`160ms`,
//!   `ease.standard`) with a `+4px` drop. While exiting (`data-state="closed"`), pointer events pass
//!   through so clicking the trigger mid-exit reopens immediately without the outside-press handler
//!   canceling it.
//! - Header features `SwapText` for both `title` and `description`: when either string changes while
//!   the dialog is open, the old copy rises out (`y: 0 -> -5px`, `160ms`) while the new copy rises
//!   in from below (`y: +5px -> 0`, `220ms`, `ease.enter`).
//! - Close button (`32×32`, `Radii::CONTROL`, `1px` border, `50%` `surface_muted` fill) brightens on
//!   hover and responds on active press; `Esc` and backdrop click also dismiss the dialog.

use std::{cell::RefCell, rc::Rc};

use arc_motion::{
    ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, is_reduced_motion,
    motion_now,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
use gpui_kit::{
    AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
    MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
    TestSupportExt as _, Window, base::StyledExt as _, canvas, deferred, div, point, prelude::*,
    px,
};

/// Maximum modal dialog width (`440px`).
pub const DIALOG_MAX_WIDTH: f32 = 440.0;
/// Viewport inset (`var(--space-8) = 32px`).
pub const DIALOG_VIEWPORT_MARGIN: f32 = 32.0;

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

/// Computes the vertical offset (`px`) of the dialog card during enter/exit.
///
/// - Enter: `spring_y` runs on `motion.spring.smooth` from `8.0 -> 0.0`.
/// - Exit: `presence_t` (`1.0 -> 0.0`) interpolates from current position toward `+4.0`.
pub fn dialog_card_y_offset(is_open: bool, spring_y: f32, presence_t: f32, reduced: bool) -> f32 {
    if reduced {
        return 0.0;
    }
    if is_open {
        spring_y
    } else {
        let exit_progress = (1.0 - presence_t).clamp(0.0, 1.0);
        spring_y + (4.0 - spring_y) * exit_progress
    }
}

/// Samples `(old_alpha, old_y, new_alpha, new_y)` for `SwapText` when `title` or `description`
/// changes while the dialog is open.
pub fn swap_text_sample(elapsed_secs: f64, reduced: bool) -> (f32, f32, f32, f32) {
    if reduced || elapsed_secs >= 0.22 {
        return (0.0, -5.0, 1.0, 0.0);
    }
    let out_t = (elapsed_secs / 0.16).clamp(0.0, 1.0) as f32;
    let out_eased = CubicBezier::new(0.2, 0.0, 0.0, 1.0).sample(out_t);
    let in_t = (elapsed_secs / 0.22).clamp(0.0, 1.0) as f32;
    let in_eased = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(in_t);
    let old_blur = BlurFallback::evaluate(px(out_eased * 4.0), reduced);
    let new_blur = BlurFallback::evaluate(px((1.0 - in_eased) * 8.0), reduced);
    let old_alpha = ((1.0 - out_eased) * old_blur.opacity_multiplier).clamp(0.0, 1.0);
    let old_y = -5.0 * out_eased;
    let new_alpha = (in_eased * new_blur.opacity_multiplier).clamp(0.0, 1.0);
    let new_y = 5.0 * (1.0 - in_eased);
    (old_alpha, old_y, new_alpha, new_y)
}

fn paint_close_x(cx: f32, cy: f32, scale: f32, color: Hsla, window: &mut Window) {
    let r = 4.2 * scale;
    for (x1, y1, x2, y2) in [
        (cx - r, cy - r, cx + r, cy + r),
        (cx + r, cy - r, cx - r, cy + r),
    ] {
        let mut b = PathBuilder::stroke(px(1.75));
        b.move_to(point(px(x1), px(y1)));
        b.line_to(point(px(x2), px(y2)));
        if let Ok(path) = b.build() {
            window.paint_path(path, color);
        }
    }
}

#[derive(Clone)]
struct DialogInternal {
    open: bool,
    last_open_changed_at: f64,
    close_hovered: bool,
    close_pressed: bool,
    prev_title: Option<SharedString>,
    last_title: SharedString,
    title_changed_at: f64,
    prev_desc: Option<SharedString>,
    last_desc: SharedString,
    desc_changed_at: f64,
    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    card_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    focus_handle: FocusHandle,
}

impl DialogInternal {
    fn new(
        default_open: bool,
        title: SharedString,
        desc: SharedString,
        now: f64,
        focus_handle: FocusHandle,
    ) -> Self {
        Self {
            open: default_open,
            last_open_changed_at: now - 10.0,
            close_hovered: false,
            close_pressed: false,
            prev_title: None,
            last_title: title,
            title_changed_at: now - 10.0,
            prev_desc: None,
            last_desc: desc,
            desc_changed_at: now - 10.0,
            trigger_bounds: Rc::new(RefCell::new(None)),
            card_bounds: Rc::new(RefCell::new(None)),
            focus_handle,
        }
    }
}

/// Arc `Dialog` — modal dialog with spring entrance, backdrop dim, `SwapText` header transitions,
/// and mid-exit click-through.
#[derive(IntoElement)]
pub struct ArcDialog {
    id: ElementId,
    title: SharedString,
    description: Option<SharedString>,
    trigger: Option<AnyElement>,
    body: Option<AnyElement>,
    open: Option<bool>,
    default_open: bool,
    content_only: bool,
    max_width: Pixels,
    on_open_change: Option<OpenCallback>,
}

impl ArcDialog {
    pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            description: None,
            trigger: None,
            body: None,
            open: None,
            default_open: false,
            content_only: false,
            max_width: px(DIALOG_MAX_WIDTH),
            on_open_change: None,
        }
    }

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

    /// Optional trigger element that opens the dialog on click.
    pub fn trigger(mut self, trigger: impl IntoElement) -> Self {
        self.trigger = Some(trigger.into_any_element());
        self
    }

    /// Body content rendered inside the `.body` padding area (`24px`).
    pub fn content(mut self, body: impl IntoElement) -> Self {
        self.body = Some(body.into_any_element());
        self
    }

    /// 直接承载自带外观的完整面板,不额外渲染标题、内边距、边框与阴影。
    /// `title` 仍作为弹窗的可访问名称;内容应提供自己的关闭入口。
    pub fn content_only(mut self, content_only: bool) -> Self {
        self.content_only = content_only;
        self
    }

    /// 设置面板最大宽度;实际宽度始终受窗口安全边距约束。
    pub fn max_width(mut self, max_width: Pixels) -> Self {
        if f32::from(max_width).is_finite() && max_width > px(0.0) {
            self.max_width = max_width;
        }
        self
    }

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

    pub fn default_open(mut self, default_open: bool) -> Self {
        self.default_open = default_open;
        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
    }
}

#[allow(clippy::too_many_arguments)]
fn render_swap_slot(
    old_text: Option<SharedString>,
    new_text: SharedString,
    elapsed: f64,
    reduced: bool,
    line_height_px: f32,
    text_size: Pixels,
    font_medium: bool,
    color: Hsla,
) -> AnyElement {
    let (old_alpha, old_y, new_alpha, new_y) = swap_text_sample(elapsed, reduced);
    let swapping = old_text.is_some() && old_alpha > 0.01;

    if !swapping {
        return div()
            .line_height(px(line_height_px))
            .text_size(text_size)
            .when(font_medium, |d| d.font_medium())
            .text_color(color)
            .child(new_text)
            .into_any_element();
    }

    div()
        .relative()
        .min_h(px(line_height_px))
        .child(
            div()
                .line_height(px(line_height_px))
                .text_size(text_size)
                .when(font_medium, |d| d.font_medium())
                .text_color(color)
                .opacity(new_alpha)
                .mt(px(new_y))
                .child(new_text),
        )
        .when_some(old_text, |d, old| {
            d.child(
                div()
                    .absolute()
                    .top(px(old_y))
                    .left_0()
                    .right_0()
                    .line_height(px(line_height_px))
                    .text_size(text_size)
                    .when(font_medium, |d| d.font_medium())
                    .text_color(color)
                    .opacity(old_alpha)
                    .child(old),
            )
        })
        .into_any_element()
}

impl RenderOnce for ArcDialog {
    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 desc_str = self.description.clone().unwrap_or_default();
        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-dialog-state".into());
        let title_init = self.title.clone();
        let desc_init = desc_str.clone();
        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
            DialogInternal::new(
                self.default_open,
                title_init,
                desc_init,
                now,
                cx.focus_handle(),
            )
        });

        // Detect live title / description changes while open so `SwapText` plays.
        {
            let snap = internal.read(cx).clone();
            let is_open_now = self.open.unwrap_or(snap.open);
            if snap.last_title != self.title {
                let prev = snap.last_title.clone();
                let next = self.title.clone();
                internal.update(cx, |s, _| {
                    if is_open_now {
                        s.prev_title = Some(prev);
                        s.title_changed_at = now;
                    }
                    s.last_title = next;
                });
            }
            if snap.last_desc != desc_str {
                let prev = snap.last_desc.clone();
                let next = desc_str.clone();
                internal.update(cx, |s, _| {
                    if is_open_now && !prev.is_empty() {
                        s.prev_desc = Some(prev);
                        s.desc_changed_at = now;
                    }
                    s.last_desc = next;
                });
            }
        }

        let snap = internal.read(cx).clone();
        let is_open = self.open.unwrap_or(snap.open);

        let overlay_presence = ArcPresence::new((self.id.clone(), "dialog-overlay"), is_open)
            .animate_initial(false)
            .config(ArcPresenceConfig {
                enter_duration: motion.duration.standard,
                exit_duration: motion.duration.fast,
                enter_ease: motion.ease.enter,
                exit_ease: motion.ease.standard,
                fade_on_reduced_motion: true,
            })
            .sample(window, cx);

        let card_presence = ArcPresence::new((self.id.clone(), "dialog-card"), is_open)
            .animate_initial(false)
            .config(ArcPresenceConfig {
                enter_duration: motion.duration.fast,
                exit_duration: motion.duration.fast,
                enter_ease: motion.ease.enter,
                exit_ease: motion.ease.standard,
                fade_on_reduced_motion: true,
            })
            .sample(window, cx);

        let spring_y = if reduced {
            0.0
        } else {
            arc_spring(
                (self.id.clone(), "dialog-y"),
                if is_open { 0.0 } else { 8.0 },
                motion.spring.smooth,
                window,
                cx,
            )
        };
        let y_offset = dialog_card_y_offset(is_open, spring_y, card_presence.progress, reduced);

        let title_elapsed = (now - snap.title_changed_at).max(0.0);
        let desc_elapsed = (now - snap.desc_changed_at).max(0.0);
        if is_open && !reduced && (title_elapsed < 0.23 || desc_elapsed < 0.23) {
            window.request_animation_frame();
        }

        let trigger_bounds_ref = snap.trigger_bounds.clone();
        let trigger_probe = canvas(
            move |rect, _, _| {
                *trigger_bounds_ref.borrow_mut() = Some(rect);
            },
            |_, _, _, _| {},
        )
        .absolute()
        .inset_0();

        let internal_trig = internal.clone();
        let on_open_trig = self.on_open_change.clone();
        let focus_trig = snap.focus_handle.clone();
        let mut root = div()
            .id(self.id.clone())
            .test_support()
            .relative()
            .flex()
            .child(trigger_probe);

        if let Some(trig) = self.trigger {
            root = root.child(
                div()
                    .id(ElementId::NamedChild(
                        self.id.clone().into(),
                        "trigger".into(),
                    ))
                    .test_support()
                    .role(Role::Button)
                    .aria_label("Open dialog")
                    .relative()
                    .flex()
                    .cursor_pointer()
                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                        let t = motion_now(cx);
                        internal_trig.update(cx, |s, _| {
                            s.open = true;
                            s.last_open_changed_at = t;
                        });
                        focus_trig.focus(window, cx);
                        if let Some(h) = &on_open_trig {
                            h(&true, window, cx);
                        }
                        window.refresh();
                    })
                    .child(trig),
            );
        }

        if !overlay_presence.should_render() && !card_presence.should_render() {
            return root;
        }

        // 子输入已有焦点时不得在重绘中抢回,否则键盘输入只能维持一帧。
        if is_open && !snap.focus_handle.contains_focused(window, cx) {
            snap.focus_handle.focus(window, cx);
        }

        // Outside-press listener: only active while `is_open` is true, so clicks pass through while
        // the dialog is animating out (`data-state="closed"`).
        let card_bounds_ref = snap.card_bounds.clone();
        let card_bounds_out = snap.card_bounds.clone();
        let trig_bounds_out = snap.trigger_bounds.clone();
        let internal_out = internal.clone();
        let on_open_out = self.on_open_change.clone();
        let opened_at = snap.last_open_changed_at;
        let card_probe = canvas(
            move |rect, _, _| {
                *card_bounds_ref.borrow_mut() = Some(rect);
            },
            move |_, _, window, _| {
                if is_open {
                    let c_ref = card_bounds_out.clone();
                    let t_ref = trig_bounds_out.clone();
                    let st = internal_out.clone();
                    let cb = on_open_out.clone();
                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
                        if !phase.bubble() {
                            return;
                        }
                        let t_now = motion_now(cx);
                        if (t_now - opened_at).abs() < 0.001 {
                            return;
                        }
                        let in_card = c_ref.borrow().is_some_and(|b| b.contains(&event.position));
                        let in_trig = t_ref.borrow().is_some_and(|b| b.contains(&event.position));
                        if !in_card && !in_trig {
                            st.update(cx, |s, _| {
                                s.open = false;
                                s.last_open_changed_at = t_now;
                            });
                            if let Some(h) = &cb {
                                h(&false, window, cx);
                            }
                            window.refresh();
                        }
                    });
                }
            },
        )
        .absolute()
        .inset_0();

        // Close button (`32×32`, `1px` border, `50%` surface_muted fill, `.close:active { scale(.96) }`).
        let close_bg = if snap.close_hovered || snap.close_pressed {
            colors.surface_muted
        } else {
            oklab_mix(colors.surface_muted, Hsla::transparent_black(), 0.5)
        };
        let close_fg = if snap.close_hovered || snap.close_pressed {
            colors.foreground
        } else {
            colors.text_secondary
        };
        let close_scale = if snap.close_pressed && !reduced {
            0.92
        } else {
            1.0
        };
        let internal_close_hover = internal.clone();
        let internal_close_press = internal.clone();
        let internal_close_up = internal.clone();
        let on_open_close = self.on_open_change.clone();

        let close_btn = div()
            .id(ElementId::NamedChild(
                self.id.clone().into(),
                "close".into(),
            ))
            .test_support()
            .role(Role::Button)
            .aria_label("Close dialog")
            .flex_none()
            .w(Spacing::S8)
            .h(Spacing::S8)
            .rounded(Radii::CONTROL)
            .border_1()
            .border_color(colors.border)
            .bg(close_bg)
            .cursor_pointer()
            .on_hover(move |hovered, window, cx| {
                internal_close_hover.update(cx, |s, _| {
                    s.close_hovered = *hovered;
                    if !*hovered {
                        s.close_pressed = false;
                    }
                });
                window.refresh();
            })
            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                cx.stop_propagation();
                internal_close_press.update(cx, |s, _| {
                    s.close_pressed = true;
                });
                window.refresh();
            })
            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
                cx.stop_propagation();
                let t = motion_now(cx);
                internal_close_up.update(cx, |s, _| {
                    s.close_pressed = false;
                    s.open = false;
                    s.last_open_changed_at = t;
                });
                if let Some(h) = &on_open_close {
                    h(&false, window, cx);
                }
                window.refresh();
            })
            .child(
                canvas(
                    |_, _, _| {},
                    move |rect, _, window, _| {
                        let cx = f32::from(rect.origin.x) + f32::from(rect.size.width) * 0.5;
                        let cy = f32::from(rect.origin.y) + f32::from(rect.size.height) * 0.5;
                        paint_close_x(cx, cy, close_scale, close_fg, window);
                    },
                )
                .size_full(),
            );

        let title_slot = render_swap_slot(
            snap.prev_title.clone(),
            self.title.clone(),
            title_elapsed,
            reduced,
            24.0,
            Typography::TEXT_LG,
            true,
            colors.foreground,
        );

        let desc_slot = self.description.as_ref().map(|d| {
            render_swap_slot(
                snap.prev_desc.clone(),
                d.clone(),
                desc_elapsed,
                reduced,
                21.0,
                Typography::TEXT_SM,
                false,
                colors.text_secondary,
            )
        });

        let header = div()
            .w_full()
            .flex()
            .items_start()
            .justify_between()
            .gap(Spacing::S5)
            .p(Spacing::S6)
            .border_b_1()
            .border_color(colors.border)
            .child(
                div()
                    .flex_1()
                    .flex()
                    .flex_col()
                    .gap(Spacing::S2)
                    .child(title_slot)
                    .when_some(desc_slot, |d, desc| d.child(desc)),
            )
            .child(close_btn);

        let body = div()
            .w_full()
            .when(!self.content_only, |d| d.p(Spacing::S6))
            .text_size(Typography::TEXT_SM)
            .text_color(colors.foreground)
            .when_some(self.body, |d, b| d.child(b));

        let viewport = window.viewport_size();
        let avail_w = (f32::from(viewport.width) - DIALOG_VIEWPORT_MARGIN).max(0.0);
        let card_w = avail_w.min(f32::from(self.max_width));

        let internal_key = internal.clone();
        let on_open_key = self.on_open_change.clone();
        let card = div()
            .id(ElementId::NamedChild(
                self.id.clone().into(),
                "content".into(),
            ))
            .role(Role::Dialog)
            .aria_label(self.title.clone())
            .test_support()
            .track_focus(&snap.focus_handle)
            .relative()
            .w(px(card_w))
            .mt(px(y_offset))
            .when(!self.content_only, |d| {
                d.rounded(Radii::SURFACE)
                    .border_1()
                    .border_color(colors.border)
                    .bg(colors.surface_raised)
                    .shadow(Shadows::floating(theme.mode))
            })
            .text_color(colors.foreground)
            .opacity(card_presence.progress.clamp(0.0, 1.0))
            .on_mouse_down(MouseButton::Left, |_, _, cx| {
                cx.stop_propagation();
            })
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                if event.keystroke.key.as_str() == "escape" {
                    cx.stop_propagation();
                    let t = motion_now(cx);
                    internal_key.update(cx, |s, _| {
                        s.open = false;
                        s.last_open_changed_at = t;
                    });
                    if let Some(h) = &on_open_key {
                        h(&false, window, cx);
                    }
                    window.refresh();
                }
            })
            .child(card_probe)
            .when(!self.content_only, |d| d.child(header))
            .child(body);

        // Backdrop (`oklch(10% 0 0 / .46)` approximated in HSLA with `overlay_presence.progress`).
        let mut backdrop_color = gpui_kit::hsla(0.0, 0.0, 0.04, 0.46);
        backdrop_color.a *= overlay_presence.progress.clamp(0.0, 1.0);

        let (rel_left, rel_top) = snap
            .trigger_bounds
            .borrow()
            .map(|b| (-f32::from(b.origin.x), -f32::from(b.origin.y)))
            .unwrap_or((0.0, 0.0));

        let modal_layer = div()
            .id(ElementId::NamedChild(
                self.id.clone().into(),
                "backdrop".into(),
            ))
            .test_support()
            .absolute()
            .left(px(rel_left))
            .top(px(rel_top))
            .w(viewport.width)
            .h(viewport.height)
            .bg(backdrop_color)
            .flex()
            .items_center()
            .justify_center()
            .p(Spacing::S4)
            // 冒泡阶段在内层列表滚动之后消费;即使贴边,也不能滚动模态背后的文档。
            .when(is_open, |layer| {
                layer.on_scroll(|_, _, cx| cx.stop_propagation())
            })
            .child(card);

        root.child(deferred(modal_layer).with_priority(30))
    }
}

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

    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, IntoElement, MouseButton, ParentElement, Render, Role, SharedString, Styled,
        TestAppContext, Window, div, px,
        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
    };

    use super::*;

    struct DialogHarness {
        open: bool,
        title: SharedString,
        close_count: Rc<Cell<usize>>,
    }

    impl Render for DialogHarness {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let count = self.close_count.clone();
            div().size_full().p(px(24.0)).child(
                ArcDialog::new("test-dialog", self.title.clone())
                    .description("Confirm workspace archive")
                    .open(self.open)
                    .on_open_change(cx.listener(move |this, next: &bool, _, cx| {
                        this.open = *next;
                        if !*next {
                            count.set(count.get() + 1);
                        }
                        cx.notify();
                    }))
                    .trigger(div().w(px(100.0)).h(px(36.0)).child("Open dialog"))
                    .content(div().child("Dialog body content")),
            )
        }
    }

    #[gpui_kit::test]
    fn modal_consumes_wheel_after_inner_list_and_unlocks_after_close(cx: &mut TestAppContext) {
        use gpui_kit::{
            InputEvent as _, ScrollDelta, ScrollEvent, ScrollHandle, TouchPhase, point, size,
        };
        struct ScrollDialog {
            open: bool,
            document: ScrollHandle,
            list: ScrollHandle,
        }
        impl Render for ScrollDialog {
            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
                div()
                    .id("modal-scroll-document")
                    .size_full()
                    .overflow_y_scroll()
                    .track_scroll(&self.document)
                    .child(
                        ArcDialog::new("scroll-dialog", "Scroll dialog")
                            .open(self.open)
                            .trigger(div().w(px(120.0)).h(px(36.0)).child("Open"))
                            .on_open_change(cx.listener(|this, open: &bool, _, cx| {
                                this.open = *open;
                                cx.notify();
                            }))
                            .content(
                                div()
                                    .id("modal-scroll-list")
                                    .test_support()
                                    .h(px(120.0))
                                    .overflow_y_scroll()
                                    .track_scroll(&self.list)
                                    .child(div().h(px(900.0)).flex_none()),
                            ),
                    )
                    .child(div().h(px(1800.0)).flex_none())
            }
        }
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
        });
        let document = ScrollHandle::new();
        let list = ScrollHandle::new();
        let (_, cx) = cx.add_window_view(|_, _| ScrollDialog {
            open: false,
            document: document.clone(),
            list: list.clone(),
        });
        cx.simulate_resize(size(px(800.0), px(700.0)));
        cx.update(|w, cx| {
            w.render_frame(cx);
            w.click(
                ElementId::NamedChild(ElementId::from("scroll-dialog").into(), "trigger".into()),
                cx,
            );
            w.render_frame(cx);
        });
        cx.executor()
            .advance_clock(std::time::Duration::from_millis(400));
        cx.update(|w, cx| {
            w.render_frame(cx);
            for (index, delta) in [-60.0, -2000.0, -60.0, 60.0, 2000.0, 60.0]
                .into_iter()
                .enumerate()
            {
                let position = w.find("modal-scroll-list").bounds().center();
                w.pointer_move(position, None, cx);
                w.dispatch_event(
                    ScrollEvent {
                        position,
                        delta: ScrollDelta::Pixels(point(px(0.0), px(delta))),
                        modifiers: Default::default(),
                        touch_phase: TouchPhase::Moved,
                        source: Default::default(),
                    }
                    .to_platform_input(),
                    cx,
                );
                w.render_frame(cx);
                assert_eq!(document.offset().y, px(0.0));
                if index == 0 {
                    assert!(list.offset().y < px(0.0), "内层列表必须仍能滚动");
                }
                if index >= 4 {
                    assert_eq!(list.offset().y, px(0.0));
                }
            }
            w.press("escape", cx);
        });
        cx.executor()
            .advance_clock(std::time::Duration::from_millis(400));
        cx.update(|w, cx| {
            w.render_frame(cx);
            let position = point(px(400.0), px(300.0));
            w.pointer_move(position, None, cx);
            w.dispatch_event(
                ScrollEvent {
                    position,
                    delta: ScrollDelta::Pixels(point(px(0.0), px(-60.0))),
                    modifiers: Default::default(),
                    touch_phase: TouchPhase::Moved,
                    source: Default::default(),
                }
                .to_platform_input(),
                cx,
            );
            w.render_frame(cx);
            assert!(document.offset().y < px(0.0));
        });
    }

    #[test]
    fn card_offset_and_swap_text_curves_follow_spec() {
        assert!((dialog_card_y_offset(true, 8.0, 0.0, false) - 8.0).abs() < 1e-4);
        assert!((dialog_card_y_offset(true, 0.0, 1.0, false) - 0.0).abs() < 1e-4);
        assert!((dialog_card_y_offset(false, 0.0, 0.0, false) - 4.0).abs() < 1e-4);
        assert_eq!(dialog_card_y_offset(true, 6.0, 0.5, true), 0.0);

        let (old_a0, _, new_a0, new_y0) = swap_text_sample(0.0, false);
        assert!(old_a0 > 0.95);
        assert!(new_a0 < 0.05);
        assert!(new_y0 > 4.0);

        let (old_a1, _, new_a1, new_y1) = swap_text_sample(0.25, false);
        assert_eq!(old_a1, 0.0);
        assert_eq!(new_a1, 1.0);
        assert_eq!(new_y1, 0.0);
    }

    #[gpui_kit::test]
    fn dialog_opens_on_trigger_and_closes_on_close_button_or_outside_click(
        cx: &mut TestAppContext,
    ) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });
        let close_count = Rc::new(Cell::new(0));
        let (_view, cx) = cx.add_window_view(|_, _| DialogHarness {
            open: false,
            title: "Archive project".into(),
            close_count: close_count.clone(),
        });

        cx.update(|window, cx| {
            window.render_frame(cx);

            let trig = window.find_by_label("Open dialog");
            assert_eq!(trig.role(), Some(Role::Button));
            let tpos = trig.bounds().center();
            window.pointer_down(tpos, MouseButton::Left, cx);
            window.pointer_up(tpos, MouseButton::Left, cx);
            window.render_frame(cx);

            let modal = window.find_by_label("Archive project");
            assert_eq!(modal.role(), Some(Role::Dialog));

            // Click the close button.
            let close_btn = window.find_by_label("Close dialog");
            let cpos = close_btn.bounds().center();
            window.pointer_down(cpos, MouseButton::Left, cx);
            window.pointer_up(cpos, MouseButton::Left, cx);
            window.render_frame(cx);
            assert_eq!(close_count.get(), 1);
        });
    }
}