Skip to main content

arc_ui/overlay/
drawer.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/drawer/drawer.tsx` & `.module.css`
3//!
4//! P3 Component #8: `drawer`
5//!
6//! - Edge-anchored sliding panel (`DrawerSide::Right | Left | Top | Bottom`), optionally scoped
7//!   inside a container (`contained(true)`) instead of the full window viewport.
8//! - Backdrop overlay (`oklch(10% 0 0 / .38)` full-screen or `.16` when contained) fades in over
9//!   `duration.standard` (`220ms`, `ease.enter`) and out over `duration.fast` (`160ms`,
10//!   `ease.standard`).
11//! - Panel springs fully opaque from its own edge on `motion.spring.smooth` (`0.35s, bounce 0`) and
12//!   returns over `duration.standard` (`220ms`). Its shadow/opacity stays at `1.0` for the first
13//!   `65%` of the exit and fades out over the final `35%` (`drawer_exit_opacity`) so the floating
14//!   shadow leaves with the panel instead of popping at unmount.
15//! - The header doubles as a drag handle: dragging toward the anchored edge follows 1:1, dragging
16//!   away rubber-bands via `-\sqrt{-d}` (`drawer_pan_offset`). Releasing past `1/3` of the panel
17//!   size or with velocity `> 500 px/s` toward the edge flings the drawer closed; otherwise it
18//!   snaps back to `0` on `motion.spring.snappy`.
19//! - `DrawerSide::Bottom` renders the top pill grab indicator (`36×4px`, `top: 9px`, `75%` opacity).
20//! - Live changes to `title` or `description` while open animate via `swap_text_sample`.
21
22use std::{cell::RefCell, rc::Rc};
23
24use arc_motion::{
25    ArcPresence, ArcPresenceConfig, arc_spring, arc_spring_with_options, is_reduced_motion,
26    motion_now, spring::SpringOptions,
27};
28use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
29use gpui_kit::{
30    AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
31    MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, PathBuilder, Pixels, Point,
32    RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window, base::StyledExt as _,
33    canvas, deferred, div, point, prelude::*, px,
34};
35
36use crate::overlay::dialog::swap_text_sample;
37
38/// Default drawer width for `Left`/`Right` (`30rem = 480px`, or `22rem = 352px` when contained).
39pub const DRAWER_WIDTH: f32 = 480.0;
40pub const DRAWER_CONTAINED_WIDTH: f32 = 352.0;
41/// Maximum height for `Top`/`Bottom` drawers (`32rem = 512px`).
42pub const DRAWER_MAX_VERTICAL_SIZE: f32 = 512.0;
43/// Corner radius on the inner face of the drawer (`12px`, shadcn Sheet).
44pub const DRAWER_INNER_RADIUS: f32 = 12.0;
45/// Fling velocity threshold (`500 px/s`) toward the anchored edge.
46pub const DRAWER_FLING_VELOCITY: f32 = 500.0;
47
48/// Which viewport (or container) edge the drawer slides from.
49#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
50pub enum DrawerSide {
51    #[default]
52    Right,
53    Left,
54    Top,
55    Bottom,
56}
57
58impl DrawerSide {
59    pub const ALL: [DrawerSide; 4] = [Self::Right, Self::Left, Self::Top, Self::Bottom];
60
61    /// `+1.0` for `Right` / `Bottom` (positive coordinate moves toward the edge), `-1.0` for
62    /// `Left` / `Top`.
63    pub const fn edge_sign(self) -> f32 {
64        match self {
65            Self::Right | Self::Bottom => 1.0,
66            Self::Left | Self::Top => -1.0,
67        }
68    }
69
70    pub const fn is_horizontal(self) -> bool {
71        matches!(self, Self::Left | Self::Right)
72    }
73
74    pub const fn label(self) -> &'static str {
75        match self {
76            Self::Right => "Right",
77            Self::Left => "Left",
78            Self::Top => "Top",
79            Self::Bottom => "Bottom",
80        }
81    }
82}
83
84/// Computes the drag displacement (`px`) along the drawer's axis given raw delta `raw_delta_px`.
85///
86/// Follows the pointer 1:1 when dragging toward the anchored edge (`toward >= 0`) and rubber-bands
87/// via `-\sqrt{-toward}` when pulling away from the edge.
88pub fn drawer_pan_offset(side: DrawerSide, raw_delta_px: f32) -> f32 {
89    let sign = side.edge_sign();
90    let toward = raw_delta_px * sign;
91    let clamped = if toward >= 0.0 {
92        toward
93    } else {
94        -(-toward).sqrt()
95    };
96    sign * clamped
97}
98
99/// Whether releasing a header drag should fling the drawer closed (`toward > size / 3` or
100/// `toward > 0 && velocity_toward > 500`).
101pub fn drawer_should_dismiss(
102    side: DrawerSide,
103    offset_px: f32,
104    velocity_px_per_sec: f32,
105    panel_extent_px: f32,
106) -> bool {
107    let sign = side.edge_sign();
108    let toward = offset_px * sign;
109    let vel_toward = velocity_px_per_sec * sign;
110    let threshold = (panel_extent_px / 3.0).max(40.0);
111    toward > threshold || (toward > 0.0 && vel_toward > DRAWER_FLING_VELOCITY)
112}
113
114/// Computes the panel opacity during exit (`1.0` for the first `65%` of the leave, then linear to
115/// `0.0` over the remaining `35%`).
116pub fn drawer_exit_opacity(is_open: bool, presence_progress: f32, reduced: bool) -> f32 {
117    let p = presence_progress.clamp(0.0, 1.0);
118    if reduced || is_open {
119        return p;
120    }
121    let exit_elapsed_fraction = 1.0 - p;
122    if exit_elapsed_fraction <= 0.65 {
123        1.0
124    } else {
125        ((1.0 - exit_elapsed_fraction) / 0.35).clamp(0.0, 1.0)
126    }
127}
128
129type OpenCallback = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
130
131fn paint_close_x(cx: f32, cy: f32, scale: f32, color: Hsla, window: &mut Window) {
132    let r = 4.2 * scale;
133    for (x1, y1, x2, y2) in [
134        (cx - r, cy - r, cx + r, cy + r),
135        (cx + r, cy - r, cx - r, cy + r),
136    ] {
137        let mut b = PathBuilder::stroke(px(1.75));
138        b.move_to(point(px(x1), px(y1)));
139        b.line_to(point(px(x2), px(y2)));
140        if let Ok(path) = b.build() {
141            window.paint_path(path, color);
142        }
143    }
144}
145
146#[derive(Clone)]
147struct DrawerInternal {
148    open: bool,
149    was_open: bool,
150    last_side: DrawerSide,
151    slide_epoch: u64,
152    opened_at_secs: f64,
153    close_hovered: bool,
154    close_pressed: bool,
155    dragging: bool,
156    drag_start_pt: Point<Pixels>,
157    drag_last_pt: Point<Pixels>,
158    drag_last_at: f64,
159    drag_velocity: f32,
160    drag_offset: f32,
161    prev_title: Option<SharedString>,
162    last_title: SharedString,
163    title_changed_at: f64,
164    prev_desc: Option<SharedString>,
165    last_desc: SharedString,
166    desc_changed_at: f64,
167    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
168    panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
169    focus_handle: FocusHandle,
170}
171
172impl DrawerInternal {
173    fn new(
174        default_open: bool,
175        side: DrawerSide,
176        title: SharedString,
177        desc: SharedString,
178        now: f64,
179        focus_handle: FocusHandle,
180    ) -> Self {
181        Self {
182            open: default_open,
183            was_open: default_open,
184            last_side: side,
185            slide_epoch: 0,
186            opened_at_secs: now - 10.0,
187            close_hovered: false,
188            close_pressed: false,
189            dragging: false,
190            drag_start_pt: point(px(0.0), px(0.0)),
191            drag_last_pt: point(px(0.0), px(0.0)),
192            drag_last_at: now,
193            drag_velocity: 0.0,
194            drag_offset: 0.0,
195            prev_title: None,
196            last_title: title,
197            title_changed_at: now - 10.0,
198            prev_desc: None,
199            last_desc: desc,
200            desc_changed_at: now - 10.0,
201            trigger_bounds: Rc::new(RefCell::new(None)),
202            panel_bounds: Rc::new(RefCell::new(None)),
203            focus_handle,
204        }
205    }
206}
207
208/// Arc `Drawer` — edge-anchored sliding sheet with header pan-to-dismiss, rubber-banding, late
209/// shadow fade, and `SwapText` header transitions.
210#[derive(IntoElement)]
211pub struct Drawer {
212    id: ElementId,
213    title: SharedString,
214    description: Option<SharedString>,
215    side: DrawerSide,
216    contained: bool,
217    trigger: Option<AnyElement>,
218    body: Option<AnyElement>,
219    open: Option<bool>,
220    default_open: bool,
221    on_open_change: Option<OpenCallback>,
222}
223
224impl Drawer {
225    pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
226        Self {
227            id: id.into(),
228            title: title.into(),
229            description: None,
230            side: DrawerSide::Right,
231            contained: false,
232            trigger: None,
233            body: None,
234            open: None,
235            default_open: false,
236            on_open_change: None,
237        }
238    }
239
240    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
241        self.description = Some(description.into());
242        self
243    }
244
245    pub fn side(mut self, side: DrawerSide) -> Self {
246        self.side = side;
247        self
248    }
249
250    /// Anchors the drawer inside its parent container (`position: relative; overflow: hidden`)
251    /// rather than the full window viewport.
252    pub fn contained(mut self, contained: bool) -> Self {
253        self.contained = contained;
254        self
255    }
256
257    pub fn trigger(mut self, trigger: impl IntoElement) -> Self {
258        self.trigger = Some(trigger.into_any_element());
259        self
260    }
261
262    pub fn content(mut self, body: impl IntoElement) -> Self {
263        self.body = Some(body.into_any_element());
264        self
265    }
266
267    pub fn open(mut self, open: bool) -> Self {
268        self.open = Some(open);
269        self
270    }
271
272    pub fn default_open(mut self, default_open: bool) -> Self {
273        self.default_open = default_open;
274        self
275    }
276
277    pub fn on_open_change(
278        mut self,
279        handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
280    ) -> Self {
281        self.on_open_change = Some(Rc::new(handler));
282        self
283    }
284}
285
286#[allow(clippy::too_many_arguments)]
287fn render_swap_slot(
288    old_text: Option<SharedString>,
289    new_text: SharedString,
290    elapsed: f64,
291    reduced: bool,
292    line_height_px: f32,
293    text_size: Pixels,
294    font_medium: bool,
295    color: Hsla,
296) -> AnyElement {
297    let (old_alpha, old_y, new_alpha, new_y) = swap_text_sample(elapsed, reduced);
298    let swapping = old_text.is_some() && old_alpha > 0.01;
299
300    if !swapping {
301        return div()
302            .line_height(px(line_height_px))
303            .text_size(text_size)
304            .when(font_medium, |d| d.font_medium())
305            .text_color(color)
306            .child(new_text)
307            .into_any_element();
308    }
309
310    div()
311        .relative()
312        .min_h(px(line_height_px))
313        .child(
314            div()
315                .line_height(px(line_height_px))
316                .text_size(text_size)
317                .when(font_medium, |d| d.font_medium())
318                .text_color(color)
319                .opacity(new_alpha)
320                .mt(px(new_y))
321                .child(new_text),
322        )
323        .when_some(old_text, |d, old| {
324            d.child(
325                div()
326                    .absolute()
327                    .top(px(old_y))
328                    .left_0()
329                    .right_0()
330                    .line_height(px(line_height_px))
331                    .text_size(text_size)
332                    .when(font_medium, |d| d.font_medium())
333                    .text_color(color)
334                    .opacity(old_alpha)
335                    .child(old),
336            )
337        })
338        .into_any_element()
339}
340
341impl RenderOnce for Drawer {
342    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
343        let theme = cx.arc_theme().clone();
344        let colors = theme.colors;
345        let motion = theme.motion;
346        let reduced = is_reduced_motion(cx);
347        let now = motion_now(cx);
348
349        let desc_str = self.description.clone().unwrap_or_default();
350        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-drawer-state".into());
351        let title_init = self.title.clone();
352        let desc_init = desc_str.clone();
353        let side = self.side;
354        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
355            DrawerInternal::new(
356                self.default_open,
357                side,
358                title_init,
359                desc_init,
360                now,
361                cx.focus_handle(),
362            )
363        });
364
365        // Detect live title / description changes and side switches.
366        {
367            let snap = internal.read(cx).clone();
368            let is_open_now = self.open.unwrap_or(snap.open);
369            if snap.last_side != side || snap.was_open != is_open_now {
370                internal.update(cx, |s, _| {
371                    if s.last_side != side || (!s.was_open && is_open_now) {
372                        s.slide_epoch = s.slide_epoch.wrapping_add(1);
373                    }
374                    s.last_side = side;
375                    s.was_open = is_open_now;
376                });
377            }
378            if snap.last_title != self.title {
379                let prev = snap.last_title.clone();
380                let next = self.title.clone();
381                internal.update(cx, |s, _| {
382                    if is_open_now {
383                        s.prev_title = Some(prev);
384                        s.title_changed_at = now;
385                    }
386                    s.last_title = next;
387                });
388            }
389            if snap.last_desc != desc_str {
390                let prev = snap.last_desc.clone();
391                let next = desc_str.clone();
392                internal.update(cx, |s, _| {
393                    if is_open_now && !prev.is_empty() {
394                        s.prev_desc = Some(prev);
395                        s.desc_changed_at = now;
396                    }
397                    s.last_desc = next;
398                });
399            }
400        }
401
402        let snap = internal.read(cx).clone();
403        let is_open = self.open.unwrap_or(snap.open);
404
405        let overlay_presence = ArcPresence::new((self.id.clone(), "drawer-overlay"), is_open)
406            .animate_initial(false)
407            .config(ArcPresenceConfig {
408                enter_duration: motion.duration.standard,
409                exit_duration: motion.duration.fast,
410                enter_ease: motion.ease.enter,
411                exit_ease: motion.ease.standard,
412                fade_on_reduced_motion: true,
413            })
414            .sample(window, cx);
415
416        let panel_presence = ArcPresence::new((self.id.clone(), "drawer-panel"), is_open)
417            .animate_initial(false)
418            .config(ArcPresenceConfig {
419                enter_duration: motion.duration.standard,
420                exit_duration: motion.duration.standard,
421                enter_ease: motion.ease.enter,
422                exit_ease: motion.ease.standard,
423                fade_on_reduced_motion: true,
424            })
425            .sample(window, cx);
426
427        let viewport = window.viewport_size();
428        let base_extent = if side.is_horizontal() {
429            let max_w = if self.contained {
430                DRAWER_CONTAINED_WIDTH
431            } else {
432                DRAWER_WIDTH
433            };
434            (f32::from(viewport.width) - 16.0).clamp(220.0_f32.min(max_w), max_w)
435        } else {
436            (f32::from(viewport.height) - 32.0).clamp(
437                200.0_f32.min(DRAWER_MAX_VERTICAL_SIZE),
438                DRAWER_MAX_VERTICAL_SIZE,
439            )
440        };
441
442        // Slide spring (`0.0` when open, `edge_sign * base_extent` when closed) plus active drag offset.
443        // Keyed by `(side, slide_epoch)` and seeded with `initial_value = closed_slide` so that
444        // opening a side for the first time or after switching sides always starts from that side's
445        // own anchored edge (`+base_extent` for Right/Bottom, `-base_extent` for Left/Top).
446        let side_key = side.label();
447        let slide_epoch = snap.slide_epoch;
448        let closed_slide = side.edge_sign() * base_extent;
449        let target_slide = if is_open { 0.0 } else { closed_slide };
450        let slide_spring = if reduced {
451            0.0
452        } else {
453            arc_spring_with_options(
454                (
455                    self.id.clone(),
456                    format!("drawer-slide-{side_key}-{slide_epoch}"),
457                ),
458                target_slide,
459                SpringOptions::new(motion.spring.smooth).with_initial_value(closed_slide),
460                window,
461                cx,
462            )
463            .value
464        };
465        let drag_offset = if reduced {
466            0.0
467        } else if snap.dragging {
468            let _ = arc_spring_with_options(
469                (self.id.clone(), format!("drawer-drag-{side_key}")),
470                snap.drag_offset,
471                SpringOptions::new(motion.spring.snappy),
472                window,
473                cx,
474            );
475            snap.drag_offset
476        } else {
477            arc_spring(
478                (self.id.clone(), format!("drawer-drag-{side_key}")),
479                0.0,
480                motion.spring.snappy,
481                window,
482                cx,
483            )
484        };
485        let total_shift = slide_spring + drag_offset;
486        let panel_alpha = drawer_exit_opacity(is_open, panel_presence.progress, reduced);
487
488        let title_elapsed = (now - snap.title_changed_at).max(0.0);
489        let desc_elapsed = (now - snap.desc_changed_at).max(0.0);
490        if is_open && !reduced && (title_elapsed < 0.23 || desc_elapsed < 0.23) {
491            window.request_animation_frame();
492        }
493
494        let trigger_bounds_ref = snap.trigger_bounds.clone();
495        let trigger_probe = canvas(
496            move |rect, _, _| {
497                *trigger_bounds_ref.borrow_mut() = Some(rect);
498            },
499            |_, _, _, _| {},
500        )
501        .absolute()
502        .inset_0();
503
504        let internal_trig = internal.clone();
505        let on_open_trig = self.on_open_change.clone();
506        let focus_trig = snap.focus_handle.clone();
507        let mut root = div()
508            .id(self.id.clone())
509            .test_support()
510            .relative()
511            .flex()
512            .child(trigger_probe);
513
514        if let Some(trig) = self.trigger {
515            root = root.child(
516                div()
517                    .id(ElementId::NamedChild(
518                        self.id.clone().into(),
519                        "trigger".into(),
520                    ))
521                    .test_support()
522                    .role(Role::Button)
523                    .aria_label("Open drawer")
524                    .relative()
525                    .flex()
526                    .cursor_pointer()
527                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
528                        let t = motion_now(cx);
529                        internal_trig.update(cx, |s, _| {
530                            s.open = true;
531                            s.opened_at_secs = t;
532                            s.dragging = false;
533                            s.drag_offset = 0.0;
534                        });
535                        focus_trig.focus(window, cx);
536                        if let Some(h) = &on_open_trig {
537                            h(&true, window, cx);
538                        }
539                        window.refresh();
540                    })
541                    .child(trig),
542            );
543        }
544
545        if !overlay_presence.should_render() && !panel_presence.should_render() {
546            return root;
547        }
548
549        if is_open && !snap.focus_handle.is_focused(window) {
550            snap.focus_handle.focus(window, cx);
551        }
552
553        // Panel bounds + window-level drag tracking & outside-press dismissal.
554        let panel_bounds_ref = snap.panel_bounds.clone();
555        let panel_bounds_out = snap.panel_bounds.clone();
556        let trig_bounds_out = snap.trigger_bounds.clone();
557        let internal_events = internal.clone();
558        let on_open_events = self.on_open_change.clone();
559        let opened_at = snap.opened_at_secs;
560        let is_dragging = snap.dragging;
561
562        let panel_probe = canvas(
563            move |rect, _, _| {
564                *panel_bounds_ref.borrow_mut() = Some(rect);
565            },
566            move |_, _, window, _| {
567                if is_open {
568                    let p_ref = panel_bounds_out.clone();
569                    let t_ref = trig_bounds_out.clone();
570                    let st = internal_events.clone();
571                    let cb = on_open_events.clone();
572                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
573                        if !phase.bubble() {
574                            return;
575                        }
576                        let t_now = motion_now(cx);
577                        if (t_now - opened_at).abs() < 0.001 {
578                            return;
579                        }
580                        let in_panel = p_ref.borrow().is_some_and(|b| b.contains(&event.position));
581                        let in_trig = t_ref.borrow().is_some_and(|b| b.contains(&event.position));
582                        if !in_panel && !in_trig {
583                            st.update(cx, |s, _| {
584                                s.open = false;
585                                s.dragging = false;
586                                s.drag_offset = 0.0;
587                            });
588                            if let Some(h) = &cb {
589                                h(&false, window, cx);
590                            }
591                            window.refresh();
592                        }
593                    });
594                }
595                if is_dragging {
596                    let st_move = internal_events.clone();
597                    window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
598                        if !phase.bubble() {
599                            return;
600                        }
601                        let t_now = motion_now(cx);
602                        st_move.update(cx, |s, _| {
603                            if !s.dragging {
604                                return;
605                            }
606                            let raw_delta = if side.is_horizontal() {
607                                f32::from(event.position.x - s.drag_start_pt.x)
608                            } else {
609                                f32::from(event.position.y - s.drag_start_pt.y)
610                            };
611                            let step_delta = if side.is_horizontal() {
612                                f32::from(event.position.x - s.drag_last_pt.x)
613                            } else {
614                                f32::from(event.position.y - s.drag_last_pt.y)
615                            };
616                            let dt = (t_now - s.drag_last_at).max(0.004) as f32;
617                            s.drag_velocity = step_delta / dt;
618                            s.drag_last_pt = event.position;
619                            s.drag_last_at = t_now;
620                            s.drag_offset = drawer_pan_offset(side, raw_delta);
621                        });
622                        window.refresh();
623                    });
624
625                    let st_up = internal_events.clone();
626                    let cb_up = on_open_events.clone();
627                    let p_ref_up = panel_bounds_out.clone();
628                    window.on_mouse_event(move |_: &MouseUpEvent, phase, window, cx| {
629                        if !phase.bubble() {
630                            return;
631                        }
632                        let extent = p_ref_up
633                            .borrow()
634                            .map(|b| {
635                                if side.is_horizontal() {
636                                    f32::from(b.size.width)
637                                } else {
638                                    f32::from(b.size.height)
639                                }
640                            })
641                            .unwrap_or(base_extent);
642                        let (offset, vel) = {
643                            let r = st_up.read(cx);
644                            (r.drag_offset, r.drag_velocity)
645                        };
646                        let dismiss = drawer_should_dismiss(side, offset, vel, extent);
647                        st_up.update(cx, |s, _| {
648                            s.dragging = false;
649                            s.drag_offset = 0.0;
650                            s.drag_velocity = 0.0;
651                            if dismiss {
652                                s.open = false;
653                            }
654                        });
655                        if dismiss && let Some(h) = &cb_up {
656                            h(&false, window, cx);
657                        }
658                        window.refresh();
659                    });
660                }
661            },
662        )
663        .absolute()
664        .inset_0();
665
666        // Close button (`32×32`, `65%` surface_muted fill).
667        let close_bg = if snap.close_hovered || snap.close_pressed {
668            colors.surface_muted
669        } else {
670            oklab_mix(colors.surface_muted, Hsla::transparent_black(), 0.65)
671        };
672        let close_fg = if snap.close_hovered || snap.close_pressed {
673            colors.foreground
674        } else {
675            colors.text_secondary
676        };
677        let close_scale = if snap.close_pressed && !reduced {
678            0.92
679        } else {
680            1.0
681        };
682        let int_close_hover = internal.clone();
683        let int_close_down = internal.clone();
684        let int_close_up = internal.clone();
685        let on_open_close = self.on_open_change.clone();
686
687        let close_btn = div()
688            .id(ElementId::NamedChild(
689                self.id.clone().into(),
690                "close".into(),
691            ))
692            .test_support()
693            .role(Role::Button)
694            .aria_label("Close drawer")
695            .flex_none()
696            .w(Spacing::S8)
697            .h(Spacing::S8)
698            .rounded(Radii::CONTROL)
699            .border_1()
700            .border_color(colors.border)
701            .bg(close_bg)
702            .cursor_pointer()
703            .on_hover(move |hovered, window, cx| {
704                int_close_hover.update(cx, |s, _| {
705                    s.close_hovered = *hovered;
706                    if !*hovered {
707                        s.close_pressed = false;
708                    }
709                });
710                window.refresh();
711            })
712            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
713                cx.stop_propagation();
714                int_close_down.update(cx, |s, _| {
715                    s.close_pressed = true;
716                });
717                window.refresh();
718            })
719            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
720                cx.stop_propagation();
721                int_close_up.update(cx, |s, _| {
722                    s.close_pressed = false;
723                    s.open = false;
724                    s.dragging = false;
725                    s.drag_offset = 0.0;
726                });
727                if let Some(h) = &on_open_close {
728                    h(&false, window, cx);
729                }
730                window.refresh();
731            })
732            .child(
733                canvas(
734                    |_, _, _| {},
735                    move |rect, _, window, _| {
736                        let cx = f32::from(rect.origin.x) + f32::from(rect.size.width) * 0.5;
737                        let cy = f32::from(rect.origin.y) + f32::from(rect.size.height) * 0.5;
738                        paint_close_x(cx, cy, close_scale, close_fg, window);
739                    },
740                )
741                .size_full(),
742            );
743
744        let title_slot = render_swap_slot(
745            snap.prev_title.clone(),
746            self.title.clone(),
747            title_elapsed,
748            reduced,
749            24.0,
750            Typography::TEXT_LG,
751            true,
752            colors.foreground,
753        );
754
755        let desc_slot = self.description.as_ref().map(|d| {
756            render_swap_slot(
757                snap.prev_desc.clone(),
758                d.clone(),
759                desc_elapsed,
760                reduced,
761                21.0,
762                Typography::TEXT_SM,
763                false,
764                colors.text_secondary,
765            )
766        });
767
768        let int_pan_start = internal.clone();
769        let header = div()
770            .id(ElementId::NamedChild(
771                self.id.clone().into(),
772                "header".into(),
773            ))
774            .test_support()
775            .w_full()
776            .flex_none()
777            .flex()
778            .items_start()
779            .justify_between()
780            .gap(Spacing::S5)
781            .p(Spacing::S6)
782            .border_b_1()
783            .border_color(colors.border)
784            .on_mouse_down(
785                MouseButton::Left,
786                move |event: &MouseDownEvent, window, cx| {
787                    if reduced {
788                        return;
789                    }
790                    let t = motion_now(cx);
791                    int_pan_start.update(cx, |s, _| {
792                        s.dragging = true;
793                        s.drag_start_pt = event.position;
794                        s.drag_last_pt = event.position;
795                        s.drag_last_at = t;
796                        s.drag_velocity = 0.0;
797                        s.drag_offset = 0.0;
798                    });
799                    window.refresh();
800                },
801            )
802            .child(
803                div()
804                    .flex_1()
805                    .flex()
806                    .flex_col()
807                    .gap(Spacing::S2)
808                    .child(title_slot)
809                    .when_some(desc_slot, |d, desc| d.child(desc)),
810            )
811            .child(close_btn);
812
813        let body = div()
814            .id(ElementId::NamedChild(self.id.clone().into(), "body".into()))
815            .w_full()
816            .flex_1()
817            .min_h_0()
818            .overflow_y_scroll()
819            .p(Spacing::S6)
820            .text_size(Typography::TEXT_SM)
821            .text_color(colors.foreground)
822            .when_some(self.body, |d, b| d.child(b));
823
824        let int_key = internal.clone();
825        let on_open_key = self.on_open_change.clone();
826        let rad = px(DRAWER_INNER_RADIUS);
827
828        let mut panel = div()
829            .id(ElementId::NamedChild(
830                self.id.clone().into(),
831                "content".into(),
832            ))
833            .role(Role::Dialog)
834            .aria_label(self.title.clone())
835            .test_support()
836            .track_focus(&snap.focus_handle)
837            .absolute()
838            .flex()
839            .flex_col()
840            .overflow_hidden()
841            .border_color(colors.border)
842            .bg(colors.surface_raised)
843            .text_color(colors.foreground)
844            .when(!self.contained, |d| d.shadow(Shadows::floating(theme.mode)))
845            .opacity(panel_alpha)
846            .on_mouse_down(MouseButton::Left, |_, _, cx| {
847                cx.stop_propagation();
848            })
849            .on_key_down(move |event: &KeyDownEvent, window, cx| {
850                if event.keystroke.key.as_str() == "escape" {
851                    cx.stop_propagation();
852                    int_key.update(cx, |s, _| {
853                        s.open = false;
854                        s.dragging = false;
855                        s.drag_offset = 0.0;
856                    });
857                    if let Some(h) = &on_open_key {
858                        h(&false, window, cx);
859                    }
860                    window.refresh();
861                }
862            })
863            .child(panel_probe);
864
865        // Side-specific anchoring, border sides, corner radii, and bottom grab bar.
866        panel = match side {
867            DrawerSide::Right => panel
868                .top_0()
869                .bottom_0()
870                .right(px(-total_shift))
871                .w(px(base_extent))
872                .border_l_1()
873                .when(!self.contained, |d| d.border_t_1().border_b_1())
874                .rounded_tl(rad)
875                .rounded_bl(rad),
876            DrawerSide::Left => panel
877                .top_0()
878                .bottom_0()
879                .left(px(total_shift))
880                .w(px(base_extent))
881                .border_r_1()
882                .when(!self.contained, |d| d.border_t_1().border_b_1())
883                .rounded_tr(rad)
884                .rounded_br(rad),
885            DrawerSide::Top => panel
886                .left_0()
887                .right_0()
888                .top(px(total_shift))
889                .max_h(px(base_extent))
890                .border_b_1()
891                .rounded_bl(rad)
892                .rounded_br(rad),
893            DrawerSide::Bottom => panel
894                .left_0()
895                .right_0()
896                .bottom(px(-total_shift))
897                .max_h(px(base_extent))
898                .border_t_1()
899                .rounded_tl(rad)
900                .rounded_tr(rad)
901                .child(
902                    div().w_full().pt(px(9.0)).flex().justify_center().child(
903                        div()
904                            .w(px(36.0))
905                            .h(px(4.0))
906                            .rounded(Radii::PILL)
907                            .bg(colors.border_strong)
908                            .opacity(0.75),
909                    ),
910                ),
911        };
912
913        panel = panel.child(header).child(body);
914
915        let base_alpha = if self.contained { 0.16 } else { 0.38 };
916        let mut backdrop_color = gpui_kit::hsla(0.0, 0.0, 0.04, base_alpha);
917        backdrop_color.a *= overlay_presence.progress.clamp(0.0, 1.0);
918
919        let (rel_left, rel_top) = if self.contained {
920            (0.0, 0.0)
921        } else {
922            snap.trigger_bounds
923                .borrow()
924                .map(|b| (-f32::from(b.origin.x), -f32::from(b.origin.y)))
925                .unwrap_or((0.0, 0.0))
926        };
927
928        let layer = div()
929            .id(ElementId::NamedChild(
930                self.id.clone().into(),
931                "backdrop".into(),
932            ))
933            .test_support()
934            .absolute()
935            .left(px(rel_left))
936            .top(px(rel_top))
937            .when(self.contained, |d| d.right_0().bottom_0())
938            .when(!self.contained, |d| d.w(viewport.width).h(viewport.height))
939            .bg(backdrop_color)
940            .overflow_hidden()
941            .child(panel);
942
943        if self.contained {
944            root.child(layer)
945        } else {
946            root.child(deferred(layer).with_priority(30))
947        }
948    }
949}
950
951#[cfg(test)]
952mod tests {
953    use std::{cell::Cell, rc::Rc};
954
955    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
956    use gpui_kit::{
957        Context, IntoElement, MouseButton, ParentElement, Render, Role, Styled, TestAppContext,
958        Window, div, px,
959        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
960    };
961
962    use super::*;
963
964    #[test]
965    fn drawer_pan_rubber_band_dismiss_and_late_shadow_fade_match_spec() {
966        // Right drawer: dragging right (+60px) follows 1:1; dragging left (-25px) rubber-bands to -5px.
967        assert!((drawer_pan_offset(DrawerSide::Right, 60.0) - 60.0).abs() < 1e-4);
968        assert!((drawer_pan_offset(DrawerSide::Right, -25.0) - -5.0).abs() < 1e-4);
969        // Left drawer: dragging left (-60px) follows 1:1; dragging right (+36px) rubber-bands to +6px.
970        assert!((drawer_pan_offset(DrawerSide::Left, -60.0) - -60.0).abs() < 1e-4);
971        assert!((drawer_pan_offset(DrawerSide::Left, 36.0) - 6.0).abs() < 1e-4);
972
973        // Dismiss past 1/3 of 480px (= 160px) or velocity > 500 px/s.
974        assert!(!drawer_should_dismiss(
975            DrawerSide::Right,
976            120.0,
977            100.0,
978            480.0
979        ));
980        assert!(drawer_should_dismiss(DrawerSide::Right, 170.0, 50.0, 480.0));
981        assert!(drawer_should_dismiss(DrawerSide::Right, 20.0, 620.0, 480.0));
982
983        // Exit opacity stays at 1.0 for the first 65% of the leave (`progress` from 1.0 down to 0.35),
984        // then fades linearly to 0.0.
985        assert_eq!(drawer_exit_opacity(false, 0.80, false), 1.0);
986        assert_eq!(drawer_exit_opacity(false, 0.35, false), 1.0);
987        assert!((drawer_exit_opacity(false, 0.175, false) - 0.5).abs() < 1e-3);
988        assert_eq!(drawer_exit_opacity(false, 0.0, false), 0.0);
989    }
990
991    struct DrawerHost {
992        open: bool,
993        closed_count: Rc<Cell<usize>>,
994    }
995
996    impl Render for DrawerHost {
997        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
998            let count = self.closed_count.clone();
999            div().size_full().p(px(24.0)).child(
1000                Drawer::new("test-drawer", "Inspector drawer")
1001                    .description("Edge panel details")
1002                    .side(DrawerSide::Right)
1003                    .open(self.open)
1004                    .on_open_change(cx.listener(move |this, next: &bool, _, cx| {
1005                        this.open = *next;
1006                        if !*next {
1007                            count.set(count.get() + 1);
1008                        }
1009                        cx.notify();
1010                    }))
1011                    .trigger(div().w(px(110.0)).h(px(36.0)).child("Open drawer"))
1012                    .content(div().child("Drawer details body")),
1013            )
1014        }
1015    }
1016
1017    #[gpui_kit::test]
1018    fn drawer_opens_on_trigger_and_closes_on_close_button(cx: &mut TestAppContext) {
1019        cx.update(|cx| {
1020            gpui_kit::init(cx);
1021            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
1022            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
1023        });
1024        let closed_count = Rc::new(Cell::new(0));
1025        let (_view, cx) = cx.add_window_view(|_, _| DrawerHost {
1026            open: false,
1027            closed_count: closed_count.clone(),
1028        });
1029
1030        cx.update(|window, cx| {
1031            window.render_frame(cx);
1032            let trig = window.find_by_label("Open drawer");
1033            let tpos = trig.bounds().center();
1034            window.pointer_down(tpos, MouseButton::Left, cx);
1035            window.pointer_up(tpos, MouseButton::Left, cx);
1036            window.render_frame(cx);
1037
1038            let panel = window.find_by_label("Inspector drawer");
1039            assert_eq!(panel.role(), Some(Role::Dialog));
1040
1041            // Click the close button after render_frame(cx) settles the slide spring into the viewport,
1042            // or enable reduced motion so the panel starts immediately at 0.0 offset.
1043            let close_btn = window.find_by_label("Close drawer");
1044            let cpos = close_btn.bounds().center();
1045            window.pointer_down(cpos, MouseButton::Left, cx);
1046            window.pointer_up(cpos, MouseButton::Left, cx);
1047            window.render_frame(cx);
1048            assert_eq!(closed_count.get(), 1);
1049        });
1050    }
1051
1052    struct SideSwitchHost {
1053        open: bool,
1054        side: DrawerSide,
1055    }
1056
1057    impl Render for SideSwitchHost {
1058        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1059            div().size_full().child(
1060                Drawer::new("switch-drawer", "Side switch drawer")
1061                    .side(self.side)
1062                    .open(self.open)
1063                    .content(div().child("Body")),
1064            )
1065        }
1066    }
1067
1068    #[gpui_kit::test]
1069    fn drawer_switching_sides_always_slides_from_anchored_edge(cx: &mut TestAppContext) {
1070        cx.update(|cx| {
1071            gpui_kit::init(cx);
1072            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
1073            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx);
1074        });
1075        let (view, cx) = cx.add_window_view(|_, _| SideSwitchHost {
1076            open: false,
1077            side: DrawerSide::Right,
1078        });
1079
1080        cx.update(|window, cx| {
1081            window.render_frame(cx);
1082            let vw = f32::from(window.viewport_size().width);
1083
1084            // 1. Open Left drawer after mounting closed as Right: must start on the left (< 0).
1085            view.update(cx, |this, cx| {
1086                this.side = DrawerSide::Left;
1087                this.open = true;
1088                cx.notify();
1089            });
1090            window.render_frame(cx);
1091            let left_bounds = window.find_by_label("Side switch drawer").bounds();
1092            assert!(
1093                f32::from(left_bounds.origin.x) < 0.0,
1094                "Left drawer should start sliding from left edge (< 0), got {:?}",
1095                left_bounds
1096            );
1097
1098            // 2. Close Left drawer, then open Right drawer: must start on the right (> vw - width).
1099            view.update(cx, |this, cx| {
1100                this.open = false;
1101                cx.notify();
1102            });
1103            window.render_frame(cx);
1104            view.update(cx, |this, cx| {
1105                this.side = DrawerSide::Right;
1106                this.open = true;
1107                cx.notify();
1108            });
1109            window.render_frame(cx);
1110            let right_bounds = window.find_by_label("Side switch drawer").bounds();
1111            assert!(
1112                f32::from(right_bounds.origin.x) > vw - DRAWER_WIDTH,
1113                "Right drawer should start sliding from right edge (> {}), got {:?}",
1114                vw - DRAWER_WIDTH,
1115                right_bounds
1116            );
1117        });
1118    }
1119}