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
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/bottom-sheet/bottom-sheet.tsx` & `.module.css`
//!
//! P3 Component #9: `bottom-sheet`
//!
//! - Bottom-anchored sheet (`width: min(100%, 36rem = 576px)`) that rests at one or more sorted
//!   detents (default `[0.45, 0.92]` of viewport height) with `160px` bottom extension so upward
//!   rubber-band stretches never expose a gap below the fold.
//! - Backdrop dim is a continuous function of the sheet's vertical offset (`sheet_backdrop_dim`):
//!   `1.0` at the tallest detent, `LOW_DIM = 0.78` at the smallest detent, and `0.0` at
//!   `full_height + CLOSED_GAP (40px)`.
//! - iOS-style upward stretch resistance (`sheet_rubber` / `sheet_unrubber`, asymptotic limit
//!   `STRETCH = 120px`), `0.20s` momentum projection (`PROJECTION_SECS`), and `320 px/s` flick
//!   threshold (`FLICK_VELOCITY`) that always advances at least one detent (or closes from the
//!   lowest detent).
//! - Grabber button (`3.5rem × 1.25rem` with `36×5px` pill bar) toggles between lowest and tallest
//!   detents on click and steps detents via `ArrowUp` / `ArrowDown` / `Home` / `End`.

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

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

/// Maximum sheet width (`36rem = 576px`).
pub const SHEET_MAX_WIDTH: f32 = 576.0;
/// Hidden extension below the bottom edge (`160px`) so upward stretches never reveal a gap.
pub const SHEET_EXTENSION: f32 = 160.0;
/// Extra travel below the fold when closed (`40px`) to hide the floating shadow.
pub const SHEET_CLOSED_GAP: f32 = 40.0;
/// Velocity projection horizon (`0.20s`).
pub const SHEET_PROJECTION_SECS: f32 = 0.20;
/// Minimum flick speed (`320 px/s`) to force a detent step.
pub const SHEET_FLICK_VELOCITY: f32 = 320.0;
/// Asymptotic upward stretch cap (`120px`).
pub const SHEET_STRETCH_LIMIT: f32 = 120.0;
/// Fraction of full backdrop dim remaining at the smallest detent (`0.78`).
pub const SHEET_LOW_DIM: f32 = 0.78;

/// Target stop for [`BottomSheet`]: either a sorted detent index or `Closed`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SheetStop {
    Detent(usize),
    Closed,
}

/// iOS-style upward rubber-band resistance approaching [`SHEET_STRETCH_LIMIT`] (`120px`).
pub fn sheet_rubber(distance: f32) -> f32 {
    let d = distance.max(0.0);
    (1.0 - 1.0 / (d * 0.55 / SHEET_STRETCH_LIMIT + 1.0)) * SHEET_STRETCH_LIMIT
}

/// Inverse of [`sheet_rubber`] so catching an overstretched sheet mid-flight never jumps.
pub fn sheet_unrubber(stretch: f32) -> f32 {
    let s = stretch.clamp(0.0, SHEET_STRETCH_LIMIT - 1.0);
    (1.0 / (1.0 - s / SHEET_STRETCH_LIMIT) - 1.0) * SHEET_STRETCH_LIMIT / 0.55
}

/// Sanitizes and sorts detent fractions into ascending `(0.0, 1.0]` values (fallback `[0.45, 0.92]`).
pub fn normalize_detents(detents: &[f32]) -> Vec<f32> {
    let mut stops: Vec<f32> = detents
        .iter()
        .copied()
        .filter(|d| *d > 0.05 && *d <= 1.0)
        .collect();
    stops.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    stops.dedup_by(|a, b| (*a - *b).abs() < 0.01);
    if stops.is_empty() {
        vec![0.45, 0.92]
    } else {
        stops
    }
}

/// Computes the vertical offset (`px` below the tallest detent) for `stop`.
pub fn sheet_stop_offset(stop: SheetStop, stops: &[f32], full_height: f32) -> f32 {
    let top_frac = stops.last().copied().unwrap_or(0.92).max(0.05);
    match stop {
        SheetStop::Closed => full_height + SHEET_CLOSED_GAP,
        SheetStop::Detent(idx) => {
            let i = idx.min(stops.len().saturating_sub(1));
            let frac = stops.get(i).copied().unwrap_or(top_frac);
            full_height * (1.0 - frac / top_frac)
        }
    }
}

/// Continuous backdrop dim multiplier (`0.0..=1.0`) derived from current sheet offset `offset_y`.
pub fn sheet_backdrop_dim(offset_y: f32, stops: &[f32], full_height: f32) -> f32 {
    if full_height <= 1.0 {
        return 0.0;
    }
    let low = sheet_stop_offset(SheetStop::Detent(0), stops, full_height);
    let closed = full_height + SHEET_CLOSED_GAP;
    let dim = if offset_y <= low {
        let ratio = if low > 0.001 {
            (offset_y / low).max(0.0)
        } else {
            0.0
        };
        1.0 - (1.0 - SHEET_LOW_DIM) * ratio
    } else {
        let span = (closed - low).max(1.0);
        SHEET_LOW_DIM * (1.0 - (offset_y - low) / span)
    };
    dim.clamp(0.0, 1.0)
}

/// Resolves which [`SheetStop`] a drag release should land on given `current_y`, `velocity_y`,
/// `from_detent`, `stops`, and `full_height`.
pub fn resolve_sheet_release(
    current_y: f32,
    velocity_y: f32,
    from_detent: usize,
    stops: &[f32],
    full_height: f32,
) -> SheetStop {
    let top = stops.len().saturating_sub(1);
    let eff_vel = if current_y < 0.0 { 0.0 } else { velocity_y };
    let projected = current_y + eff_vel * SHEET_PROJECTION_SECS;

    let mut best = SheetStop::Closed;
    let mut best_dist = (sheet_stop_offset(best, stops, full_height) - projected).abs();
    for idx in 0..stops.len() {
        let cand = SheetStop::Detent(idx);
        let dist = (sheet_stop_offset(cand, stops, full_height) - projected).abs();
        if dist < best_dist {
            best_dist = dist;
            best = cand;
        }
    }

    if eff_vel.abs() > SHEET_FLICK_VELOCITY && best == SheetStop::Detent(from_detent) {
        best = if eff_vel < 0.0 {
            SheetStop::Detent((from_detent + 1).min(top))
        } else if from_detent == 0 {
            SheetStop::Closed
        } else {
            SheetStop::Detent(from_detent - 1)
        };
    }
    best
}

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

fn paint_close_x(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
    let r = 4.2_f32;
    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 BottomSheetInternal {
    open: bool,
    detent: usize,
    opened_at_secs: f64,
    grabber_hovered: bool,
    close_hovered: bool,
    dragging: bool,
    drag_moved: bool,
    drag_start_y: f32,
    drag_origin_y: f32,
    drag_current_y: f32,
    drag_last_y: f32,
    drag_last_at: f64,
    drag_velocity_y: f32,
    release_velocity_y: Option<f32>,
    suppress_grabber_click: bool,
    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    sheet_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    focus_handle: FocusHandle,
}

impl BottomSheetInternal {
    fn new(default_open: bool, initial_detent: usize, now: f64, focus_handle: FocusHandle) -> Self {
        Self {
            open: default_open,
            detent: initial_detent,
            opened_at_secs: now - 10.0,
            grabber_hovered: false,
            close_hovered: false,
            dragging: false,
            drag_moved: false,
            drag_start_y: 0.0,
            drag_origin_y: 0.0,
            drag_current_y: 0.0,
            drag_last_y: 0.0,
            drag_last_at: now,
            drag_velocity_y: 0.0,
            release_velocity_y: None,
            suppress_grabber_click: false,
            trigger_bounds: Rc::new(RefCell::new(None)),
            sheet_bounds: Rc::new(RefCell::new(None)),
            focus_handle,
        }
    }
}

/// Arc `BottomSheet` — multi-detent bottom sheet with position-driven backdrop dim, iOS rubber-band
/// stretch, velocity projection, and keyboard/click grabber controls.
#[derive(IntoElement)]
pub struct BottomSheet {
    id: ElementId,
    title: SharedString,
    description: Option<SharedString>,
    detents: Vec<f32>,
    initial_detent: usize,
    detent: Option<usize>,
    on_detent_change: Option<DetentCallback>,
    close_label: SharedString,
    trigger: Option<AnyElement>,
    body: Option<AnyElement>,
    open: Option<bool>,
    default_open: bool,
    on_open_change: Option<OpenCallback>,
}

impl BottomSheet {
    pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            description: None,
            detents: vec![0.45, 0.92],
            initial_detent: 0,
            detent: None,
            on_detent_change: None,
            close_label: "Close".into(),
            trigger: None,
            body: None,
            open: None,
            default_open: false,
            on_open_change: None,
        }
    }

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

    /// Resting heights as fractions of viewport height (e.g. `[0.45, 0.92]`).
    pub fn detents(mut self, detents: impl IntoIterator<Item = f32>) -> Self {
        self.detents = detents.into_iter().collect();
        self
    }

    pub fn initial_detent(mut self, index: usize) -> Self {
        self.initial_detent = index;
        self
    }

    pub fn detent(mut self, index: usize) -> Self {
        self.detent = Some(index);
        self
    }

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

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

    pub fn trigger(mut self, trigger: impl IntoElement) -> Self {
        self.trigger = Some(trigger.into_any_element());
        self
    }

    pub fn content(mut self, body: impl IntoElement) -> Self {
        self.body = Some(body.into_any_element());
        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
    }
}

impl RenderOnce for BottomSheet {
    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 stops = normalize_detents(&self.detents);
        let top_idx = stops.len().saturating_sub(1);
        let init_detent = self.initial_detent.min(top_idx);

        let state_id =
            ElementId::NamedChild(self.id.clone().into(), "__arc-bottom-sheet-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
            BottomSheetInternal::new(self.default_open, init_detent, now, cx.focus_handle())
        });

        let snap = internal.read(cx).clone();
        let is_open = self.open.unwrap_or(snap.open);
        let active_detent = self.detent.unwrap_or(snap.detent).min(top_idx);
        let expanded = active_detent == top_idx;

        let viewport = window.viewport_size();
        let vp_h = f32::from(viewport.height).max(320.0);
        let vp_w = f32::from(viewport.width).max(320.0);
        let top_frac = stops.last().copied().unwrap_or(0.92);
        let full_height = (vp_h * top_frac).max(200.0);
        let sheet_width = vp_w.min(SHEET_MAX_WIDTH);

        let target_stop = if is_open {
            SheetStop::Detent(active_detent)
        } else {
            SheetStop::Closed
        };
        let target_y = sheet_stop_offset(target_stop, &stops, full_height);

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

        // Single motion coordinate `y` (`px` below tallest detent).
        let spring_spec = if is_open {
            motion.spring.smooth
        } else {
            SpringSpec::visual(0.30, 0.0)
        };
        let mut spring_opts = SpringOptions::new(spring_spec);
        if let Some(vel) = snap.release_velocity_y {
            spring_opts = spring_opts.with_initial_velocity(vel);
            internal.update(cx, |s, _| {
                s.release_velocity_y = None;
            });
        }
        let current_y = if reduced {
            sheet_stop_offset(SheetStop::Detent(active_detent), &stops, full_height)
        } else if snap.dragging && snap.drag_moved {
            let _ = arc_spring_with_options(
                (self.id.clone(), "sheet-y"),
                snap.drag_current_y,
                SpringOptions::new(motion.spring.snappy),
                window,
                cx,
            );
            snap.drag_current_y
        } else {
            arc_spring_with_options(
                (self.id.clone(), "sheet-y"),
                target_y,
                spring_opts,
                window,
                cx,
            )
            .value
        };

        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 int_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 bottom sheet")
                    .relative()
                    .flex()
                    .cursor_pointer()
                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                        let t = motion_now(cx);
                        int_trig.update(cx, |s, _| {
                            s.open = true;
                            s.detent = init_detent;
                            s.opened_at_secs = t;
                            s.dragging = false;
                            s.drag_moved = false;
                        });
                        focus_trig.focus(window, cx);
                        if let Some(h) = &on_open_trig {
                            h(&true, window, cx);
                        }
                        window.refresh();
                    })
                    .child(trig),
            );
        }

        if !presence.should_render() && (current_y - (full_height + SHEET_CLOSED_GAP)).abs() < 2.0 {
            return root;
        }

        if is_open && !snap.focus_handle.is_focused(window) {
            snap.focus_handle.focus(window, cx);
        }

        // Window-level outside click & header drag tracking.
        let sheet_bounds_ref = snap.sheet_bounds.clone();
        let sheet_bounds_out = snap.sheet_bounds.clone();
        let trig_bounds_out = snap.trigger_bounds.clone();
        let int_events = internal.clone();
        let on_open_events = self.on_open_change.clone();
        let on_detent_events = self.on_detent_change.clone();
        let opened_at = snap.opened_at_secs;
        let is_dragging = snap.dragging;
        let stops_for_up = stops.clone();

        let sheet_probe = canvas(
            move |rect, _, _| {
                *sheet_bounds_ref.borrow_mut() = Some(rect);
            },
            move |_, _, window, _| {
                if is_open {
                    let s_ref = sheet_bounds_out.clone();
                    let t_ref = trig_bounds_out.clone();
                    let st = int_events.clone();
                    let cb = on_open_events.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_sheet = s_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_sheet && !in_trig {
                            st.update(cx, |s, _| {
                                s.open = false;
                                s.dragging = false;
                                s.drag_moved = false;
                            });
                            if let Some(h) = &cb {
                                h(&false, window, cx);
                            }
                            window.refresh();
                        }
                    });
                }
                if is_dragging {
                    let st_move = int_events.clone();
                    window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
                        if !phase.bubble() {
                            return;
                        }
                        let t_now = motion_now(cx);
                        let py = f32::from(event.position.y);
                        st_move.update(cx, |s, _| {
                            if !s.dragging {
                                return;
                            }
                            let delta = py - s.drag_start_y;
                            if !s.drag_moved && delta.abs() < 3.0 {
                                return;
                            }
                            s.drag_moved = true;
                            let raw = s.drag_origin_y + delta;
                            s.drag_current_y = if raw < 0.0 { -sheet_rubber(-raw) } else { raw };
                            let dt = (t_now - s.drag_last_at).max(0.004) as f32;
                            s.drag_velocity_y = (py - s.drag_last_y) / dt;
                            s.drag_last_y = py;
                            s.drag_last_at = t_now;
                        });
                        window.refresh();
                    });

                    let st_up = int_events.clone();
                    let cb_open = on_open_events.clone();
                    let cb_detent = on_detent_events.clone();
                    let stops_up = stops_for_up.clone();
                    window.on_mouse_event(move |_: &MouseUpEvent, phase, window, cx| {
                        if !phase.bubble() {
                            return;
                        }
                        let (moved, cur_y, vel_y, from_d) = {
                            let r = st_up.read(cx);
                            (r.drag_moved, r.drag_current_y, r.drag_velocity_y, r.detent)
                        };
                        if !moved {
                            st_up.update(cx, |s, _| {
                                s.dragging = false;
                            });
                            return;
                        }
                        let next_stop =
                            resolve_sheet_release(cur_y, vel_y, from_d, &stops_up, full_height);
                        match next_stop {
                            SheetStop::Closed => {
                                st_up.update(cx, |s, _| {
                                    s.dragging = false;
                                    s.drag_moved = false;
                                    s.suppress_grabber_click = true;
                                    s.release_velocity_y = Some(vel_y);
                                    s.open = false;
                                });
                                if let Some(h) = &cb_open {
                                    h(&false, window, cx);
                                }
                            }
                            SheetStop::Detent(next_idx) => {
                                st_up.update(cx, |s, _| {
                                    s.dragging = false;
                                    s.drag_moved = false;
                                    s.suppress_grabber_click = true;
                                    s.release_velocity_y = Some(vel_y);
                                    s.detent = next_idx;
                                });
                                if next_idx != from_d
                                    && let Some(h) = &cb_detent
                                {
                                    h(&next_idx, window, cx);
                                }
                            }
                        }
                        window.refresh();
                    });
                }
            },
        )
        .absolute()
        .inset_0();

        // Grabber button (`3.5rem × 1.25rem = 56×20px` with `36×5px` pill bar).
        let grabber_bar_bg = if snap.grabber_hovered || (snap.dragging && snap.drag_moved) {
            colors.text_muted
        } else {
            colors.border_strong
        };
        let int_grab_hover = internal.clone();
        let int_grab_click = internal.clone();
        let on_detent_grab = self.on_detent_change.clone();
        let grabber = div()
            .id(ElementId::NamedChild(
                self.id.clone().into(),
                "grabber".into(),
            ))
            .test_support()
            .role(Role::Button)
            .aria_label(if expanded {
                "Collapse sheet"
            } else {
                "Expand sheet"
            })
            .w(px(56.0))
            .h(px(20.0))
            .mx_auto()
            .mb(Spacing::S1)
            .rounded(Radii::PILL)
            .flex()
            .items_center()
            .justify_center()
            .cursor_pointer()
            .on_hover(move |hovered, window, cx| {
                int_grab_hover.update(cx, |s, _| {
                    s.grabber_hovered = *hovered;
                });
                window.refresh();
            })
            .on_click(move |_, window, cx| {
                let suppressed = int_grab_click.read(cx).suppress_grabber_click;
                if suppressed {
                    int_grab_click.update(cx, |s, _| {
                        s.suppress_grabber_click = false;
                    });
                    return;
                }
                let next_idx = if active_detent == top_idx { 0 } else { top_idx };
                int_grab_click.update(cx, |s, _| {
                    s.detent = next_idx;
                });
                if let Some(h) = &on_detent_grab {
                    h(&next_idx, window, cx);
                }
                window.refresh();
            })
            .child(
                div()
                    .w(px(36.0))
                    .h(px(5.0))
                    .rounded(Radii::PILL)
                    .bg(grabber_bar_bg),
            );

        // Close pill button (`32×32`, `Radii::PILL`, `surface_muted`).
        let close_fg = if snap.close_hovered {
            colors.foreground
        } else {
            colors.text_secondary
        };
        let close_border = if snap.close_hovered {
            colors.border_strong
        } else {
            colors.border
        };
        let int_close_hover = internal.clone();
        let int_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(self.close_label.clone())
            .flex_none()
            .w(px(32.0))
            .h(px(32.0))
            .rounded(Radii::PILL)
            .border_1()
            .border_color(close_border)
            .bg(colors.surface_muted)
            .cursor_pointer()
            .on_hover(move |hovered, window, cx| {
                int_close_hover.update(cx, |s, _| {
                    s.close_hovered = *hovered;
                });
                window.refresh();
            })
            .on_mouse_down(MouseButton::Left, |_, _, cx| {
                cx.stop_propagation();
            })
            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
                cx.stop_propagation();
                int_close_up.update(cx, |s, _| {
                    s.open = false;
                    s.dragging = false;
                    s.drag_moved = false;
                });
                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_fg, window);
                    },
                )
                .size_full(),
            );

        let int_pan_down = internal.clone();
        let header = div()
            .id(ElementId::NamedChild(
                self.id.clone().into(),
                "header".into(),
            ))
            .test_support()
            .w_full()
            .flex_none()
            .pt(Spacing::S2)
            .px(Spacing::S5)
            .pb(Spacing::S4)
            .border_b_1()
            .border_color(colors.border_subtle)
            .on_mouse_down(
                MouseButton::Left,
                move |event: &MouseDownEvent, window, cx| {
                    if reduced {
                        return;
                    }
                    let py = f32::from(event.position.y);
                    let origin = if current_y < 0.0 {
                        -sheet_unrubber(-current_y)
                    } else {
                        current_y
                    };
                    let t = motion_now(cx);
                    int_pan_down.update(cx, |s, _| {
                        s.dragging = true;
                        s.drag_moved = false;
                        s.drag_start_y = py;
                        s.drag_origin_y = origin;
                        s.drag_current_y = current_y;
                        s.drag_last_y = py;
                        s.drag_last_at = t;
                        s.drag_velocity_y = 0.0;
                    });
                    window.refresh();
                },
            )
            .child(grabber)
            .child(
                div()
                    .w_full()
                    .flex()
                    .items_start()
                    .justify_between()
                    .gap(Spacing::S4)
                    .child(
                        div()
                            .flex_1()
                            .min_w_0()
                            .flex()
                            .flex_col()
                            .gap(px(2.0))
                            .child(
                                div()
                                    .text_size(Typography::TEXT_LG)
                                    .font_medium()
                                    .text_color(colors.foreground)
                                    .child(self.title.clone()),
                            )
                            .when_some(self.description, |d, desc| {
                                d.child(
                                    div()
                                        .text_size(Typography::TEXT_SM)
                                        .text_color(colors.text_secondary)
                                        .child(desc),
                                )
                            }),
                    )
                    .child(close_btn),
            );

        let body = div()
            .id(ElementId::NamedChild(self.id.clone().into(), "body".into()))
            .w_full()
            .flex_1()
            .min_h_0()
            .when(expanded, |d| d.overflow_y_scroll())
            .when(!expanded, |d| d.overflow_hidden())
            .pt(Spacing::S1)
            .px(Spacing::S5)
            .pb(Spacing::S6)
            .text_size(Typography::TEXT_SM)
            .text_color(colors.foreground)
            .when_some(self.body, |d, b| d.child(b));

        // Keyboard support (`Esc` closes; `ArrowUp` / `ArrowDown` / `Home` / `End` adjust detents).
        let int_key = internal.clone();
        let on_open_key = self.on_open_change.clone();
        let on_detent_key = self.on_detent_change.clone();
        let sheet_opacity = if reduced {
            presence.progress.clamp(0.0, 1.0)
        } else {
            1.0
        };
        let sheet_left = ((vp_w - sheet_width) * 0.5).max(0.0);

        let sheet = 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)
            .absolute()
            .left(px(sheet_left))
            .bottom(px(-SHEET_EXTENSION - current_y))
            .w(px(sheet_width))
            .h(px(full_height + SHEET_EXTENSION))
            .pb(px(SHEET_EXTENSION))
            .rounded_tl(Radii::SURFACE)
            .rounded_tr(Radii::SURFACE)
            .border_t_1()
            .border_l_1()
            .border_r_1()
            .border_color(colors.border)
            .bg(colors.surface_raised)
            .text_color(colors.foreground)
            .shadow(Shadows::floating(theme.mode))
            .opacity(sheet_opacity)
            .flex()
            .flex_col()
            .overflow_hidden()
            .on_mouse_down(MouseButton::Left, |_, _, cx| {
                cx.stop_propagation();
            })
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                match event.keystroke.key.as_str() {
                    "escape" => {
                        cx.stop_propagation();
                        int_key.update(cx, |s, _| {
                            s.open = false;
                            s.dragging = false;
                            s.drag_moved = false;
                        });
                        if let Some(h) = &on_open_key {
                            h(&false, window, cx);
                        }
                        window.refresh();
                    }
                    "up" | "down" | "home" | "end" => {
                        cx.stop_propagation();
                        let next_idx = match event.keystroke.key.as_str() {
                            "up" => (active_detent + 1).min(top_idx),
                            "down" => active_detent.saturating_sub(1),
                            "home" => top_idx,
                            _ => 0,
                        };
                        if next_idx != active_detent {
                            int_key.update(cx, |s, _| {
                                s.detent = next_idx;
                            });
                            if let Some(h) = &on_detent_key {
                                h(&next_idx, window, cx);
                            }
                            window.refresh();
                        }
                    }
                    _ => {}
                }
            })
            .child(sheet_probe)
            .child(header)
            .child(body);

        // Backdrop dim follows `current_y` directly (`sheet_backdrop_dim`).
        let dim_progress = if reduced {
            presence.progress.clamp(0.0, 1.0)
        } else {
            sheet_backdrop_dim(current_y, &stops, full_height) * presence.progress.clamp(0.0, 1.0)
        };
        let base_dim_alpha = if theme.mode.is_dark() { 0.52 } else { 0.34 };
        let backdrop_color = gpui_kit::hsla(0.0, 0.0, 0.04, base_dim_alpha * dim_progress);

        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 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)
            .overflow_hidden()
            .child(sheet);

        root.child(deferred(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, Styled, TestAppContext,
        Window, div, px,
        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
    };

    use super::*;

    #[test]
    fn rubber_band_backdrop_dim_and_release_projection_follow_spec() {
        // Rubber / unrubber roundtrip and asymptotic cap (`120px`).
        let r = sheet_rubber(80.0);
        assert!(r > 0.0 && r < SHEET_STRETCH_LIMIT);
        assert!((sheet_unrubber(r) - 80.0).abs() < 1e-3);
        assert!(sheet_rubber(10_000.0) < SHEET_STRETCH_LIMIT);

        let stops = normalize_detents(&[0.92, 0.45]);
        assert_eq!(stops, vec![0.45, 0.92]);

        let full = 600.0;
        let low_off = sheet_stop_offset(SheetStop::Detent(0), &stops, full);
        let top_off = sheet_stop_offset(SheetStop::Detent(1), &stops, full);
        let closed_off = sheet_stop_offset(SheetStop::Closed, &stops, full);
        assert_eq!(top_off, 0.0);
        assert!(low_off > 250.0 && low_off < full);
        assert_eq!(closed_off, full + SHEET_CLOSED_GAP);

        // Backdrop dim is 1.0 at top detent, LOW_DIM (0.78) at lowest detent, 0.0 when closed.
        assert!((sheet_backdrop_dim(0.0, &stops, full) - 1.0).abs() < 1e-4);
        assert!((sheet_backdrop_dim(low_off, &stops, full) - SHEET_LOW_DIM).abs() < 1e-4);
        assert_eq!(sheet_backdrop_dim(closed_off, &stops, full), 0.0);

        // Upward flick from detent 0 advances to detent 1; downward flick from detent 0 closes.
        assert_eq!(
            resolve_sheet_release(low_off - 10.0, -450.0, 0, &stops, full),
            SheetStop::Detent(1)
        );
        assert_eq!(
            resolve_sheet_release(low_off + 10.0, 450.0, 0, &stops, full),
            SheetStop::Closed
        );
    }

    struct SheetHost {
        open: bool,
        detent: Rc<Cell<usize>>,
    }

    impl Render for SheetHost {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let detent = self.detent.clone();
            div().size_full().p(px(24.0)).child(
                BottomSheet::new("test-sheet", "Trip details")
                    .description("Two detents: 45% peek and 92% expanded")
                    .detents([0.45, 0.92])
                    .initial_detent(0)
                    .open(self.open)
                    .on_open_change(cx.listener(|this, next: &bool, _, cx| {
                        this.open = *next;
                        cx.notify();
                    }))
                    .on_detent_change(cx.listener(move |_, next: &usize, _, _| {
                        detent.set(*next);
                    }))
                    .trigger(div().w(px(120.0)).h(px(36.0)).child("Open sheet"))
                    .content(div().child("Bottom sheet body")),
            )
        }
    }

    #[gpui_kit::test]
    fn bottom_sheet_opens_toggles_detent_via_grabber_and_closes(cx: &mut TestAppContext) {
        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 detent = Rc::new(Cell::new(0));
        let (_view, cx) = cx.add_window_view(|_, _| SheetHost {
            open: false,
            detent: detent.clone(),
        });

        cx.update(|window, cx| {
            window.render_frame(cx);
            let trig = window.find_by_label("Open bottom sheet");
            let tpos = trig.bounds().center();
            window.pointer_down(tpos, MouseButton::Left, cx);
            window.pointer_up(tpos, MouseButton::Left, cx);
            window.render_frame(cx);

            let dialog = window.find_by_label("Trip details");
            assert_eq!(dialog.role(), Some(Role::Dialog));

            // Clicking the grabber at detent 0 expands to the tallest detent (1).
            let grabber = window.find_by_label("Expand sheet");
            let gpos = grabber.bounds().center();
            window.pointer_down(gpos, MouseButton::Left, cx);
            window.pointer_up(gpos, MouseButton::Left, cx);
            window.render_frame(cx);
            assert_eq!(detent.get(), 1);

            // Clicking the close pill dismisses the sheet.
            let close_btn = window.find_by_label("Close");
            let cpos = close_btn.bounds().center();
            window.pointer_down(cpos, MouseButton::Left, cx);
            window.pointer_up(cpos, MouseButton::Left, cx);
            window.render_frame(cx);
        });
    }
}