u0ui 0.3.5

Carbon UI: IBM Carbon v11 visuals with a shadcn-style API for GPUI Kit
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
//! Shared plumbing for floating and modal surfaces (Dialog, Sheet, Popover,
//! menus, tooltips): open state, presence (enter/exit motion that keeps a
//! closing surface mounted until it has faded), focus moves, the Carbon
//! floating shadow, and a translate wrapper.
//!
//! Behavior stays Kit's: modal hosts are [`gpui_kit::base::Dialog`] (focus
//! trap, Escape, backdrop press, deferred top layer) and anchored surfaces are
//! [`gpui_kit::base::Popup`] (trigger measurement, anchoring, window-edge
//! snapping). Base leaves open state, motion and focus moves to callers; they
//! live here.
use crate::motion::{self, Motion};
use crate::theme::color;
use crate::tokens::ColorRole;
use gpui_kit::{
    Anchor, AnyElement, App, Bounds, BoxShadow, Element, ElementId, Entity, FocusHandle,
    GlobalElementId, InspectorElementId, InteractiveElement, IntoElement, KeyDownEvent, LayoutId,
    MouseButton, ParentElement, Pixels, Point, Rems, Size, Styled, Window, canvas, div, point, px,
};
use gpui_kit::{KeyBinding, actions, prelude::FluentBuilder as _};
use std::{cell::Cell, rc::Rc};

actions!(
    u0ui_floating,
    [
        /// Tab on the trigger of an open non-modal surface: into the surface.
        IntoSurface,
        /// Tab inside an open non-modal surface.
        SurfaceTab,
        /// Shift+Tab inside an open non-modal surface.
        SurfaceTabPrev
    ]
);

/// The key context of an open non-modal surface's trigger wrapper.
pub(crate) const TRIGGER_CONTEXT: &str = "U0FloatingTrigger";
/// The key context of an open non-modal surface.
pub(crate) const SURFACE_CONTEXT: &str = "U0FloatingSurface";

/// Bind Tab and Shift+Tab around open non-modal surfaces ([`TabFlow`]). A
/// binding in the element's own key context is deeper than Base's
/// window-level `root::Tab`, so it wins. Called by [`crate::init`].
pub(crate) fn init(cx: &mut App) {
    cx.bind_keys([
        KeyBinding::new("tab", IntoSurface, Some(TRIGGER_CONTEXT)),
        KeyBinding::new("tab", SurfaceTab, Some(SURFACE_CONTEXT)),
        KeyBinding::new("shift-tab", SurfaceTabPrev, Some(SURFACE_CONTEXT)),
    ]);
}

/// Base's `root::Tab` from `from`, stepping on past any stop inside the
/// closing `surface` (GPUI orders a floating surface's stops apart from the
/// page's, as it paints last), so focus lands on the page's stop after
/// `from`. Base's action keeps a focus trap around both in force.
pub(crate) fn tab_past(
    from: &FocusHandle,
    surface: &FocusHandle,
    window: &mut Window,
    cx: &mut App,
) {
    from.focus(window, cx);
    let Ok(tab) = cx.build_action("root::Tab", None) else {
        return;
    };
    let mut seen = Vec::new();
    while let Some(at) = window.focused(cx) {
        if seen.contains(&at) {
            break;
        }
        at.dispatch_action(&*tab, window, cx);
        seen.push(at);
        if !surface.contains_focused(window, cx) {
            break;
        }
    }
}

/// Base's root action `name` (`root::Tab` / `root::TabPrev`) from the
/// focused element.
fn step(name: &str, window: &mut Window, cx: &mut App) {
    if let (Some(at), Ok(action)) = (window.focused(cx), cx.build_action(name, None)) {
        at.dispatch_action(&*action, window, cx);
    }
}

/// [`TabFlow`]'s keyed state: trigger handle, end anchor, focus has been
/// inside since the surface opened.
type FlowState = (FocusHandle, FocusHandle, bool);

/// Whether focus is in the trigger wrapper tracked by `handles`.
fn trigger_now(handles: &Entity<FlowState>, window: &Window, cx: &App) -> bool {
    handles.read(cx).0.contains_focused(window, cx)
}

/// Tab order and focus-leave for a non-modal surface that follows its
/// trigger in the reference's DOM (Carbon `Popover`): Tab on the open
/// trigger enters the surface, Shift+Tab from its first stop returns to the
/// trigger (still open), Tab from its last stop closes it and moves to the
/// stop after the trigger, and focus leaving surface and trigger any other
/// way closes it without pulling focus back (`onRequestClose` on
/// `focusout` with a `relatedTarget` outside both).
/// Nested surfaces (a popover, date picker or list opened inside) count as
/// inside: their elements are descendants of this surface.
pub(crate) struct TabFlow {
    /// Tracked by the trigger wrapper (not a tab stop): focus inside it is
    /// "on the trigger".
    pub trigger: FocusHandle,
    /// A zero-size, non-tab-stop anchor after the trigger: Tab and
    /// Shift+Tab from it reach the stops after and on the trigger.
    pub end: FocusHandle,
}

impl TabFlow {
    /// The flow keyed by `id`; closes the surface (`set_open(false)`) when
    /// focus has left it and its trigger this frame.
    pub fn new(
        id: &ElementId,
        open: bool,
        surface: &FocusHandle,
        set_open: &OpenChange,
        window: &mut Window,
        cx: &mut App,
    ) -> Self {
        let handles: Entity<FlowState> =
            window.use_keyed_state((id.clone(), "tab-flow"), cx, |_, cx| {
                (cx.focus_handle(), cx.focus_handle(), false)
            });
        let (trigger, end, had) = handles.read(cx).clone();
        let inside = surface.contains_focused(window, cx) || trigger.contains_focused(window, cx);
        if !open {
            if had {
                handles.update(cx, |h, _| h.2 = false);
            }
        } else if inside {
            if !had {
                handles.update(cx, |h, _| h.2 = true);
            }
        } else if had {
            // Decide once this frame's deferred focus moves have run: a
            // nested surface that just closed (a popover in this one) is
            // still handing focus back to its trigger in here, and until
            // then focus sits on an element that is gone.
            let set_open = set_open.clone();
            let surface = surface.clone();
            window.defer(cx, move |window, cx| {
                let inside =
                    surface.contains_focused(window, cx) || trigger_now(&handles, window, cx);
                if !inside {
                    handles.update(cx, |h, _| h.2 = false);
                    set_open(false, window, cx);
                }
            });
        }
        Self { trigger, end }
    }

    /// Wrap the trigger: track [`Self::trigger`], add [`Self::end`], and
    /// while `open` send Tab into `surface`.
    pub fn trigger(
        &self,
        wrapper: gpui_kit::Stateful<gpui_kit::Div>,
        open: bool,
        surface: &FocusHandle,
        set_open: &OpenChange,
    ) -> gpui_kit::Stateful<gpui_kit::Div> {
        let end = self.end.clone();
        let into = {
            let surface = surface.clone();
            let set_open = set_open.clone();
            let end = end.clone();
            move |_: &IntoSurface, window: &mut Window, cx: &mut App| {
                cx.stop_propagation();
                surface.focus(window, cx);
                step("root::Tab", window, cx);
                if !surface.contains_focused(window, cx) || surface.is_focused(window) {
                    // Nothing to stop on inside: Tab goes on past it.
                    set_open(false, window, cx);
                    tab_past(&end, &surface, window, cx);
                }
            }
        };
        wrapper
            .track_focus(&self.trigger.clone().tab_stop(false))
            .when(open, |this| {
                this.key_context(TRIGGER_CONTEXT).on_action(into)
            })
            .child(div().track_focus(&end.tab_stop(false)).absolute().size_0())
    }

    /// Key handling for the surface element.
    pub fn surface(
        &self,
        surface_el: gpui_kit::Stateful<gpui_kit::Div>,
        surface: &FocusHandle,
        set_open: &OpenChange,
    ) -> gpui_kit::Stateful<gpui_kit::Div> {
        let tab = {
            let surface = surface.clone();
            let set_open = set_open.clone();
            let end = self.end.clone();
            move |_: &SurfaceTab, window: &mut Window, cx: &mut App| {
                cx.stop_propagation();
                step("root::Tab", window, cx);
                if !surface.contains_focused(window, cx) {
                    set_open(false, window, cx);
                    tab_past(&end, &surface, window, cx);
                }
            }
        };
        let back = {
            let surface = surface.clone();
            let end = self.end.clone();
            move |_: &SurfaceTabPrev, window: &mut Window, cx: &mut App| {
                cx.stop_propagation();
                step("root::TabPrev", window, cx);
                if !surface.contains_focused(window, cx) || surface.is_focused(window) {
                    end.focus(window, cx);
                    step("root::TabPrev", window, cx);
                }
            }
        };
        surface_el
            .key_context(SURFACE_CONTEXT)
            .on_action(tab)
            .on_action(back)
    }
}

/// `px` at 100% zoom as rems (Carbon's rem is 16px).
pub(crate) fn rem(px_value: f32) -> Rems {
    gpui_kit::rems(px_value / crate::tokens::REM_PX)
}

/// The one shadow floating layers carry: `box-shadow: 0 2px 6px var(--shadow)`
/// (`.cds--menu`, `.cu-panel`, `.cu-command`).
pub fn floating_shadow() -> Vec<BoxShadow> {
    vec![BoxShadow::new(px(0.), px(2.), color(ColorRole::Shadow)).blur_radius(px(6.))]
}

/// The popover's shadow, `.cds--popover--drop-shadow .cds--popover { filter:
/// drop-shadow(0 0.125rem 0.125rem rgba(0, 0, 0, 0.2)) }` (Popover, HoverCard).
/// A box shadow stands in for the filter, which GPUI lacks; the caret is
/// left without one.
pub fn popover_drop_shadow() -> Vec<BoxShadow> {
    // The CSS hard-codes black at 20%; there is no token for it.
    vec![BoxShadow::new(px(0.), px(2.), gpui_kit::hsla(0., 0., 0., 0.2)).blur_radius(px(2.))]
}

/// An open-change callback.
pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;

/// A plain callback.
pub type Callback = Rc<dyn Fn(&mut Window, &mut App)>;

/// Resolved open state for one frame, with a setter that respects
/// controlled/uncontrolled ownership (`OpenState` in `index.d.ts`).
#[derive(Clone)]
pub(crate) struct Openness {
    /// Whether the surface is open this frame.
    pub open: bool,
    state: Entity<bool>,
    controlled: bool,
    on_change: Option<OpenChange>,
}

impl Openness {
    /// Request `open`: uncontrolled state updates itself; the callback is told
    /// either way.
    pub fn set(&self, open: bool, window: &mut Window, cx: &mut App) {
        if !self.controlled {
            self.state.update(cx, |state, cx| {
                if *state != open {
                    *state = open;
                    cx.notify();
                }
            });
        }
        if let Some(on_change) = &self.on_change {
            on_change(open, window, cx);
        }
        window.refresh();
    }

    /// A shareable setter.
    pub fn setter(&self) -> OpenChange {
        let this = self.clone();
        Rc::new(move |open, window, cx| this.set(open, window, cx))
    }
}

/// Resolve `open` (controlled) or the keyed internal state seeded by
/// `default_open` (uncontrolled).
pub(crate) fn openness(
    id: &ElementId,
    open: Option<bool>,
    default_open: bool,
    on_change: Option<OpenChange>,
    window: &mut Window,
    cx: &mut App,
) -> Openness {
    let state = window.use_keyed_state((id.clone(), "open"), cx, |_, _| default_open);
    Openness {
        open: open.unwrap_or_else(|| *state.read(cx)),
        state,
        controlled: open.is_some(),
        on_change,
    }
}

/// Presence progress, 0 (absent) → 1 (present): `enter` while opening, `exit`
/// while closing, retargeting from the current value when interrupted (Base's
/// keyed transition shortens a reversal like a CSS transition does). The motion
/// is non-spatial, so under reduced motion the fade keeps playing; callers drop
/// any translation when [`motion::reduced_motion`] is on.
///
/// The surface stays mounted while `open || progress > 0`.
pub(crate) fn presence(
    id: impl Into<ElementId>,
    open: bool,
    enter: Motion,
    exit: Motion,
    window: &mut Window,
    cx: &mut App,
) -> f32 {
    let id: ElementId = id.into();
    let motion = if open { enter } else { exit };
    motion::animate(
        (id, "presence"),
        if open { 1f32 } else { 0. },
        motion.spatial(false),
        window,
        cx,
    )
}

/// Entrance-only presence, 0 → 1 with `enter` while open; closing cuts to 0
/// on the same frame (the reference unmounts the surface at once, as
/// `.cu-panel` does). Reopening animates the entrance again from 0.
pub(crate) fn entrance(
    id: impl Into<ElementId>,
    open: bool,
    enter: Motion,
    window: &mut Window,
    cx: &mut App,
) -> f32 {
    let id: ElementId = id.into();
    if open {
        // Non-spatial: callers drop any slide under reduced motion.
        motion::animate((id, "presence"), 1f32, enter.spatial(false), window, cx)
    } else {
        // A zero-length transition finishes at once and leaves the keyed
        // state at 0, so the next open starts from there.
        gpui_kit::base::transition(
            (id, "presence"),
            0f32,
            gpui_kit::base::Transition::new(std::time::Duration::ZERO),
            window,
            cx,
        )
    }
}

/// Focus that moves into a modal or floating surface when it opens and returns
/// to the previously focused element when it closes. Base's hosts trap focus
/// but leave both moves to the application.
struct SurfaceFocus {
    focus: FocusHandle,
    previous: Option<FocusHandle>,
    shown: bool,
}

/// The focus handle of the surface keyed by `id`, after applying this frame's
/// open/close focus moves. `initial` (if any) receives focus on open instead of
/// the surface itself (Carbon focuses a danger modal's secondary button).
pub(crate) fn surface_focus(
    id: &ElementId,
    open: bool,
    initial: Option<FocusHandle>,
    window: &mut Window,
    cx: &mut App,
) -> FocusHandle {
    surface_focus_returning(id, open, initial, None, window, cx)
}

/// [`surface_focus`], returning focus on close to `return_to` when given
/// instead of whatever had focus when the surface opened (a menubar menu
/// reached with ←/→ from another menu returns to its own trigger, not to
/// the menu it replaced).
pub(crate) fn surface_focus_returning(
    id: &ElementId,
    open: bool,
    initial: Option<FocusHandle>,
    return_to: Option<FocusHandle>,
    window: &mut Window,
    cx: &mut App,
) -> FocusHandle {
    let state = window.use_keyed_state((id.clone(), "surface-focus"), cx, |_, cx| SurfaceFocus {
        focus: cx.focus_handle(),
        previous: None,
        shown: false,
    });
    let shown = state.read(cx).shown;
    if open && !shown {
        let previous = return_to.or_else(|| window.focused(cx));
        state.update(cx, |state, _| {
            state.shown = true;
            state.previous = previous;
        });
        let target = initial.unwrap_or_else(|| state.read(cx).focus.clone());
        // The host attaches its focus handle while painting this frame.
        window.defer(cx, move |window, cx| target.focus(window, cx));
    } else if !open && shown {
        let previous = state.update(cx, |state, _| {
            state.shown = false;
            state.previous.take()
        });
        let surface = state.read(cx).focus.clone();
        // An action that closed the surface may also have moved focus on
        // purpose (a palette entry that navigates focuses the new page): keep
        // that instead of pulling focus back to the old trigger. The last
        // frame still holds the surface, so "inside it" is answerable here.
        let now = window.focused(cx);
        if moved_elsewhere(now.as_ref(), previous.as_ref(), || {
            surface.contains_focused(window, cx)
        }) {
            return state.read(cx).focus.clone();
        }
        window.defer(cx, move |window, cx| match previous {
            Some(previous) => previous.focus(window, cx),
            // Nothing had focus before: do not leave it on a surface that is
            // going away, where keys would hit its (closed) dialog context.
            None if surface.contains_focused(window, cx) => window.blur(cx),
            None => {}
        });
    }
    state.read(cx).focus.clone()
}

/// Whether focus left a closing surface for somewhere other than the element
/// it would return to: `now` is set, is not `previous`, and is not inside the
/// surface (`inside`, asked only when needed).
fn moved_elsewhere(
    now: Option<&FocusHandle>,
    previous: Option<&FocusHandle>,
    inside: impl FnOnce() -> bool,
) -> bool {
    match now {
        Some(now) => Some(now) != previous && !inside(),
        None => false,
    }
}

/// Wrap a caller's trigger element so pressing it (pointer) or activating it
/// from the keyboard (Enter/Space while focus is inside) runs `activate`.
/// GPUI cannot inject a click handler into an arbitrary element, so this is
/// Base's `DialogTrigger` wrapper plus the keyboard path.
pub(crate) fn trigger_wrapper(
    id: impl Into<ElementId>,
    trigger: AnyElement,
    activate: Callback,
) -> gpui_kit::Stateful<gpui_kit::Div> {
    let on_key = activate.clone();
    div()
        .id(id)
        .flex_shrink_0()
        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
            activate(window, cx);
        })
        .on_key_down(move |event: &KeyDownEvent, window, cx| {
            if matches!(event.keystroke.key.as_str(), "enter" | "space") && !event.is_held {
                on_key(window, cx);
                cx.stop_propagation();
            }
        })
        .child(trigger)
}

/// The gap Base's `Popup` keeps from the window edges (`WINDOW_MARGIN`).
pub const WINDOW_MARGIN: f32 = 8.;

/// Which side of its trigger a dropdown surface (list-box menu, date-picker
/// calendar, dropdown menu) opens on.
///
/// Carbon's list boxes and menus open below the field (`direction="bottom"`,
/// the menu attached at the field's bottom edge); with `autoAlign` they flip
/// above when there is no room below but there is above. Base's `Popup` only
/// clamps a surface into the window, which slides it up over its own trigger
/// near the bottom edge; choosing the side first keeps the trigger visible.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DropSide {
    /// Hanging from the trigger's bottom edge.
    #[default]
    Below,
    /// Standing on the trigger's top edge.
    Above,
}

impl DropSide {
    /// The side for a surface `height` px tall under a trigger spanning
    /// `top..bottom` in a viewport `viewport` px tall: below when it fits,
    /// else above when it fits there, else the roomier side.
    pub fn choose(top: f32, bottom: f32, height: f32, viewport: f32) -> Self {
        let below = Self::Below.room(top, bottom, viewport);
        let above = Self::Above.room(top, bottom, viewport);
        if height <= below || (height > above && below >= above) {
            Self::Below
        } else {
            Self::Above
        }
    }

    /// The height available on this side, keeping [`WINDOW_MARGIN`] from the
    /// window edge.
    pub fn room(self, top: f32, bottom: f32, viewport: f32) -> f32 {
        match self {
            Self::Below => viewport - WINDOW_MARGIN - bottom,
            Self::Above => top - WINDOW_MARGIN,
        }
        .max(0.)
    }

    /// The Base anchor for a surface hanging from the trigger's start edge.
    pub fn anchor(self) -> Anchor {
        match self {
            Self::Below => Anchor::TopLeft,
            Self::Above => Anchor::BottomLeft,
        }
    }

    /// The Base anchor for a surface centred on the trigger (Carbon
    /// `menuAlignment="bottom"`).
    pub fn anchor_center(self) -> Anchor {
        match self {
            Self::Below => Anchor::TopCenter,
            Self::Above => Anchor::BottomCenter,
        }
    }

    /// The Base anchor for a surface aligned with the trigger's end edge
    /// (Carbon `menuAlignment="bottom-end"`).
    pub fn anchor_end(self) -> Anchor {
        match self {
            Self::Below => Anchor::TopRight,
            Self::Above => Anchor::BottomRight,
        }
    }
}

/// Which edge of its trigger a Carbon `Menu` given the trigger's
/// `x: [left, right]` lines up with (`Menu`'s `calculatePosition` in
/// `bundle.js`): the trigger's start edge when the menu fits before the
/// window's end, keeping [`WINDOW_MARGIN`]; else its end edge when the menu
/// fits there; else the start edge, clamped into the window.
pub fn menu_hangs_from_end(left: f32, right: f32, width: f32, viewport: f32) -> bool {
    let start_fits = viewport - WINDOW_MARGIN - width - left >= 0.;
    let end_fits = right - width >= 0.;
    !start_fits && end_fits
}

/// Per-instance dropdown placement state: the trigger's window bounds and
/// the surface's size, both recorded while painting, and the side the
/// surface was last placed on.
#[derive(Clone, Default)]
pub(crate) struct DropAnchor {
    trigger: Rc<Cell<Bounds<Pixels>>>,
    surface: Rc<Cell<Size<Pixels>>>,
    side: Rc<Cell<DropSide>>,
    /// See [`Self::set_top_inset`].
    top_inset: Rc<Cell<f32>>,
    /// The surface measured this frame fits the side it was placed on (see
    /// [`Self::surface`]).
    settled: Rc<Cell<bool>>,
}

/// The [`DropAnchor`] keyed by `id`.
pub(crate) fn drop_anchor(
    id: impl Into<ElementId>,
    window: &mut Window,
    cx: &mut App,
) -> DropAnchor {
    window
        .use_keyed_state(id.into(), cx, |_, _| DropAnchor::default())
        .read(cx)
        .clone()
}

impl DropAnchor {
    /// The trigger's last measured width in px.
    pub fn width(&self) -> f32 {
        f32::from(self.trigger.get().size.width)
    }

    /// The trigger's last measured height in px.
    pub fn height(&self) -> f32 {
        f32::from(self.trigger.get().size.height)
    }

    /// How far below the measured trigger's top edge a surface placed
    /// [`DropSide::Above`] stands (px): the measured element can hold more
    /// than the control the surface belongs to, such as a field's label over
    /// its input, and the room above is counted from that control's top.
    pub fn set_top_inset(&self, inset: f32) {
        self.top_inset.set(inset.max(0.));
    }

    /// The trigger's last measured `(top, bottom)`, with the top inset.
    fn edges(trigger: Bounds<Pixels>, inset: f32) -> (f32, f32) {
        let bottom = f32::from(trigger.bottom());
        ((f32::from(trigger.top()) + inset).min(bottom), bottom)
    }

    /// A zero-size canvas that records the bounds of its (`relative`) parent,
    /// the trigger.
    pub fn measure_trigger(&self) -> impl IntoElement + use<> {
        let trigger = self.trigger.clone();
        canvas(move |bounds, _, _| trigger.set(bounds), |_, _, _, _| {})
            .absolute()
            .top_0()
            .left_0()
            .size_full()
    }

    /// The side for a surface `height` px tall and the room there, from the
    /// trigger's last bounds (the side is remembered for
    /// [`Self::measure_surface`]).
    pub fn place(&self, height: f32, window: &Window) -> (DropSide, f32) {
        let (top, bottom) = Self::edges(self.trigger.get(), self.top_inset.get());
        let viewport = f32::from(window.viewport_size().height);
        let side = DropSide::choose(top, bottom, height, viewport);
        self.side.set(side);
        (side, side.room(top, bottom, viewport))
    }

    /// Whether the surface, at its last measured width, hangs from the
    /// trigger's end edge ([`menu_hangs_from_end`]); `None` until the
    /// surface has been measured once.
    pub fn hangs_from_end(&self, window: &Window) -> Option<bool> {
        let width = f32::from(self.surface.get().width);
        if width <= 0. {
            return None;
        }
        let trigger = self.trigger.get();
        Some(menu_hangs_from_end(
            f32::from(trigger.left()),
            f32::from(trigger.right()),
            width,
            f32::from(window.viewport_size().width),
        ))
    }

    /// The side for the surface's last measured size (below until it has
    /// been measured once).
    pub fn place_measured(&self, window: &Window) -> DropSide {
        self.place(f32::from(self.surface.get().height), window).0
    }

    /// A canvas filling its (`relative`) parent, the surface, that records
    /// the surface's size and asks for another frame when the side chosen
    /// for it no longer fits (its first open, or its size changed).
    pub fn measure_surface(&self) -> impl IntoElement + use<> {
        let (trigger, surface, side, inset, settled) = (
            self.trigger.clone(),
            self.surface.clone(),
            self.side.clone(),
            self.top_inset.clone(),
            self.settled.clone(),
        );
        canvas(
            move |bounds, window, _| {
                surface.set(bounds.size);
                let (top, bottom) = Self::edges(trigger.get(), inset.get());
                let want = DropSide::choose(
                    top,
                    bottom,
                    f32::from(bounds.size.height),
                    f32::from(window.viewport_size().height),
                );
                settled.set(want == side.get());
                if want != side.get() {
                    window.request_animation_frame();
                }
            },
            |_, _, _, _| {},
        )
        .absolute()
        .top_0()
        .left_0()
        .size_full()
    }
}

impl DropAnchor {
    /// `content` with [`Self::measure_surface`], painted only once it sits
    /// on the side its measured size calls for. On first open the surface
    /// has not been measured (height 0, so "below"); near the window bottom
    /// it would paint below, clamped over its trigger, for one frame before
    /// flipping above. The measurement happens while prepainting, before
    /// anything paints, so that frame is skipped instead.
    pub fn surface(&self, content: impl IntoElement) -> AnyElement {
        self.settled.set(true);
        PaintGate {
            child: div()
                .relative()
                .child(content)
                .child(self.measure_surface())
                .into_any_element(),
            settled: self.settled.clone(),
        }
        .into_any_element()
    }
}

/// Lays out and prepaints its child, but paints it only when `settled`
/// (set during the child's prepaint) holds.
struct PaintGate {
    child: AnyElement,
    settled: Rc<Cell<bool>>,
}

impl Element for PaintGate {
    type RequestLayoutState = ();
    type PrepaintState = ();

    fn id(&self) -> Option<ElementId> {
        None
    }

    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
        None
    }

    fn request_layout(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (LayoutId, ()) {
        (self.child.request_layout(window, cx), ())
    }

    fn prepaint(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&InspectorElementId>,
        _: Bounds<Pixels>,
        _: &mut (),
        window: &mut Window,
        cx: &mut App,
    ) {
        self.child.prepaint(window, cx);
    }

    fn paint(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&InspectorElementId>,
        _: Bounds<Pixels>,
        _: &mut (),
        _: &mut (),
        window: &mut Window,
        cx: &mut App,
    ) {
        if self.settled.get() {
            self.child.paint(window, cx);
        }
    }
}

/// Translates its child by a fraction of the child's own size plus a fixed
/// offset, like CSS `transform: translate(…)`: layout is unchanged; paint, hit
/// testing and accessibility follow the offset (`window.with_element_offset`,
/// as Kit's dialog entrance surface does).
pub(crate) struct Translate {
    child: AnyElement,
    fraction: Point<f32>,
    offset: Point<Pixels>,
}

/// Where a surface centered on `center` along one axis starts once shifted by
/// `fraction` of its `size` plus `px` (a Carbon `*-start`/`*-end` alignment),
/// kept [`WINDOW_MARGIN`] inside a `viewport` that long. The shift comes
/// first and the clamp after, so a shifted `*-end` surface near the window
/// edge is not moved twice (its caret stays on the trigger).
pub fn cross_origin(center: f32, size: f32, fraction: f32, px: f32, viewport: f32) -> f32 {
    let desired = center - size / 2. + fraction * size + px;
    desired
        .min(viewport - WINDOW_MARGIN - size)
        .max(WINDOW_MARGIN)
}

impl Translate {
    /// `translate(fraction.x * 100%, fraction.y * 100%)` + `offset`.
    pub fn new(child: impl IntoElement, fraction: Point<f32>, offset: Point<Pixels>) -> Self {
        Self {
            child: child.into_any_element(),
            fraction,
            offset,
        }
    }

    /// `translateY(y)` in px.
    pub fn y(child: impl IntoElement, y: f32) -> Self {
        Self::new(child, point(0., 0.), point(px(0.), px(y)))
    }
}

impl Element for Translate {
    type RequestLayoutState = ();
    type PrepaintState = ();

    fn id(&self) -> Option<ElementId> {
        None
    }

    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
        None
    }

    fn request_layout(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (LayoutId, ()) {
        (self.child.request_layout(window, cx), ())
    }

    fn prepaint(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&InspectorElementId>,
        bounds: Bounds<Pixels>,
        _: &mut (),
        window: &mut Window,
        cx: &mut App,
    ) {
        let offset = point(
            bounds.size.width * self.fraction.x + self.offset.x,
            bounds.size.height * self.fraction.y + self.offset.y,
        );
        window.with_element_offset(offset, |window| self.child.prepaint(window, cx));
    }

    fn paint(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&InspectorElementId>,
        _: Bounds<Pixels>,
        _: &mut (),
        _: &mut (),
        window: &mut Window,
        cx: &mut App,
    ) {
        self.child.paint(window, cx);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn menus_hang_from_the_trigger_start_unless_the_window_end_is_near() {
        // A 188px menu under a chevron at 146..178 in a 960px window.
        assert!(!menu_hangs_from_end(146., 178., 188., 960.));
        // Near the end edge it lines up with the trigger's end instead.
        assert!(menu_hangs_from_end(900., 932., 188., 960.));
        // Exactly fitting before the 8px margin still starts at the start.
        assert!(!menu_hangs_from_end(764., 796., 188., 960.));
        assert!(menu_hangs_from_end(765., 796., 188., 960.));
        // No room either way: the start edge, clamped by the popup.
        assert!(!menu_hangs_from_end(100., 132., 400., 300.));
    }

    #[test]
    fn floating_shadow_is_carbons() {
        crate::theme::tests_set(crate::tokens::CarbonTheme::White);
        let shadow = &floating_shadow()[0];
        // `.cds--menu { box-shadow: 0 2px 6px var(--shadow) }`.
        assert_eq!(
            (shadow.offset.x, shadow.offset.y, shadow.blur_radius),
            (px(0.), px(2.), px(6.))
        );
        assert!(!shadow.inset);
        let drop = &popover_drop_shadow()[0];
        assert_eq!(
            (drop.offset.y, drop.blur_radius, drop.color.a),
            (px(2.), px(2.), 0.2)
        );
    }

    #[test]
    fn end_aligned_surfaces_shift_before_clamping() {
        // The header's Theme button centered at 1390 in a 1440 window: a
        // 336px `bottom-right` popover ends 20px past the center (caret over
        // the button) until that would cross the window margin.
        assert_eq!(cross_origin(1390., 336., -0.5, 20., 1440.), 1074.);
        assert_eq!(cross_origin(1430., 336., -0.5, 20., 1440.), 1096.);
        assert_eq!(cross_origin(1300., 336., -0.5, 20., 1440.), 984.);
        // Centered surfaces are only clamped.
        assert_eq!(cross_origin(100., 336., 0., 0., 1440.), 8.);
        assert_eq!(cross_origin(720., 336., 0., 0., 1440.), 552.);
        // `*-start`: starts 20px before the center.
        assert_eq!(cross_origin(400., 200., 0.5, -20., 1440.), 380.);
    }

    /// 60px above the window bottom.
    fn trigger_top(window: &Window) -> Pixels {
        window.viewport_size().height - px(60.)
    }

    /// A surface hanging from a trigger: records where its content painted.
    struct DropHarness {
        painted: Rc<std::cell::RefCell<Vec<Bounds<Pixels>>>>,
    }

    impl gpui_kit::Render for DropHarness {
        fn render(
            &mut self,
            window: &mut Window,
            cx: &mut gpui_kit::Context<Self>,
        ) -> impl IntoElement {
            let anchor = drop_anchor("drop", window, cx);
            let trigger = div()
                .relative()
                .size(px(100.))
                .h(px(32.))
                .child(anchor.measure_trigger());
            let side = anchor.place_measured(window);
            let painted = self.painted.clone();
            let content = div().w(px(100.)).h(px(120.)).child(
                canvas(|_, _, _| {}, move |b, _, _, _| painted.borrow_mut().push(b)).size_full(),
            );
            div().size_full().relative().child(
                div()
                    .absolute()
                    .top(trigger_top(window))
                    .left(px(20.))
                    .child(
                        gpui_kit::base::Popup::new("popup", trigger)
                            .anchor(side.anchor())
                            .content(anchor.surface(content)),
                    ),
            )
        }
    }

    #[gpui_kit::test]
    fn a_drop_surface_never_paints_on_the_side_it_does_not_fit(cx: &mut gpui_kit::TestAppContext) {
        let painted = Rc::new(std::cell::RefCell::new(Vec::new()));
        let (_, window) = cx.add_window_view({
            let painted = painted.clone();
            |_, _| DropHarness { painted }
        });
        // The trigger 60px above the window bottom: 120px fit above,
        // not below. The first frames measure the trigger, then the surface
        // (still unmeasured, so placed below and clamped over the trigger).
        for _ in 0..4 {
            window.update(|window, cx| window.draw(cx).clear(cx));
        }
        let top = window.update(|window, _| trigger_top(window));
        let painted = painted.borrow();
        assert!(!painted.is_empty(), "the surface never painted");
        for bounds in painted.iter() {
            assert!(
                bounds.bottom() <= top,
                "painted over the trigger: {bounds:?}"
            );
        }
    }

    #[test]
    fn drop_side_opens_below_and_flips_above_without_covering_the_trigger() {
        // A 32px field at 400..432 in a 900px window: 160px fits below.
        assert_eq!(DropSide::choose(400., 432., 160., 900.), DropSide::Below);
        assert_eq!(DropSide::Below.room(400., 432., 900.), 460.);
        // Near the bottom (the Tags combobox at 804..836): flip above.
        assert_eq!(DropSide::choose(804., 836., 160., 900.), DropSide::Above);
        assert_eq!(DropSide::Above.room(804., 836., 900.), 796.);
        // Exactly fitting below stays below (8px window margin).
        assert_eq!(DropSide::choose(700., 732., 160., 900.), DropSide::Below);
        assert_eq!(DropSide::choose(700., 733., 160., 900.), DropSide::Above);
        // Fits on neither side: the roomier one; the caller caps the height to its room.
        assert_eq!(DropSide::choose(100., 132., 800., 900.), DropSide::Below);
        assert_eq!(DropSide::choose(700., 732., 800., 900.), DropSide::Above);
        assert_eq!(DropSide::Below.room(100., 900., 900.), 0.);
        assert_eq!(DropSide::Below.anchor(), Anchor::TopLeft);
        assert_eq!(DropSide::Above.anchor(), Anchor::BottomLeft);
    }
}