gpui-component 0.6.4

GPUI Component: the styled component library of GPUI Kit, with 60+ desktop UI 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
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
use gpui_base::TestSupportExt as _;
use std::{rc::Rc, sync::LazyLock, time::Duration};

use gpui::{
    Action, Animation, AnimationExt as _, AnyElement, App, BoxShadow, ClickEvent, Edges,
    FocusHandle, Hsla, InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce,
    SharedString, StyleRefinement, Styled, Window, WindowControlArea, anchored, div, hsla, point,
    prelude::FluentBuilder, px,
};
use gpui_base::{ElementExt as _, TextSelectionScopeId};
use rust_i18n::t;

use crate::{
    ActiveTheme as _, IconName, Root, Sizable as _, StyledExt, TITLE_BAR_HEIGHT, WindowExt as _,
    animation::cubic_bezier,
    button::{Button, ButtonVariant, ButtonVariants as _},
    dialog::{DialogContent, DialogDispatchAnchor, DialogTitle},
    scroll::ScrollableElement as _,
    v_flex,
};

pub static ANIMATION_DURATION: LazyLock<Duration> = LazyLock::new(|| Duration::from_secs_f64(0.25));
pub use gpui_base::actions::{Cancel, Confirm};

/// Dialog button props.
#[derive(Clone)]
pub struct DialogButtonProps {
    pub(crate) ok_text: Option<SharedString>,
    pub(crate) ok_variant: ButtonVariant,
    pub(crate) cancel_text: Option<SharedString>,
    pub(crate) cancel_variant: ButtonVariant,
    pub(crate) show_cancel: bool,
    pub(crate) on_ok: Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static>,
    pub(crate) on_cancel: Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static>,
    pub(crate) on_close: Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>,
}

impl Default for DialogButtonProps {
    fn default() -> Self {
        Self {
            ok_text: None,
            ok_variant: ButtonVariant::Primary,
            cancel_text: None,
            cancel_variant: ButtonVariant::default(),
            show_cancel: false,
            on_ok: Rc::new(|_, _, _| true),
            on_cancel: Rc::new(|_, _, _| true),
            on_close: Rc::new(|_, _, _| {}),
        }
    }
}

impl DialogButtonProps {
    /// Sets the text of the OK button. Default is `OK`.
    pub fn ok_text(mut self, ok_text: impl Into<SharedString>) -> Self {
        self.ok_text = Some(ok_text.into());
        self
    }

    /// Sets the variant of the OK button. Default is `ButtonVariant::Primary`.
    pub fn ok_variant(mut self, ok_variant: ButtonVariant) -> Self {
        self.ok_variant = ok_variant;
        self
    }

    /// Sets the text of the Cancel button. Default is `Cancel`.
    pub fn cancel_text(mut self, cancel_text: impl Into<SharedString>) -> Self {
        self.cancel_text = Some(cancel_text.into());
        self
    }

    /// Sets the variant of the Cancel button. Default is `ButtonVariant::default()`.
    pub fn cancel_variant(mut self, cancel_variant: ButtonVariant) -> Self {
        self.cancel_variant = cancel_variant;
        self
    }

    /// Sets whether to show the Cancel button. Default is `false`.
    pub fn show_cancel(mut self, show_cancel: bool) -> Self {
        self.show_cancel = show_cancel;
        self
    }

    /// Sets the callback for when the dialog is has been confirmed.
    ///
    /// The callback should return `true` to close the dialog, if return `false` the dialog will not be closed.
    pub fn on_ok(
        mut self,
        on_ok: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
    ) -> Self {
        self.on_ok = Rc::new(on_ok);
        self
    }

    /// Sets the callback for when the dialog is has been canceled.
    ///
    /// The callback should return `true` to close the dialog, if return `false` the dialog will not be closed.
    pub fn on_cancel(
        mut self,
        on_cancel: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
    ) -> Self {
        self.on_cancel = Rc::new(on_cancel);
        self
    }

    pub(crate) fn render_ok(&self, _: &mut Window, _: &mut App) -> AnyElement {
        let ok_text = self
            .ok_text
            .clone()
            .unwrap_or_else(|| t!("Dialog.ok").into());

        DialogButton {
            anchor_key: "dialog-ok-anchor",
            button: Button::new("ok")
                .label(ok_text)
                .with_variant(self.ok_variant),
            action: Rc::new(Confirm { secondary: false }),
        }
        .into_any_element()
    }

    pub(crate) fn render_cancel(&self, _: &mut Window, _: &mut App) -> AnyElement {
        let cancel_text = self
            .cancel_text
            .clone()
            .unwrap_or_else(|| t!("Dialog.cancel").into());

        DialogButton {
            anchor_key: "dialog-cancel-anchor",
            button: Button::new("cancel")
                .label(cancel_text)
                .with_variant(self.cancel_variant),
            action: Rc::new(Cancel),
        }
        .into_any_element()
    }
}

/// A default dialog button: activating it dispatches `action` on the dialog
/// it sits in, whatever holds focus at that moment.
#[derive(IntoElement)]
struct DialogButton {
    /// Distinct per button: OK and Cancel render as siblings in one scope.
    anchor_key: &'static str,
    button: Button,
    action: Rc<dyn Action>,
}

impl RenderOnce for DialogButton {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let anchor = DialogDispatchAnchor::new(self.anchor_key, window, cx);
        self.button
            .child(anchor.element())
            .on_click(move |_, window, cx| anchor.dispatch(&*self.action, window, cx))
    }
}

type ContentBuilderFn = Rc<dyn Fn(DialogContent, &mut Window, &mut App) -> DialogContent + 'static>;

#[derive(Clone)]
pub(crate) struct DialogProps {
    width: Pixels,
    max_width: Option<Pixels>,
    margin_top: Option<Pixels>,
    close_button: bool,

    overlay: bool,
    overlay_closable: bool,
    pub(crate) overlay_visible: bool,
    keyboard: bool,
}

impl Default for DialogProps {
    fn default() -> Self {
        Self {
            margin_top: None,
            width: px(448.),
            max_width: None,
            overlay: true,
            keyboard: true,
            overlay_visible: false,
            close_button: true,
            overlay_closable: true,
        }
    }
}

enum BaseDialogRoot {
    Dialog(gpui_base::Dialog),
    AlertDialog(gpui_base::AlertDialog),
}

macro_rules! map_base_root {
    ($self:expr, $method:ident($($arg:expr),* $(,)?)) => {
        match $self {
            BaseDialogRoot::Dialog(root) => BaseDialogRoot::Dialog(root.$method($($arg),*)),
            BaseDialogRoot::AlertDialog(root) => {
                BaseDialogRoot::AlertDialog(root.$method($($arg),*))
            }
        }
    };
}

impl BaseDialogRoot {
    fn layer(self, index: usize, topmost: bool) -> Self {
        map_base_root!(self, layer(index, topmost))
    }
    fn focus_handle(self, focus: FocusHandle) -> Self {
        map_base_root!(self, focus_handle(focus))
    }
    fn close_on_escape(self, value: bool) -> Self {
        map_base_root!(self, close_on_escape(value))
    }
    fn close_on_backdrop_press(self, value: bool) -> Self {
        match self {
            Self::Dialog(root) => Self::Dialog(root.close_on_backdrop_press(value)),
            Self::AlertDialog(root) => Self::AlertDialog(root),
        }
    }
    fn dismiss_below_y(self, value: Pixels) -> Self {
        map_base_root!(self, dismiss_below_y(value))
    }
    fn backdrop(self, element: impl IntoElement) -> Self {
        map_base_root!(self, backdrop(element))
    }
    fn popup(self, element: impl IntoElement) -> Self {
        map_base_root!(self, popup(element))
    }
    fn on_ok(self, handler: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static) -> Self {
        map_base_root!(self, on_ok(handler))
    }
    fn on_cancel(
        self,
        handler: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
    ) -> Self {
        map_base_root!(self, on_cancel(handler))
    }
    fn on_close(self, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self {
        map_base_root!(self, on_close(handler))
    }
    fn request_close(self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
        map_base_root!(self, request_close(handler))
    }
}

impl IntoElement for BaseDialogRoot {
    type Element = <gpui_base::Dialog as IntoElement>::Element;
    fn into_element(self) -> Self::Element {
        match self {
            Self::Dialog(root) => root.into_element(),
            Self::AlertDialog(root) => root.into_element(),
        }
    }
}

/// A modal to display content in a dialog box.
#[derive(IntoElement)]
pub struct Dialog {
    base: Option<BaseDialogRoot>,
    pub(crate) style: StyleRefinement,
    children: Vec<AnyElement>,
    trigger: Option<AnyElement>,
    title: Option<AnyElement>,
    pub(crate) header: Option<AnyElement>,
    pub(crate) footer: Option<AnyElement>,
    pub(crate) content_builder: Option<ContentBuilderFn>,
    pub(crate) props: DialogProps,

    pub(super) button_props: DialogButtonProps,

    /// This will be change when open the dialog, the focus handle is create when open the dialog.
    pub(crate) focus_handle: FocusHandle,
    pub(crate) layer_ix: usize,
    pub(crate) selection_scope: TextSelectionScopeId,
}

pub(crate) fn overlay_color(overlay: bool, cx: &App) -> Hsla {
    if !overlay {
        return hsla(0., 0., 0., 0.);
    }

    cx.theme().overlay
}

impl Dialog {
    /// Create a new dialog.
    pub fn new(cx: &mut App) -> Self {
        Self {
            base: Some(BaseDialogRoot::Dialog(gpui_base::Dialog::new(cx))),
            focus_handle: cx.focus_handle(),
            style: StyleRefinement::default(),
            trigger: None,
            title: None,
            header: None,
            footer: None,
            content_builder: None,
            props: DialogProps::default(),
            children: Vec::new(),
            layer_ix: 0,
            selection_scope: TextSelectionScopeId::default(),
            button_props: DialogButtonProps::default(),
        }
    }

    /// Sets the trigger element for the dialog.
    ///
    /// When a trigger is set, the dialog will render as a trigger button that opens the dialog when clicked.
    pub fn trigger(mut self, trigger: impl IntoElement) -> Self {
        self.trigger = Some(trigger.into_any_element());
        self
    }

    /// Sets the content of the dialog.
    pub fn content<F>(mut self, builder: F) -> Self
    where
        F: Fn(DialogContent, &mut Window, &mut App) -> DialogContent + 'static,
    {
        self.content_builder = Some(Rc::new(builder));
        self
    }

    /// Sets the title of the dialog.
    pub fn title(mut self, title: impl IntoElement) -> Self {
        self.title = Some(title.into_any_element());
        self
    }

    /// Sets the footer of the dialog, the footer will render at the bottom of the dialog, usually for action buttons.
    ///
    /// When you set the footer, the `button_props` will be ignored, you need to render the action buttons by yourself.
    pub(crate) fn header(mut self, header: impl IntoElement) -> Self {
        self.header = Some(header.into_any_element());
        self
    }

    /// Sets the footer of the dialog, the footer will render at the bottom of the dialog, usually for action buttons.
    ///
    /// When you set the footer, the `button_props` will be ignored, you need to render the action buttons by yourself.
    pub fn footer(mut self, footer: impl IntoElement) -> Self {
        self.footer = Some(footer.into_any_element());
        self
    }

    /// Set the button props of the dialog.
    pub fn button_props(mut self, button_props: DialogButtonProps) -> Self {
        self.button_props = button_props;
        self
    }
    pub(crate) fn with_base_alert_dialog(mut self, base: gpui_base::AlertDialog) -> Self {
        self.base = Some(BaseDialogRoot::AlertDialog(base));
        self.props.overlay_closable = false;
        self
    }

    /// Sets the callback for when the dialog is closed.
    ///
    /// Called after [`Self::on_ok`] or [`Self::on_cancel`] callback.
    pub fn on_close(
        mut self,
        on_close: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.button_props.on_close = Rc::new(on_close);
        self
    }

    /// Sets the callback for when the dialog is has been confirmed.
    ///
    /// The callback should return `true` to close the dialog, if return `false` the dialog will not be closed.
    pub fn on_ok(
        mut self,
        on_ok: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
    ) -> Self {
        self.button_props = self.button_props.on_ok(on_ok);
        self
    }

    /// Sets the callback for when the dialog is has been canceled.
    ///
    /// The callback should return `true` to close the dialog, if return `false` the dialog will not be closed.
    pub fn on_cancel(
        mut self,
        on_cancel: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
    ) -> Self {
        self.button_props = self.button_props.on_cancel(on_cancel);
        self
    }

    /// Sets the false to hide close icon, default: true
    pub fn close_button(mut self, close_button: bool) -> Self {
        self.props.close_button = close_button;
        self
    }

    /// Set the top offset of the dialog, defaults to None, will use the 1/10 of the viewport height.
    pub fn margin_top(mut self, margin_top: impl Into<Pixels>) -> Self {
        self.props.margin_top = Some(margin_top.into());
        self
    }

    /// Sets the width of the dialog, defaults to 448px.
    ///
    /// The dialog is never wider than the viewport minus a margin on each side.
    ///
    /// See also [`Self::width`]
    pub fn w(mut self, width: impl Into<Pixels>) -> Self {
        self.props.width = width.into();
        self
    }

    /// Sets the width of the dialog, defaults to 448px.
    ///
    /// The dialog is never wider than the viewport minus a margin on each side.
    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
        self.props.width = width.into();
        self
    }

    /// Set the maximum width of the dialog, defaults to `None`.
    pub fn max_w(mut self, max_width: impl Into<Pixels>) -> Self {
        self.props.max_width = Some(max_width.into());
        self
    }

    /// Set the overlay of the dialog, defaults to `true`.
    pub fn overlay(mut self, overlay: bool) -> Self {
        self.props.overlay = overlay;
        self
    }

    /// Set the overlay closable of the dialog, defaults to `true`.
    ///
    /// When the overlay is clicked, the dialog will be closed.
    pub fn overlay_closable(mut self, overlay_closable: bool) -> Self {
        self.props.overlay_closable = overlay_closable;
        self
    }

    /// Set whether to support keyboard esc to close the dialog, defaults to `true`.
    pub fn keyboard(mut self, keyboard: bool) -> Self {
        self.props.keyboard = keyboard;
        self
    }

    pub(crate) fn has_overlay(&self) -> bool {
        self.props.overlay
    }

    pub(crate) fn with_props(mut self, props: DialogProps) -> Self {
        self.props = props;
        self
    }

    fn defer_close_dialog(window: &mut Window, cx: &mut App) {
        Root::update(window, cx, |root, window, cx| {
            root.defer_close_dialog(window, cx);
        });
    }
}

impl ParentElement for Dialog {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.children.extend(elements);
    }
}

impl Styled for Dialog {
    fn style(&mut self) -> &mut gpui::StyleRefinement {
        &mut self.style
    }
}

impl Dialog {
    fn render_trigger(self, trigger: AnyElement, _: &mut Window, _: &mut App) -> AnyElement {
        let content_builder = self.content_builder.clone();
        let style = self.style.clone();
        let props = self.props.clone();
        let button_props = self.button_props.clone();

        gpui_base::DialogTrigger::new(trigger)
            .on_open(move |window, cx| {
                let content_builder = content_builder.clone();
                let style = style.clone();
                let props = props.clone();
                let button_props = button_props.clone();
                window.open_dialog(cx, move |dialog, _, _| {
                    dialog
                        .refine_style(&style)
                        .button_props(button_props.clone())
                        .with_props(props.clone())
                        .content({
                            let content_builder = content_builder.clone();
                            move |content, window, cx| {
                                if let Some(builder) = content_builder.clone() {
                                    builder(content, window, cx)
                                } else {
                                    content
                                }
                            }
                        })
                });
            })
            .into_any_element()
    }
}

impl RenderOnce for Dialog {
    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        if let Some(trigger) = self.trigger.take() {
            return self.render_trigger(trigger, window, cx);
        }

        let layer_ix = self.layer_ix;
        let selection_scope = self.selection_scope;
        let on_close = self.button_props.on_close.clone();
        let on_ok = self.button_props.on_ok.clone();
        let on_cancel = self.button_props.on_cancel.clone();

        let window_paddings = crate::window_border::window_paddings(window);
        let view_size = window.viewport_size()
            - gpui::size(
                window_paddings.left + window_paddings.right,
                window_paddings.top + window_paddings.bottom,
            );
        // The dialog keeps this much of the viewport clear on the sides and
        // below it, so a small window shrinks the surface instead of the
        // surface running off the window. The top keeps `margin_top` (a tenth
        // of the viewport by default) plus the 16px step of each stacked layer.
        let margin = cx.theme().spacing_tokens().lg;
        let y = self.props.margin_top.unwrap_or(view_size.height / 10.) + px(layer_ix as f32 * 16.);
        let width = self
            .props
            .width
            .min((view_size.width - margin * 2.).max(px(0.)));
        let x = (view_size.width - width) / 2.;
        let max_height = (view_size.height - y - margin).max(px(0.));

        let base_size = window.text_style().font_size;
        let rem_size = window.rem_size();

        let mut paddings = Edges::all(px(16.));
        if let Some(pl) = self.style.padding.left {
            paddings.left = pl.to_pixels(base_size, rem_size);
        }
        if let Some(pr) = self.style.padding.right {
            paddings.right = pr.to_pixels(base_size, rem_size);
        }
        if let Some(pt) = self.style.padding.top {
            paddings.top = pt.to_pixels(base_size, rem_size);
        }
        if let Some(pb) = self.style.padding.bottom {
            paddings.bottom = pb.to_pixels(base_size, rem_size);
        }

        // x1 = 1/3, x2 = 2/3 make the bezier's time mapping the identity,
        // preserving the trajectory this dialog was tuned with before
        // `cubic_bezier` solved for x; vaul's (0.32, 0.72, 0., 1.) is far
        // more front-loaded under the CSS-correct solver.
        let animation = Animation::new(*ANIMATION_DURATION).with_easing(cubic_bezier(
            1. / 3.,
            0.72,
            2. / 3.,
            1.,
        ));

        anchored()
            .position(point(window_paddings.left, window_paddings.top))
            .snap_to_window()
            .child(
                div()
                    .id("dialog")
                    .test_support()
                    .occlude()
                    .w(view_size.width)
                    .h(view_size.height)
                    .child(
                        self.base
                            .take()
                            .expect("Dialog base host is always present")
                            .layer(
                                layer_ix,
                                (self.layer_ix + 1) == Root::read(window, cx).active_dialogs.len(),
                            )
                            .focus_handle(self.focus_handle.clone())
                            .close_on_escape(self.props.keyboard)
                            .close_on_backdrop_press(self.props.overlay_closable)
                            .dismiss_below_y(TITLE_BAR_HEIGHT)
                            .when(self.props.overlay, |this| {
                                this.backdrop(
                                    div()
                                        .absolute()
                                        .size_full()
                                        .window_control_area(WindowControlArea::Drag)
                                        .when(self.props.overlay_visible, |overlay| {
                                            overlay.bg(overlay_color(true, cx))
                                        }),
                                )
                            })
                            .on_ok(move |event, window, cx| on_ok(event, window, cx))
                            .on_cancel(move |event, window, cx| on_cancel(event, window, cx))
                            .on_close(move |event, window, cx| on_close(event, window, cx))
                            .request_close(move |deferred, window, cx| {
                                if deferred {
                                    Self::defer_close_dialog(window, cx);
                                } else {
                                    window.close_dialog(cx);
                                }
                            })
                            .popup(
                                v_flex()
                                    .id(layer_ix)
                                    .test_support()
                                    .debug_selector(move || format!("dialog-{layer_ix}"))
                                    .bg(cx.theme().tokens.background)
                                    .border_1()
                                    .border_color(cx.theme().border)
                                    .rounded(cx.theme().radius_lg)
                                    .min_h_24()
                                    .pt(paddings.top)
                                    .pb(paddings.bottom)
                                    .gap(paddings.top.max(px(8.)))
                                    .refine_style(&self.style)
                                    .px_0()
                                    // There style is high priority, can't be overridden.
                                    .absolute()
                                    .occlude()
                                    .relative()
                                    .left(x)
                                    .top(y)
                                    .w(width)
                                    .when_some(self.props.max_width, |this, w| this.max_w(w))
                                    .max_h(max_height)
                                    .child(
                                        v_flex()
                                            .flex_1()
                                            .overflow_hidden()
                                            .gap_y_2()
                                            .when_some(self.header, |this, header| {
                                                this.child(
                                                    div()
                                                        .pl(paddings.left)
                                                        .pr(paddings.right)
                                                        .child(header),
                                                )
                                            })
                                            .when_some(self.title, |this, title| {
                                                this.child(
                                                    DialogTitle::new()
                                                        .pl(paddings.left)
                                                        .pr(paddings.right)
                                                        .child(title),
                                                )
                                            })
                                            .when_some(self.content_builder, |this, builder| {
                                                this.child(builder(
                                                    DialogContent::new()
                                                        .gap(paddings.bottom)
                                                        .pl(paddings.left)
                                                        .pr(paddings.right),
                                                    window,
                                                    cx,
                                                ))
                                            })
                                            .when(!self.children.is_empty(), |this| {
                                                this.child(
                                                    div().flex_1().overflow_hidden().child(
                                                        // Body
                                                        v_flex()
                                                            .size_full()
                                                            .overflow_y_scrollbar()
                                                            .pl(paddings.left)
                                                            .pr(paddings.right)
                                                            .children(self.children),
                                                    ),
                                                )
                                            }),
                                    )
                                    .when_some(self.footer, |this, footer| {
                                        this.child(
                                            div()
                                                .pl(paddings.left)
                                                .pr(paddings.right)
                                                .child(footer),
                                        )
                                    })
                                    .children(self.props.close_button.then(|| {
                                        let top = (paddings.top - px(10.)).max(px(8.));
                                        let right = (paddings.right - px(10.)).max(px(8.));

                                        gpui_base::DialogClose::new()
                                            .absolute()
                                            .top(top)
                                            .right(right)
                                            .trigger(|button| {
                                                Button::new("close")
                                                    .with_base(button)
                                                    .small()
                                                    .ghost()
                                                    .icon(IconName::Close)
                                            })
                                    }))
                                    .with_animation(
                                        "slide-down",
                                        animation.clone(),
                                        move |this, delta| {
                                            // This is equivalent to `shadow_xl` with an extra opacity.
                                            let shadow = vec![
                                                BoxShadow {
                                                    color: hsla(0., 0., 0., 0.1 * delta),
                                                    offset: point(px(0.), px(20.)),
                                                    blur_radius: px(25.),
                                                    spread_radius: px(-5.),
                                                    inset: false,
                                                },
                                                BoxShadow {
                                                    color: hsla(0., 0., 0., 0.1 * delta),
                                                    offset: point(px(0.), px(8.)),
                                                    blur_radius: px(10.),
                                                    spread_radius: px(-6.),
                                                    inset: false,
                                                },
                                            ];
                                            this.top(y * delta).shadow(shadow)
                                        },
                                    )
                                    .text_selection_scope(selection_scope),
                            ),
                    )
                    .with_animation("fade-in", animation, move |this, delta| this.opacity(delta)),
            )
            .into_any_element()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use gpui::{AppContext as _, Bounds, Context, Render, TestAppContext, VisualTestContext, size};

    struct DialogHost;

    impl Render for DialogHost {
        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            div()
                .size_full()
                .children(Root::render_dialog_layer(window, cx))
        }
    }

    /// A window of `window_size` whose root renders the dialog layer, with
    /// motion reduced so the entrance animation settles on its first frame.
    fn window(cx: &mut TestAppContext, window_size: gpui::Size<Pixels>) -> &mut VisualTestContext {
        cx.update(|cx| {
            crate::init(cx);
            cx.set_reduce_motion(true);
        });
        let (_, cx) = cx.add_window_view(|window, cx| {
            let view = cx.new(|_| DialogHost);
            Root::new(view, window, cx)
        });
        cx.simulate_resize(window_size);
        cx.update(|window, cx| window.draw(cx).clear(cx));
        cx
    }

    fn open(
        cx: &mut VisualTestContext,
        build: impl Fn(Dialog, &mut Window, &mut App) -> Dialog + 'static,
    ) {
        cx.update(|window, cx| window.open_dialog(cx, build));
        cx.run_until_parked();
        // One frame mounts the layer, the next paints it at rest.
        cx.update(|window, cx| window.draw(cx).clear(cx));
        cx.update(|window, cx| window.draw(cx).clear(cx));
    }

    fn surface(cx: &mut VisualTestContext, layer_ix: usize) -> Bounds<Pixels> {
        let selector = ["dialog-0", "dialog-1"][layer_ix];
        cx.debug_bounds(selector)
            .unwrap_or_else(|| panic!("dialog layer {layer_ix} was not painted"))
    }

    /// The clamp must not touch a dialog that already fits: the default width
    /// and the tenth-of-the-viewport top offset are the documented contract.
    #[gpui::test]
    fn a_dialog_that_fits_keeps_its_default_width_and_top_offset(cx: &mut TestAppContext) {
        let cx = window(cx, size(px(1000.), px(800.)));
        open(cx, |dialog, _, _| dialog.title("Fits").child("body"));

        let bounds = surface(cx, 0);
        assert_eq!(bounds.size.width, px(448.));
        assert_eq!(bounds.origin.x, px(276.));
        assert_eq!(bounds.origin.y, px(80.));
    }

    /// A dialog wider and taller than the window must shrink to the viewport
    /// instead of running off both edges, and its footer must still be inside
    /// the surface rather than clipped below it.
    #[gpui::test]
    fn a_dialog_larger_than_the_window_stays_inside_it(cx: &mut TestAppContext) {
        let viewport = size(px(400.), px(300.));
        let cx = window(cx, viewport);
        open(cx, |dialog, _, _| {
            dialog
                .w(px(800.))
                .title("Too big")
                .child(div().h(px(1000.)).child("tall body"))
                .footer(div().h(px(32.)).debug_selector(|| "footer-probe".into()))
        });

        let bounds = surface(cx, 0);
        let footer = cx.debug_bounds("footer-probe").unwrap();
        let margin = px(16.);
        assert!(
            bounds.origin.x >= margin && bounds.right() <= viewport.width - margin,
            "the dialog ran off the sides: {bounds:?}"
        );
        assert!(
            bounds.bottom() <= viewport.height - margin,
            "the dialog ran off the bottom: {bounds:?}"
        );
        assert_eq!(bounds.origin.y, viewport.height / 10.);
        assert!(
            footer.bottom() <= bounds.bottom(),
            "the footer was clipped below the dialog: footer {footer:?}, dialog {bounds:?}"
        );
    }

    /// Each stacked dialog steps down 16px; the deepest one must still end
    /// above the bottom margin.
    #[gpui::test]
    fn stacked_dialogs_each_fit_the_window(cx: &mut TestAppContext) {
        let viewport = size(px(400.), px(300.));
        let cx = window(cx, viewport);
        open(cx, |dialog, _, _| {
            dialog.title("First").child(div().h(px(1000.)))
        });
        open(cx, |dialog, _, _| {
            dialog.title("Second").child(div().h(px(1000.)))
        });

        let first = surface(cx, 0);
        let second = surface(cx, 1);
        assert_eq!(second.origin.y, first.origin.y + px(16.));
        assert!(first.bottom() <= viewport.height - px(16.), "{first:?}");
        assert!(second.bottom() <= viewport.height - px(16.), "{second:?}");
        assert!(second.size.height < first.size.height);
    }
}