Skip to main content

arc_ui/overlay/
user_menu.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/user-menu/user-menu.tsx` & `.module.css`
3//!
4//! P3 Component #6: `user-menu`
5//!
6//! - Account menu behind a user's avatar pill (`40px` tall, `32px` face with shape+colour
7//!   [`PresenceDot`], optional name + rotating chevron).
8//! - Presence dot morphs both colour and geometry so status never relies on colour alone:
9//!   - `Available`: solid `success` circle
10//!   - `Busy`: `danger` circle with a spring-animated horizontal bar (`58% × 22%`)
11//!   - `Away`: `warning` circle with a spring-animated inner cutout (`46% × 46%`)
12//! - Panel (`15.5rem = 248px` wide, `10px` radius, `4px` inset, `surface_raised`, `floating`
13//!   shadow): identity header (`34px` face, name + optional plan badge, email), account
14//!   destinations with shortcut hints, inline 3-way Status & Theme segmented switches (`28px`
15//!   cells with a spring-gliding thumb; choosing inside keeps the menu open), and Sign out with
16//!   rising text morph (`"Sign out"` -> `"Signing out"`) and rotating loader arc when `signing_out`
17//!   is active.
18//! - Keyboard: `ArrowDown` / `ArrowUp` / `Home` / `End` across stops, `ArrowLeft` / `ArrowRight`
19//!   inside Status or Theme segmented rows, `Enter` / `Space` to activate, `Esc` to close.
20
21use std::{cell::RefCell, collections::HashMap, rc::Rc, time::Duration};
22
23use arc_motion::{
24    ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, arc_spring_with_options,
25    arc_transition, is_reduced_motion, motion_now, spring::SpringOptions,
26};
27use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
28use gpui_kit::{
29    App, BorderStyle, Bounds, Corners, Edges, ElementId, FocusHandle, Hsla, IntoElement,
30    KeyDownEvent, MouseButton, MouseDownEvent, ObjectFit, ParentElement, PathBuilder, Pixels,
31    RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
32    assets::IconName,
33    base::{Button as BaseButton, StyledExt as _},
34    bounds, canvas, deferred, div, img, point,
35    prelude::*,
36    px, quad, size,
37};
38
39use crate::data::avatar::initials_for;
40
41/// Presence status with distinct colour AND shape (solid, barred, or hollow).
42#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
43pub enum UserStatus {
44    #[default]
45    Available,
46    Busy,
47    Away,
48}
49
50impl UserStatus {
51    pub const ALL: [UserStatus; 3] = [Self::Available, Self::Busy, Self::Away];
52
53    pub const fn index(self) -> usize {
54        match self {
55            Self::Available => 0,
56            Self::Busy => 1,
57            Self::Away => 2,
58        }
59    }
60
61    pub const fn from_index(index: usize) -> Self {
62        match index % 3 {
63            0 => Self::Available,
64            1 => Self::Busy,
65            _ => Self::Away,
66        }
67    }
68
69    pub const fn label(self) -> &'static str {
70        match self {
71            Self::Available => "Available",
72            Self::Busy => "Busy",
73            Self::Away => "Away",
74        }
75    }
76}
77
78/// Inline theme choice inside [`UserMenu`].
79#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
80pub enum ThemePreference {
81    Light,
82    Dark,
83    #[default]
84    System,
85}
86
87impl ThemePreference {
88    pub const ALL: [ThemePreference; 3] = [Self::Light, Self::Dark, Self::System];
89
90    pub const fn index(self) -> usize {
91        match self {
92            Self::Light => 0,
93            Self::Dark => 1,
94            Self::System => 2,
95        }
96    }
97
98    pub const fn from_index(index: usize) -> Self {
99        match index % 3 {
100            0 => Self::Light,
101            1 => Self::Dark,
102            _ => Self::System,
103        }
104    }
105
106    pub const fn label(self) -> &'static str {
107        match self {
108            Self::Light => "Light",
109            Self::Dark => "Dark",
110            Self::System => "System",
111        }
112    }
113}
114
115/// Horizontal alignment of the menu panel relative to the trigger.
116#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
117pub enum UserMenuAlign {
118    Start,
119    Center,
120    #[default]
121    End,
122}
123
124/// User profile shown in [`UserMenu`]'s trigger and header.
125#[derive(Clone, Debug)]
126pub struct UserMenuUser {
127    pub name: SharedString,
128    pub email: SharedString,
129    pub plan: Option<SharedString>,
130    pub avatar_src: Option<SharedString>,
131}
132
133impl UserMenuUser {
134    pub fn new(name: impl Into<SharedString>, email: impl Into<SharedString>) -> Self {
135        Self {
136            name: name.into(),
137            email: email.into(),
138            plan: None,
139            avatar_src: None,
140        }
141    }
142
143    pub fn plan(mut self, plan: impl Into<SharedString>) -> Self {
144        self.plan = Some(plan.into());
145        self
146    }
147
148    pub fn avatar_src(mut self, src: impl Into<SharedString>) -> Self {
149        self.avatar_src = Some(src.into());
150        self
151    }
152}
153
154type ActionCallback = Rc<dyn Fn(&(), &mut Window, &mut App)>;
155type StatusCallback = Rc<dyn Fn(&UserStatus, &mut Window, &mut App)>;
156type ThemeCallback = Rc<dyn Fn(&ThemePreference, &mut Window, &mut App)>;
157type OpenCallback = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
158
159/// One account destination row inside [`UserMenu`].
160#[derive(Clone)]
161pub struct UserMenuItem {
162    pub label: SharedString,
163    pub icon: Option<IconName>,
164    pub keys: Vec<SharedString>,
165    pub on_select: Option<ActionCallback>,
166}
167
168impl UserMenuItem {
169    pub fn new(label: impl Into<SharedString>) -> Self {
170        Self {
171            label: label.into(),
172            icon: None,
173            keys: Vec::new(),
174            on_select: None,
175        }
176    }
177
178    pub fn icon(mut self, icon: IconName) -> Self {
179        self.icon = Some(icon);
180        self
181    }
182
183    pub fn keys<I, S>(mut self, keys: I) -> Self
184    where
185        I: IntoIterator<Item = S>,
186        S: Into<SharedString>,
187    {
188        self.keys = keys.into_iter().map(Into::into).collect();
189        self
190    }
191
192    pub fn on_select(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
193        self.on_select = Some(Rc::new(handler));
194        self
195    }
196}
197
198/// Panel width (`15.5rem = 248px`).
199pub const PANEL_WIDTH: f32 = 248.0;
200pub const ROW_STAGGER_DELAY_SECS: f64 = 0.03;
201pub const ROW_STAGGER_STEP_SECS: f64 = 0.016;
202pub const ROW_ENTER_SECS: f64 = 0.20;
203
204/// `0..=1` entrance progress for row `order` at `elapsed` seconds after menu open.
205pub fn row_stagger_progress(elapsed: f64, order: usize, reduced: bool) -> f32 {
206    if reduced {
207        return 1.0;
208    }
209    let delay = ROW_STAGGER_DELAY_SECS + (order as f64) * ROW_STAGGER_STEP_SECS;
210    let t = ((elapsed - delay) / ROW_ENTER_SECS).clamp(0.0, 1.0) as f32;
211    CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
212}
213
214#[allow(clippy::too_many_arguments)]
215fn paint_presence_dot(
216    cx: f32,
217    cy: f32,
218    diameter: f32,
219    ring_px: f32,
220    status: UserStatus,
221    hole_scale: f32,
222    bar_scale: f32,
223    surface_color: Hsla,
224    dot_color: Hsla,
225    window: &mut Window,
226) {
227    if ring_px > 0.0 {
228        let outer = diameter + ring_px * 2.0;
229        window.paint_quad(quad(
230            bounds(
231                point(px(cx - outer * 0.5), px(cy - outer * 0.5)),
232                size(px(outer), px(outer)),
233            ),
234            Corners::all(px(outer)),
235            surface_color,
236            Edges::all(px(0.0)),
237            Hsla::transparent_black(),
238            BorderStyle::Solid,
239        ));
240    }
241    window.paint_quad(quad(
242        bounds(
243            point(px(cx - diameter * 0.5), px(cy - diameter * 0.5)),
244            size(px(diameter), px(diameter)),
245        ),
246        Corners::all(px(diameter)),
247        dot_color,
248        Edges::all(px(0.0)),
249        Hsla::transparent_black(),
250        BorderStyle::Solid,
251    ));
252
253    let hole = hole_scale.clamp(0.0, 1.0);
254    if hole > 0.02 || status == UserStatus::Away {
255        let h_sz = diameter * 0.46 * hole;
256        if h_sz > 0.5 {
257            window.paint_quad(quad(
258                bounds(
259                    point(px(cx - h_sz * 0.5), px(cy - h_sz * 0.5)),
260                    size(px(h_sz), px(h_sz)),
261                ),
262                Corners::all(px(h_sz)),
263                surface_color,
264                Edges::all(px(0.0)),
265                Hsla::transparent_black(),
266                BorderStyle::Solid,
267            ));
268        }
269    }
270
271    let bar = bar_scale.clamp(0.0, 1.0);
272    if bar > 0.02 {
273        let bw = diameter * 0.58 * bar;
274        let bh = (diameter * 0.22).max(1.5);
275        window.paint_quad(quad(
276            bounds(
277                point(px(cx - bw * 0.5), px(cy - bh * 0.5)),
278                size(px(bw), px(bh)),
279            ),
280            Corners::all(px(1.0)),
281            surface_color,
282            Edges::all(px(0.0)),
283            Hsla::transparent_black(),
284            BorderStyle::Solid,
285        ));
286    }
287}
288
289fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
290    let rad = angle_deg.to_radians();
291    let cos_a = rad.cos();
292    let sin_a = rad.sin();
293    let pts = [(-3.8_f32, -1.9_f32), (0.0, 1.9), (3.8, -1.9)];
294    let mut builder = PathBuilder::stroke(px(1.75));
295    for (i, (lx, ly)) in pts.iter().enumerate() {
296        let rx = cx + lx * cos_a - ly * sin_a;
297        let ry = cy + lx * sin_a + ly * cos_a;
298        let p = point(px(rx), px(ry));
299        if i == 0 {
300            builder.move_to(p);
301        } else {
302            builder.line_to(p);
303        }
304    }
305    if let Ok(path) = builder.build() {
306        window.paint_path(path, color);
307    }
308}
309
310fn paint_theme_glyph(pref: ThemePreference, cx: f32, cy: f32, color: Hsla, window: &mut Window) {
311    match pref {
312        ThemePreference::Light => {
313            // Sun: inner disk + 4 rays.
314            window.paint_quad(quad(
315                bounds(point(px(cx - 2.6), px(cy - 2.6)), size(px(5.2), px(5.2))),
316                Corners::all(px(5.2)),
317                color,
318                Edges::all(px(0.0)),
319                Hsla::transparent_black(),
320                BorderStyle::Solid,
321            ));
322            for (dx, dy) in [(0.0_f32, -5.0_f32), (0.0, 5.0), (-5.0, 0.0), (5.0, 0.0)] {
323                let mut b = PathBuilder::stroke(px(1.4));
324                b.move_to(point(px(cx + dx * 0.72), px(cy + dy * 0.72)));
325                b.line_to(point(px(cx + dx), px(cy + dy)));
326                if let Ok(path) = b.build() {
327                    window.paint_path(path, color);
328                }
329            }
330        }
331        ThemePreference::Dark => {
332            // Crescent arc.
333            let mut b = PathBuilder::stroke(px(1.6));
334            let pts = [
335                (cx + 2.2, cy - 4.2),
336                (cx - 1.8, cy - 3.2),
337                (cx - 3.8, cy),
338                (cx - 1.8, cy + 3.2),
339                (cx + 2.2, cy + 4.2),
340            ];
341            for (i, (x, y)) in pts.iter().enumerate() {
342                if i == 0 {
343                    b.move_to(point(px(*x), px(*y)));
344                } else {
345                    b.line_to(point(px(*x), px(*y)));
346                }
347            }
348            if let Ok(path) = b.build() {
349                window.paint_path(path, color);
350            }
351        }
352        ThemePreference::System => {
353            // Monitor rectangle + stand.
354            window.paint_quad(quad(
355                bounds(point(px(cx - 5.0), px(cy - 4.2)), size(px(10.0), px(6.8))),
356                Corners::all(px(1.6)),
357                Hsla::transparent_black(),
358                Edges::all(px(1.4)),
359                color,
360                BorderStyle::Solid,
361            ));
362            let mut b = PathBuilder::stroke(px(1.4));
363            b.move_to(point(px(cx - 2.6), px(cy + 4.4)));
364            b.line_to(point(px(cx + 2.6), px(cy + 4.4)));
365            if let Ok(path) = b.build() {
366                window.paint_path(path, color);
367            }
368        }
369    }
370}
371
372fn paint_sign_out_icon(
373    signing_out: bool,
374    phase_rad: f32,
375    cx: f32,
376    cy: f32,
377    color: Hsla,
378    window: &mut Window,
379) {
380    if signing_out {
381        let mut b = PathBuilder::stroke(px(1.75));
382        let steps = 14;
383        let span = std::f32::consts::PI * 1.45;
384        let r = 5.2_f32;
385        for i in 0..=steps {
386            let a = phase_rad + (i as f32 / steps as f32) * span;
387            let p = point(px(cx + r * a.cos()), px(cy + r * a.sin()));
388            if i == 0 {
389                b.move_to(p);
390            } else {
391                b.line_to(p);
392            }
393        }
394        if let Ok(path) = b.build() {
395            window.paint_path(path, color);
396        }
397    } else {
398        // Door bracket + right arrow.
399        let mut bracket = PathBuilder::stroke(px(1.6));
400        bracket.move_to(point(px(cx - 1.0), px(cy - 4.8)));
401        bracket.line_to(point(px(cx - 5.0), px(cy - 4.8)));
402        bracket.line_to(point(px(cx - 5.0), px(cy + 4.8)));
403        bracket.line_to(point(px(cx - 1.0), px(cy + 4.8)));
404        if let Ok(path) = bracket.build() {
405            window.paint_path(path, color);
406        }
407        let mut arrow = PathBuilder::stroke(px(1.6));
408        arrow.move_to(point(px(cx - 2.0), px(cy)));
409        arrow.line_to(point(px(cx + 5.0), px(cy)));
410        arrow.move_to(point(px(cx + 2.4), px(cy - 2.6)));
411        arrow.line_to(point(px(cx + 5.0), px(cy)));
412        arrow.line_to(point(px(cx + 2.4), px(cy + 2.6)));
413        if let Ok(path) = arrow.build() {
414            window.paint_path(path, color);
415        }
416    }
417}
418
419#[derive(Clone, Copy, Debug, Eq, PartialEq)]
420enum MenuStop {
421    Item(usize),
422    StatusGroup,
423    ThemeGroup,
424    SignOut,
425}
426
427#[derive(Clone)]
428struct UserMenuInternal {
429    open: bool,
430    opened_at_secs: f64,
431    status: UserStatus,
432    theme: ThemePreference,
433    active_stop: Option<MenuStop>,
434    pointer_mode: bool,
435    last_highlight_rect: Option<(f32, f32)>,
436    trigger_hovered: bool,
437    trigger_pressed: bool,
438    last_signing_out: bool,
439    sign_out_changed_at: f64,
440    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
441    panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
442    item_offsets: Rc<RefCell<HashMap<usize, (f32, f32)>>>,
443    sign_out_offset: Rc<RefCell<Option<(f32, f32)>>>,
444    focus_handle: FocusHandle,
445}
446
447impl UserMenuInternal {
448    fn new(
449        default_open: bool,
450        default_status: UserStatus,
451        default_theme: ThemePreference,
452        now: f64,
453        focus_handle: FocusHandle,
454    ) -> Self {
455        Self {
456            open: default_open,
457            opened_at_secs: now - 10.0,
458            status: default_status,
459            theme: default_theme,
460            active_stop: None,
461            pointer_mode: false,
462            last_highlight_rect: None,
463            trigger_hovered: false,
464            trigger_pressed: false,
465            last_signing_out: false,
466            sign_out_changed_at: now - 10.0,
467            trigger_bounds: Rc::new(RefCell::new(None)),
468            panel_bounds: Rc::new(RefCell::new(None)),
469            item_offsets: Rc::new(RefCell::new(HashMap::new())),
470            sign_out_offset: Rc::new(RefCell::new(None)),
471            focus_handle,
472        }
473    }
474}
475
476/// Arc `UserMenu` — top-bar avatar trigger with morphing presence dot, identity header, account
477/// items, inline status/theme segmented switches, and sign-out progress state.
478#[derive(IntoElement)]
479pub struct UserMenu {
480    id: ElementId,
481    user: UserMenuUser,
482    status: Option<UserStatus>,
483    default_status: UserStatus,
484    show_status: bool,
485    on_status_change: Option<StatusCallback>,
486    theme_pref: Option<ThemePreference>,
487    default_theme: ThemePreference,
488    show_theme: bool,
489    on_theme_change: Option<ThemeCallback>,
490    items: Vec<UserMenuItem>,
491    sign_out_keys: Vec<SharedString>,
492    signing_out: bool,
493    on_sign_out: Option<ActionCallback>,
494    align: UserMenuAlign,
495    show_name: bool,
496    open: Option<bool>,
497    default_open: bool,
498    on_open_change: Option<OpenCallback>,
499}
500
501impl UserMenu {
502    pub fn new(id: impl Into<ElementId>, user: UserMenuUser) -> Self {
503        Self {
504            id: id.into(),
505            user,
506            status: None,
507            default_status: UserStatus::Available,
508            show_status: false,
509            on_status_change: None,
510            theme_pref: None,
511            default_theme: ThemePreference::System,
512            show_theme: true,
513            on_theme_change: None,
514            items: Vec::new(),
515            sign_out_keys: Vec::new(),
516            signing_out: false,
517            on_sign_out: None,
518            align: UserMenuAlign::End,
519            show_name: false,
520            open: None,
521            default_open: false,
522            on_open_change: None,
523        }
524    }
525
526    pub fn status(mut self, status: UserStatus) -> Self {
527        self.status = Some(status);
528        self.show_status = true;
529        self
530    }
531
532    pub fn default_status(mut self, status: UserStatus) -> Self {
533        self.default_status = status;
534        self.show_status = true;
535        self
536    }
537
538    pub fn on_status_change(
539        mut self,
540        handler: impl Fn(&UserStatus, &mut Window, &mut App) + 'static,
541    ) -> Self {
542        self.on_status_change = Some(Rc::new(handler));
543        self.show_status = true;
544        self
545    }
546
547    pub fn theme_preference(mut self, pref: ThemePreference) -> Self {
548        self.theme_pref = Some(pref);
549        self
550    }
551
552    pub fn default_theme(mut self, pref: ThemePreference) -> Self {
553        self.default_theme = pref;
554        self
555    }
556
557    pub fn show_theme(mut self, show: bool) -> Self {
558        self.show_theme = show;
559        self
560    }
561
562    pub fn on_theme_change(
563        mut self,
564        handler: impl Fn(&ThemePreference, &mut Window, &mut App) + 'static,
565    ) -> Self {
566        self.on_theme_change = Some(Rc::new(handler));
567        self
568    }
569
570    pub fn items(mut self, items: impl IntoIterator<Item = UserMenuItem>) -> Self {
571        self.items.extend(items);
572        self
573    }
574
575    pub fn sign_out_keys<I, S>(mut self, keys: I) -> Self
576    where
577        I: IntoIterator<Item = S>,
578        S: Into<SharedString>,
579    {
580        self.sign_out_keys = keys.into_iter().map(Into::into).collect();
581        self
582    }
583
584    /// Keeps the menu open with a spinner and `"Signing out"` rising label while `true`.
585    pub fn signing_out(mut self, signing_out: bool) -> Self {
586        self.signing_out = signing_out;
587        self
588    }
589
590    pub fn on_sign_out(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
591        self.on_sign_out = Some(Rc::new(handler));
592        self
593    }
594
595    pub fn align(mut self, align: UserMenuAlign) -> Self {
596        self.align = align;
597        self
598    }
599
600    pub fn show_name(mut self, show_name: bool) -> Self {
601        self.show_name = show_name;
602        self
603    }
604
605    pub fn open(mut self, open: bool) -> Self {
606        self.open = Some(open);
607        self
608    }
609
610    pub fn default_open(mut self, default_open: bool) -> Self {
611        self.default_open = default_open;
612        self
613    }
614
615    pub fn on_open_change(
616        mut self,
617        handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
618    ) -> Self {
619        self.on_open_change = Some(Rc::new(handler));
620        self
621    }
622}
623
624fn build_stops(item_count: usize, show_status: bool, show_theme: bool) -> Vec<MenuStop> {
625    let mut stops = Vec::with_capacity(item_count + 3);
626    for i in 0..item_count {
627        stops.push(MenuStop::Item(i));
628    }
629    if show_status {
630        stops.push(MenuStop::StatusGroup);
631    }
632    if show_theme {
633        stops.push(MenuStop::ThemeGroup);
634    }
635    stops.push(MenuStop::SignOut);
636    stops
637}
638
639impl RenderOnce for UserMenu {
640    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
641        let theme = cx.arc_theme().clone();
642        let colors = theme.colors;
643        let motion = theme.motion;
644        let reduced = is_reduced_motion(cx);
645        let now = motion_now(cx);
646
647        let state_id =
648            ElementId::NamedChild(self.id.clone().into(), "__arc-user-menu-state".into());
649        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
650            UserMenuInternal::new(
651                self.default_open,
652                self.default_status,
653                self.default_theme,
654                now,
655                cx.focus_handle(),
656            )
657        });
658
659        {
660            let prev_so = internal.read(cx).last_signing_out;
661            if prev_so != self.signing_out {
662                internal.update(cx, |s, _| {
663                    s.last_signing_out = self.signing_out;
664                    s.sign_out_changed_at = now;
665                });
666            }
667        }
668
669        let snap = internal.read(cx).clone();
670        let is_open = self.open.unwrap_or(snap.open);
671        let current_status = self.status.unwrap_or(snap.status);
672        let current_theme = self.theme_pref.unwrap_or(snap.theme);
673
674        // Presence dot geometry springs (`hole` for Away, `bar` for Busy).
675        let hole_target = if current_status == UserStatus::Away {
676            1.0
677        } else {
678            0.0
679        };
680        let bar_target = if current_status == UserStatus::Busy {
681            1.0
682        } else {
683            0.0
684        };
685        let (hole_scale, bar_scale) = if reduced {
686            (hole_target, bar_target)
687        } else {
688            (
689                arc_spring(
690                    (self.id.clone(), "dot-hole"),
691                    hole_target,
692                    motion.spring.snappy,
693                    window,
694                    cx,
695                ),
696                arc_spring(
697                    (self.id.clone(), "dot-bar"),
698                    bar_target,
699                    motion.spring.snappy,
700                    window,
701                    cx,
702                ),
703            )
704        };
705        let status_color = match current_status {
706            UserStatus::Available => colors.success,
707            UserStatus::Busy => colors.danger,
708            UserStatus::Away => colors.warning,
709        };
710
711        // Chevron rotation `0 -> 180`.
712        let chevron_deg = if reduced {
713            if is_open { 180.0 } else { 0.0 }
714        } else {
715            arc_spring(
716                (self.id.clone(), "chevron-deg"),
717                if is_open { 180.0 } else { 0.0 },
718                motion.spring.snappy,
719                window,
720                cx,
721            )
722        };
723
724        let menu_presence = ArcPresence::new((self.id.clone(), "panel-presence"), is_open)
725            .animate_initial(false)
726            .config(ArcPresenceConfig {
727                enter_duration: motion.duration.fast,
728                exit_duration: motion.duration.instant,
729                enter_ease: motion.ease.enter,
730                exit_ease: motion.ease.standard,
731                fade_on_reduced_motion: true,
732            })
733            .sample(window, cx);
734
735        let trigger_bg = if snap.trigger_pressed {
736            oklab_mix(colors.foreground, colors.surface_muted, 0.08)
737        } else if is_open || snap.trigger_hovered {
738            colors.surface_muted
739        } else {
740            Hsla::transparent_black()
741        };
742        let trigger_ring_surface = if snap.trigger_pressed {
743            oklab_mix(colors.foreground, colors.surface_muted, 0.08)
744        } else if is_open || snap.trigger_hovered {
745            colors.surface_muted
746        } else {
747            colors.surface
748        };
749
750        let trigger_bounds_ref = snap.trigger_bounds.clone();
751        let trigger_bounds_out = snap.trigger_bounds.clone();
752        let panel_bounds_out = snap.panel_bounds.clone();
753        let internal_outside = internal.clone();
754        let on_open_outside = self.on_open_change.clone();
755        let trigger_probe = canvas(
756            move |rect, _, _| {
757                *trigger_bounds_ref.borrow_mut() = Some(rect);
758            },
759            move |_, _, window, _| {
760                if is_open {
761                    let t_ref = trigger_bounds_out.clone();
762                    let p_ref = panel_bounds_out.clone();
763                    let st = internal_outside.clone();
764                    let cb = on_open_outside.clone();
765                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
766                        if !phase.bubble() {
767                            return;
768                        }
769                        let in_trigger =
770                            t_ref.borrow().is_some_and(|b| b.contains(&event.position));
771                        let in_panel = p_ref.borrow().is_some_and(|b| b.contains(&event.position));
772                        if !in_trigger && !in_panel {
773                            st.update(cx, |s, _| {
774                                s.open = false;
775                                s.active_stop = None;
776                                s.last_highlight_rect = None;
777                            });
778                            if let Some(h) = &cb {
779                                h(&false, window, cx);
780                            }
781                            window.refresh();
782                        }
783                    });
784                }
785            },
786        )
787        .absolute()
788        .inset_0();
789
790        let initials = initials_for(&self.user.name);
791        let show_status = self.show_status;
792
793        // Build 32px trigger avatar face.
794        let trigger_face = div()
795            .relative()
796            .flex_none()
797            .w(px(32.0))
798            .h(px(32.0))
799            .rounded(Radii::PILL)
800            .border_1()
801            .border_color(oklab_mix(
802                colors.foreground,
803                Hsla::transparent_black(),
804                0.09,
805            ))
806            .bg(colors.surface_muted)
807            .text_color(colors.text_secondary)
808            .text_size(px(11.5))
809            .font_medium()
810            .flex()
811            .items_center()
812            .justify_center()
813            .child(if let Some(src) = self.user.avatar_src.clone() {
814                div()
815                    .size_full()
816                    .rounded(Radii::PILL)
817                    .overflow_hidden()
818                    .child(
819                        img(src)
820                            .size_full()
821                            .rounded(Radii::PILL)
822                            .object_fit(ObjectFit::Cover),
823                    )
824                    .into_any_element()
825            } else {
826                div().child(initials.clone()).into_any_element()
827            })
828            .when(show_status, |this| {
829                this.child(
830                    canvas(
831                        |_, _, _| {},
832                        move |rect, _, window, _| {
833                            let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
834                            let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
835                            paint_presence_dot(
836                                cx,
837                                cy,
838                                11.0,
839                                2.0,
840                                current_status,
841                                hole_scale,
842                                bar_scale,
843                                trigger_ring_surface,
844                                status_color,
845                                window,
846                            );
847                        },
848                    )
849                    .absolute()
850                    .right(px(-1.0))
851                    .bottom(px(-1.0))
852                    .size(px(13.0)),
853                )
854            });
855
856        let a11y_label = if show_status {
857            SharedString::from(format!(
858                "Account menu, {}, {}",
859                self.user.name,
860                current_status.label()
861            ))
862        } else {
863            SharedString::from(format!("Account menu, {}", self.user.name))
864        };
865
866        let trigger_id = ElementId::NamedChild(self.id.clone().into(), "trigger".into());
867        let int_hover = internal.clone();
868        let int_down = internal.clone();
869        let int_up = internal.clone();
870        let int_out = internal.clone();
871        let int_click = internal.clone();
872        let on_open_click = self.on_open_change.clone();
873        let focus_for_open = snap.focus_handle.clone();
874        let chevron_fg = if snap.trigger_hovered || is_open {
875            colors.foreground
876        } else {
877            colors.text_muted
878        };
879
880        let trigger_btn = BaseButton::new(trigger_id)
881            .accessibility_label(a11y_label)
882            .on_click(move |_, window, cx| {
883                let t_now = motion_now(cx);
884                let next = !is_open;
885                int_click.update(cx, |s, _| {
886                    s.open = next;
887                    if next {
888                        s.opened_at_secs = t_now;
889                        s.active_stop = None;
890                        s.last_highlight_rect = None;
891                    }
892                });
893                if next {
894                    window.focus(&focus_for_open, cx);
895                }
896                if let Some(cb) = &on_open_click {
897                    cb(&next, window, cx);
898                }
899                window.refresh();
900            })
901            .relative()
902            .flex()
903            .flex_row()
904            .items_center()
905            .gap(Spacing::S2)
906            .h(px(40.0))
907            .pl(px(4.0))
908            .pr(if self.show_name { px(10.0) } else { px(4.0) })
909            .rounded(Radii::PILL)
910            .bg(trigger_bg)
911            .text_color(colors.foreground)
912            .text_size(Typography::TEXT_SM)
913            .cursor_pointer()
914            .on_hover(move |hovered, window, cx| {
915                int_hover.update(cx, |s, _| {
916                    s.trigger_hovered = *hovered;
917                    if !*hovered {
918                        s.trigger_pressed = false;
919                    }
920                });
921                window.refresh();
922            })
923            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
924                int_down.update(cx, |s, _| s.trigger_pressed = true);
925                window.refresh();
926            })
927            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
928                int_up.update(cx, |s, _| s.trigger_pressed = false);
929                window.refresh();
930            })
931            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
932                int_out.update(cx, |s, _| s.trigger_pressed = false);
933                window.refresh();
934            })
935            .child(trigger_probe)
936            .child(trigger_face)
937            .when(self.show_name, |this| {
938                this.child(
939                    div()
940                        .max_w(px(176.0))
941                        .font_medium()
942                        .truncate()
943                        .child(self.user.name.clone()),
944                )
945                .child(
946                    canvas(
947                        |_, _, _| {},
948                        move |rect, _, window, _| {
949                            let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
950                            let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
951                            paint_rotated_chevron(cx, cy, chevron_deg, chevron_fg, window);
952                        },
953                    )
954                    .size(px(16.0)),
955                )
956            });
957
958        // Floating panel.
959        let panel_el = if menu_presence.should_render() {
960            let p = menu_presence.progress.clamp(0.0, 1.0);
961            let panel_y = if reduced { 0.0 } else { -4.0 * (1.0 - p) };
962            let elapsed = (now - snap.opened_at_secs).max(0.0);
963            let menu_line = oklab_mix(colors.foreground, Hsla::transparent_black(), 0.09);
964
965            // Header row (order 0): 34px face + name + plan badge + email.
966            let h_p = row_stagger_progress(elapsed, 0, reduced);
967            if h_p < 0.999 && is_open {
968                window.request_animation_frame();
969            }
970            let panel_surface = colors.surface_raised;
971            let header_face = div()
972                .relative()
973                .flex_none()
974                .w(px(34.0))
975                .h(px(34.0))
976                .rounded(Radii::PILL)
977                .border_1()
978                .border_color(menu_line)
979                .bg(colors.surface_muted)
980                .text_color(colors.text_secondary)
981                .text_size(px(12.2))
982                .font_medium()
983                .flex()
984                .items_center()
985                .justify_center()
986                .child(if let Some(src) = self.user.avatar_src.clone() {
987                    div()
988                        .size_full()
989                        .rounded(Radii::PILL)
990                        .overflow_hidden()
991                        .child(
992                            img(src)
993                                .size_full()
994                                .rounded(Radii::PILL)
995                                .object_fit(ObjectFit::Cover),
996                        )
997                        .into_any_element()
998                } else {
999                    div().child(initials).into_any_element()
1000                })
1001                .when(show_status, |this| {
1002                    this.child(
1003                        canvas(
1004                            |_, _, _| {},
1005                            move |rect, _, window, _| {
1006                                let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
1007                                let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
1008                                paint_presence_dot(
1009                                    cx,
1010                                    cy,
1011                                    10.0,
1012                                    2.0,
1013                                    current_status,
1014                                    hole_scale,
1015                                    bar_scale,
1016                                    panel_surface,
1017                                    status_color,
1018                                    window,
1019                                );
1020                            },
1021                        )
1022                        .absolute()
1023                        .right(px(-1.0))
1024                        .bottom(px(-1.0))
1025                        .size(px(12.0)),
1026                    )
1027                });
1028
1029            let header = div()
1030                .flex()
1031                .flex_row()
1032                .items_center()
1033                .gap(px(10.0))
1034                .p(px(8.0))
1035                .opacity(if is_open { h_p } else { 1.0 })
1036                .mt(px(if is_open && !reduced {
1037                    3.0 * (1.0 - h_p)
1038                } else {
1039                    0.0
1040                }))
1041                .child(header_face)
1042                .child(
1043                    div()
1044                        .flex()
1045                        .flex_col()
1046                        .min_w_0()
1047                        .flex_1()
1048                        .gap(px(2.0))
1049                        .child(
1050                            div()
1051                                .flex()
1052                                .flex_row()
1053                                .items_center()
1054                                .min_w_0()
1055                                .gap(px(6.0))
1056                                .child(
1057                                    div()
1058                                        .text_size(px(13.0))
1059                                        .font_medium()
1060                                        .text_color(colors.foreground)
1061                                        .truncate()
1062                                        .child(self.user.name.clone()),
1063                                )
1064                                .when_some(self.user.plan.clone(), |this, plan| {
1065                                    this.child(
1066                                        div()
1067                                            .h(px(17.0))
1068                                            .px(px(5.0))
1069                                            .rounded(px(4.0))
1070                                            .border_1()
1071                                            .border_color(menu_line)
1072                                            .bg(oklab_mix(
1073                                                colors.foreground,
1074                                                Hsla::transparent_black(),
1075                                                0.04,
1076                                            ))
1077                                            .text_size(px(11.0))
1078                                            .font_medium()
1079                                            .text_color(colors.text_secondary)
1080                                            .flex()
1081                                            .items_center()
1082                                            .child(plan),
1083                                    )
1084                                }),
1085                        )
1086                        .child(
1087                            div()
1088                                .text_size(px(12.0))
1089                                .text_color(colors.text_muted)
1090                                .truncate()
1091                                .child(self.user.email.clone()),
1092                        ),
1093                );
1094
1095            // Resolve highlight geometry (only for Item(i) or SignOut; segmented groups release highlight).
1096            let active_geom = match snap.active_stop {
1097                Some(MenuStop::Item(idx)) => snap.item_offsets.borrow().get(&idx).copied(),
1098                Some(MenuStop::SignOut) => *snap.sign_out_offset.borrow(),
1099                _ => None,
1100            }
1101            .or(snap.last_highlight_rect);
1102
1103            let show_hi = matches!(
1104                snap.active_stop,
1105                Some(MenuStop::Item(_) | MenuStop::SignOut)
1106            ) && active_geom.is_some();
1107            let hi_op = arc_transition(
1108                (self.id.clone(), "hi-op"),
1109                if show_hi { 1.0 } else { 0.0 },
1110                if reduced {
1111                    Duration::ZERO
1112                } else {
1113                    motion.duration.instant
1114                },
1115                motion.ease.standard,
1116                window,
1117                cx,
1118            );
1119            let (target_top, target_h) = active_geom.unwrap_or((0.0, 32.0));
1120            let (pill_top, pill_h) = if reduced || !snap.pointer_mode {
1121                let _ = arc_spring_with_options(
1122                    (self.id.clone(), "hi-top"),
1123                    target_top,
1124                    SpringOptions::new(motion.spring.snappy),
1125                    window,
1126                    cx,
1127                );
1128                let _ = arc_spring_with_options(
1129                    (self.id.clone(), "hi-h"),
1130                    target_h,
1131                    SpringOptions::new(motion.spring.snappy),
1132                    window,
1133                    cx,
1134                );
1135                (target_top, target_h)
1136            } else {
1137                (
1138                    arc_spring(
1139                        (self.id.clone(), "hi-top"),
1140                        target_top,
1141                        motion.spring.snappy,
1142                        window,
1143                        cx,
1144                    ),
1145                    arc_spring(
1146                        (self.id.clone(), "hi-h"),
1147                        target_h,
1148                        motion.spring.snappy,
1149                        window,
1150                        cx,
1151                    ),
1152                )
1153            };
1154
1155            let highlight_pill = div()
1156                .absolute()
1157                .left(px(4.0))
1158                .right(px(4.0))
1159                .top(px(pill_top))
1160                .h(px(pill_h))
1161                .rounded(px(6.0))
1162                .bg(oklab_mix(
1163                    colors.foreground,
1164                    Hsla::transparent_black(),
1165                    0.06,
1166                ))
1167                .opacity(hi_op.clamp(0.0, 1.0));
1168
1169            let make_separator = || {
1170                div()
1171                    .h(px(1.0))
1172                    .my(px(4.0))
1173                    .mx(px(-4.0))
1174                    .bg(menu_line)
1175                    .into_any_element()
1176            };
1177
1178            let mut list_children = Vec::new();
1179            let mut order_counter = 1usize;
1180
1181            // Destination items.
1182            let item_count = self.items.len();
1183            let items_for_key = self.items.clone();
1184            if !self.items.is_empty() {
1185                list_children.push(make_separator());
1186                for (idx, item) in self.items.into_iter().enumerate() {
1187                    let row_order = order_counter;
1188                    order_counter += 1;
1189                    let rp = row_stagger_progress(elapsed, row_order, reduced);
1190                    if rp < 0.999 && is_open {
1191                        window.request_animation_frame();
1192                    }
1193
1194                    let offsets_ref = snap.item_offsets.clone();
1195                    let panel_b_ref = snap.panel_bounds.clone();
1196                    let int_rect = internal.clone();
1197                    let is_curr = snap.active_stop == Some(MenuStop::Item(idx));
1198                    let item_probe = canvas(
1199                        move |rect, _, cx| {
1200                            if let Some(pb) = *panel_b_ref.borrow() {
1201                                let rtop = f32::from(rect.origin.y - pb.origin.y);
1202                                let h = f32::from(rect.size.height);
1203                                offsets_ref.borrow_mut().insert(idx, (rtop, h));
1204                                if is_curr {
1205                                    int_rect.update(cx, |s, _| {
1206                                        s.last_highlight_rect = Some((rtop, h));
1207                                    });
1208                                }
1209                            }
1210                        },
1211                        |_, _, _, _| {},
1212                    )
1213                    .absolute()
1214                    .inset_0();
1215
1216                    let int_hi = internal.clone();
1217                    let int_sel = internal.clone();
1218                    let offsets_hover = snap.item_offsets.clone();
1219                    let on_select = item.on_select.clone();
1220                    let on_open_sel = self.on_open_change.clone();
1221                    let item_id = ElementId::NamedChild(
1222                        self.id.clone().into(),
1223                        SharedString::from(format!("dest-{idx}")),
1224                    );
1225                    let icon_fg = if is_curr {
1226                        colors.foreground
1227                    } else {
1228                        colors.text_secondary
1229                    };
1230
1231                    list_children.push(
1232                        div()
1233                            .id(item_id)
1234                            .test_support()
1235                            .role(Role::MenuItem)
1236                            .aria_label(item.label.clone())
1237                            .relative()
1238                            .flex()
1239                            .flex_row()
1240                            .items_center()
1241                            .gap(px(10.0))
1242                            .h(px(32.0))
1243                            .px(px(8.0))
1244                            .rounded(px(6.0))
1245                            .text_size(px(13.0))
1246                            .text_color(colors.foreground)
1247                            .opacity(if is_open { rp } else { 1.0 })
1248                            .mt(px(if is_open && !reduced {
1249                                3.0 * (1.0 - rp)
1250                            } else {
1251                                0.0
1252                            }))
1253                            .cursor_pointer()
1254                            .on_hover(move |hovered, window, cx| {
1255                                let geom = offsets_hover.borrow().get(&idx).copied();
1256                                int_hi.update(cx, |s, _| {
1257                                    s.pointer_mode = true;
1258                                    if *hovered {
1259                                        s.active_stop = Some(MenuStop::Item(idx));
1260                                        if let Some(g) = geom {
1261                                            s.last_highlight_rect = Some(g);
1262                                        }
1263                                    } else if s.active_stop == Some(MenuStop::Item(idx)) {
1264                                        s.active_stop = None;
1265                                    }
1266                                });
1267                                window.refresh();
1268                            })
1269                            .on_click(move |_, window, cx| {
1270                                int_sel.update(cx, |s, _| {
1271                                    s.open = false;
1272                                    s.active_stop = None;
1273                                });
1274                                if let Some(cb) = &on_open_sel {
1275                                    cb(&false, window, cx);
1276                                }
1277                                if let Some(cb) = &on_select {
1278                                    cb(&(), window, cx);
1279                                }
1280                                window.refresh();
1281                            })
1282                            .child(item_probe)
1283                            .when_some(item.icon, |this, icon| {
1284                                this.child(
1285                                    div()
1286                                        .w(px(16.0))
1287                                        .flex_none()
1288                                        .text_color(icon_fg)
1289                                        .child(icon),
1290                                )
1291                            })
1292                            .child(div().flex_1().min_w_0().truncate().child(item.label))
1293                            .when(!item.keys.is_empty(), |this| {
1294                                this.child(
1295                                    div()
1296                                        .flex_none()
1297                                        .flex()
1298                                        .flex_row()
1299                                        .items_center()
1300                                        .gap(px(2.0))
1301                                        .text_size(Typography::TEXT_XS)
1302                                        .text_color(colors.text_muted)
1303                                        .opacity(0.8)
1304                                        .children(item.keys.into_iter().map(|k| div().child(k))),
1305                                )
1306                            })
1307                            .into_any_element(),
1308                    );
1309                }
1310            }
1311
1312            // Inline Status and Theme segmented switches.
1313            let thumb_bg = if theme.mode.is_dark() {
1314                oklab_mix(colors.foreground, colors.surface_raised, 0.20)
1315            } else {
1316                colors.surface_raised
1317            };
1318            let track_bg = oklab_mix(colors.foreground, Hsla::transparent_black(), 0.05);
1319
1320            if show_status || self.show_theme {
1321                list_children.push(make_separator());
1322            }
1323
1324            if show_status {
1325                let row_order = order_counter;
1326                order_counter += 1;
1327                let rp = row_stagger_progress(elapsed, row_order, reduced);
1328                if rp < 0.999 && is_open {
1329                    window.request_animation_frame();
1330                }
1331
1332                let status_thumb_x = if reduced {
1333                    current_status.index() as f32 * 28.0
1334                } else {
1335                    arc_spring(
1336                        (self.id.clone(), "status-thumb-x"),
1337                        current_status.index() as f32 * 28.0,
1338                        motion.spring.snappy,
1339                        window,
1340                        cx,
1341                    )
1342                };
1343
1344                let int_group_hover = internal.clone();
1345                let status_buttons = UserStatus::ALL.into_iter().map(|opt| {
1346                    let checked = opt == current_status;
1347                    let int_choose = internal.clone();
1348                    let on_sc = self.on_status_change.clone();
1349                    let seg_id = ElementId::NamedChild(
1350                        self.id.clone().into(),
1351                        SharedString::from(format!("status-{}", opt.label())),
1352                    );
1353                    let opt_color = match opt {
1354                        UserStatus::Available => colors.success,
1355                        UserStatus::Busy => colors.danger,
1356                        UserStatus::Away => colors.warning,
1357                    };
1358                    let (opt_hole, opt_bar) = match opt {
1359                        UserStatus::Available => (0.0, 0.0),
1360                        UserStatus::Busy => (0.0, 1.0),
1361                        UserStatus::Away => (1.0, 0.0),
1362                    };
1363
1364                    div()
1365                        .id(seg_id)
1366                        .test_support()
1367                        .role(Role::MenuItemRadio)
1368                        .aria_label(opt.label())
1369                        .w(px(28.0))
1370                        .h(px(22.0))
1371                        .rounded(px(5.0))
1372                        .flex()
1373                        .items_center()
1374                        .justify_center()
1375                        .cursor_pointer()
1376                        .on_click(move |_, window, cx| {
1377                            // Status choices keep the menu open!
1378                            int_choose.update(cx, |s, _| {
1379                                s.status = opt;
1380                                s.active_stop = Some(MenuStop::StatusGroup);
1381                            });
1382                            if let Some(cb) = &on_sc {
1383                                cb(&opt, window, cx);
1384                            }
1385                            window.refresh();
1386                        })
1387                        .child(
1388                            canvas(
1389                                |_, _, _| {},
1390                                move |rect, _, window, _| {
1391                                    let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
1392                                    let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
1393                                    paint_presence_dot(
1394                                        cx,
1395                                        cy,
1396                                        9.0,
1397                                        0.0,
1398                                        opt,
1399                                        opt_hole,
1400                                        opt_bar,
1401                                        if checked { thumb_bg } else { panel_surface },
1402                                        opt_color,
1403                                        window,
1404                                    );
1405                                },
1406                            )
1407                            .size(px(10.0)),
1408                        )
1409                });
1410
1411                list_children.push(
1412                    div()
1413                        .id(ElementId::NamedChild(
1414                            self.id.clone().into(),
1415                            "row-status".into(),
1416                        ))
1417                        .flex()
1418                        .flex_row()
1419                        .items_center()
1420                        .gap(px(10.0))
1421                        .h(px(36.0))
1422                        .pl(px(8.0))
1423                        .pr(px(4.0))
1424                        .opacity(if is_open { rp } else { 1.0 })
1425                        .mt(px(if is_open && !reduced {
1426                            3.0 * (1.0 - rp)
1427                        } else {
1428                            0.0
1429                        }))
1430                        .on_hover(move |hovered, window, cx| {
1431                            if *hovered {
1432                                // Hovering an inline switch releases the row highlight pill.
1433                                int_group_hover.update(cx, |s, _| {
1434                                    s.active_stop = Some(MenuStop::StatusGroup);
1435                                    s.last_highlight_rect = None;
1436                                });
1437                                window.refresh();
1438                            }
1439                        })
1440                        .child(
1441                            canvas(
1442                                |_, _, _| {},
1443                                move |rect, _, window, _| {
1444                                    let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
1445                                    let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
1446                                    paint_presence_dot(
1447                                        cx,
1448                                        cy,
1449                                        10.0,
1450                                        0.0,
1451                                        current_status,
1452                                        hole_scale,
1453                                        bar_scale,
1454                                        panel_surface,
1455                                        status_color,
1456                                        window,
1457                                    );
1458                                },
1459                            )
1460                            .size(px(16.0)),
1461                        )
1462                        .child(
1463                            div()
1464                                .flex_1()
1465                                .text_size(px(13.0))
1466                                .text_color(colors.foreground)
1467                                .child("Status"),
1468                        )
1469                        .child(
1470                            div()
1471                                .relative()
1472                                .h(px(26.0))
1473                                .p(px(2.0))
1474                                .rounded(px(7.0))
1475                                .bg(track_bg)
1476                                .flex()
1477                                .flex_row()
1478                                .items_center()
1479                                .child(
1480                                    div()
1481                                        .absolute()
1482                                        .top(px(2.0))
1483                                        .bottom(px(2.0))
1484                                        .left(px(2.0 + status_thumb_x))
1485                                        .w(px(28.0))
1486                                        .rounded(px(5.0))
1487                                        .border_1()
1488                                        .border_color(menu_line)
1489                                        .bg(thumb_bg),
1490                                )
1491                                .children(status_buttons),
1492                        )
1493                        .into_any_element(),
1494                );
1495            }
1496
1497            if self.show_theme {
1498                let row_order = order_counter;
1499                order_counter += 1;
1500                let rp = row_stagger_progress(elapsed, row_order, reduced);
1501                if rp < 0.999 && is_open {
1502                    window.request_animation_frame();
1503                }
1504
1505                let theme_thumb_x = if reduced {
1506                    current_theme.index() as f32 * 28.0
1507                } else {
1508                    arc_spring(
1509                        (self.id.clone(), "theme-thumb-x"),
1510                        current_theme.index() as f32 * 28.0,
1511                        motion.spring.snappy,
1512                        window,
1513                        cx,
1514                    )
1515                };
1516
1517                let int_group_hover = internal.clone();
1518                let theme_buttons = ThemePreference::ALL.into_iter().map(|opt| {
1519                    let checked = opt == current_theme;
1520                    let int_choose = internal.clone();
1521                    let on_tc = self.on_theme_change.clone();
1522                    let seg_id = ElementId::NamedChild(
1523                        self.id.clone().into(),
1524                        SharedString::from(format!("theme-{}", opt.label())),
1525                    );
1526                    let glyph_fg = if checked {
1527                        colors.foreground
1528                    } else {
1529                        colors.text_muted
1530                    };
1531
1532                    div()
1533                        .id(seg_id)
1534                        .test_support()
1535                        .role(Role::MenuItemRadio)
1536                        .aria_label(opt.label())
1537                        .w(px(28.0))
1538                        .h(px(22.0))
1539                        .rounded(px(5.0))
1540                        .flex()
1541                        .items_center()
1542                        .justify_center()
1543                        .cursor_pointer()
1544                        .on_click(move |_, window, cx| {
1545                            // Theme choices also keep the menu open!
1546                            int_choose.update(cx, |s, _| {
1547                                s.theme = opt;
1548                                s.active_stop = Some(MenuStop::ThemeGroup);
1549                            });
1550                            if let Some(cb) = &on_tc {
1551                                cb(&opt, window, cx);
1552                            }
1553                            window.refresh();
1554                        })
1555                        .child(
1556                            canvas(
1557                                |_, _, _| {},
1558                                move |rect, _, window, _| {
1559                                    let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
1560                                    let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
1561                                    paint_theme_glyph(opt, cx, cy, glyph_fg, window);
1562                                },
1563                            )
1564                            .size(px(14.0)),
1565                        )
1566                });
1567
1568                let lead_color = colors.text_secondary;
1569                list_children.push(
1570                    div()
1571                        .id(ElementId::NamedChild(
1572                            self.id.clone().into(),
1573                            "row-theme".into(),
1574                        ))
1575                        .flex()
1576                        .flex_row()
1577                        .items_center()
1578                        .gap(px(10.0))
1579                        .h(px(36.0))
1580                        .pl(px(8.0))
1581                        .pr(px(4.0))
1582                        .opacity(if is_open { rp } else { 1.0 })
1583                        .mt(px(if is_open && !reduced {
1584                            3.0 * (1.0 - rp)
1585                        } else {
1586                            0.0
1587                        }))
1588                        .on_hover(move |hovered, window, cx| {
1589                            if *hovered {
1590                                int_group_hover.update(cx, |s, _| {
1591                                    s.active_stop = Some(MenuStop::ThemeGroup);
1592                                    s.last_highlight_rect = None;
1593                                });
1594                                window.refresh();
1595                            }
1596                        })
1597                        .child(
1598                            canvas(
1599                                |_, _, _| {},
1600                                move |rect, _, window, _| {
1601                                    let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
1602                                    let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
1603                                    paint_theme_glyph(
1604                                        ThemePreference::Light,
1605                                        cx,
1606                                        cy,
1607                                        lead_color,
1608                                        window,
1609                                    );
1610                                },
1611                            )
1612                            .size(px(16.0)),
1613                        )
1614                        .child(
1615                            div()
1616                                .flex_1()
1617                                .text_size(px(13.0))
1618                                .text_color(colors.foreground)
1619                                .child("Theme"),
1620                        )
1621                        .child(
1622                            div()
1623                                .relative()
1624                                .h(px(26.0))
1625                                .p(px(2.0))
1626                                .rounded(px(7.0))
1627                                .bg(track_bg)
1628                                .flex()
1629                                .flex_row()
1630                                .items_center()
1631                                .child(
1632                                    div()
1633                                        .absolute()
1634                                        .top(px(2.0))
1635                                        .bottom(px(2.0))
1636                                        .left(px(2.0 + theme_thumb_x))
1637                                        .w(px(28.0))
1638                                        .rounded(px(5.0))
1639                                        .border_1()
1640                                        .border_color(menu_line)
1641                                        .bg(thumb_bg),
1642                                )
1643                                .children(theme_buttons),
1644                        )
1645                        .into_any_element(),
1646                );
1647            }
1648
1649            // Sign out row (with Rise text morph & rotating loader arc when signing_out).
1650            list_children.push(make_separator());
1651            {
1652                let row_order = order_counter;
1653                let rp = row_stagger_progress(elapsed, row_order, reduced);
1654                if (rp < 0.999 && is_open) || self.signing_out {
1655                    window.request_animation_frame();
1656                }
1657
1658                // Rise animation when switching between "Sign out" and "Signing out".
1659                let so_elapsed = (now - snap.sign_out_changed_at).max(0.0);
1660                let so_dur = motion.duration.standard.as_secs_f64();
1661                let (so_op, so_dy) = if !reduced && so_elapsed < so_dur {
1662                    window.request_animation_frame();
1663                    let t = (so_elapsed / so_dur).clamp(0.0, 1.0) as f32;
1664                    let e = CubicBezier::from_spec(motion.ease.enter).sample(t);
1665                    let blur = BlurFallback::evaluate(
1666                        px((1.0 - e) * f32::from(motion.blur.subtle)),
1667                        reduced,
1668                    );
1669                    (
1670                        (e * blur.opacity_multiplier).clamp(0.0, 1.0),
1671                        4.0 * (1.0 - e),
1672                    )
1673                } else {
1674                    (1.0, 0.0)
1675                };
1676
1677                let so_ref = snap.sign_out_offset.clone();
1678                let panel_b_ref = snap.panel_bounds.clone();
1679                let int_rect = internal.clone();
1680                let is_curr_so = snap.active_stop == Some(MenuStop::SignOut);
1681                let so_probe = canvas(
1682                    move |rect, _, cx| {
1683                        if let Some(pb) = *panel_b_ref.borrow() {
1684                            let rtop = f32::from(rect.origin.y - pb.origin.y);
1685                            let h = f32::from(rect.size.height);
1686                            *so_ref.borrow_mut() = Some((rtop, h));
1687                            if is_curr_so {
1688                                int_rect.update(cx, |s, _| {
1689                                    s.last_highlight_rect = Some((rtop, h));
1690                                });
1691                            }
1692                        }
1693                    },
1694                    |_, _, _, _| {},
1695                )
1696                .absolute()
1697                .inset_0();
1698
1699                let int_hi = internal.clone();
1700                let int_click_so = internal.clone();
1701                let so_offset_hover = snap.sign_out_offset.clone();
1702                let on_sign_out = self.on_sign_out.clone();
1703                let on_open_so = self.on_open_change.clone();
1704                let signing_out = self.signing_out;
1705                let spin_period = if reduced { 2.4 } else { 0.8 };
1706                let phase_rad = ((now % spin_period) / spin_period) as f32 * std::f32::consts::TAU;
1707                let so_icon_fg = if is_curr_so {
1708                    colors.foreground
1709                } else {
1710                    colors.text_secondary
1711                };
1712                let so_label: SharedString = if signing_out {
1713                    "Signing out".into()
1714                } else {
1715                    "Sign out".into()
1716                };
1717
1718                list_children.push(
1719                    div()
1720                        .id(ElementId::NamedChild(
1721                            self.id.clone().into(),
1722                            "sign-out".into(),
1723                        ))
1724                        .test_support()
1725                        .role(Role::MenuItem)
1726                        .aria_label(so_label.clone())
1727                        .relative()
1728                        .flex()
1729                        .flex_row()
1730                        .items_center()
1731                        .gap(px(10.0))
1732                        .h(px(32.0))
1733                        .px(px(8.0))
1734                        .rounded(px(6.0))
1735                        .text_size(px(13.0))
1736                        .text_color(colors.foreground)
1737                        .opacity(if is_open { rp } else { 1.0 })
1738                        .mt(px(if is_open && !reduced {
1739                            3.0 * (1.0 - rp)
1740                        } else {
1741                            0.0
1742                        }))
1743                        .cursor_pointer()
1744                        .on_hover(move |hovered, window, cx| {
1745                            let geom = *so_offset_hover.borrow();
1746                            int_hi.update(cx, |s, _| {
1747                                s.pointer_mode = true;
1748                                if *hovered {
1749                                    s.active_stop = Some(MenuStop::SignOut);
1750                                    if let Some(g) = geom {
1751                                        s.last_highlight_rect = Some(g);
1752                                    }
1753                                } else if s.active_stop == Some(MenuStop::SignOut) {
1754                                    s.active_stop = None;
1755                                }
1756                            });
1757                            window.refresh();
1758                        })
1759                        .on_click(move |_, window, cx| {
1760                            if let Some(cb) = &on_sign_out {
1761                                cb(&(), window, cx);
1762                            } else {
1763                                int_click_so.update(cx, |s, _| {
1764                                    s.open = false;
1765                                    s.active_stop = None;
1766                                });
1767                                if let Some(cb) = &on_open_so {
1768                                    cb(&false, window, cx);
1769                                }
1770                            }
1771                            window.refresh();
1772                        })
1773                        .child(so_probe)
1774                        .child(
1775                            canvas(
1776                                |_, _, _| {},
1777                                move |rect, _, window, _| {
1778                                    let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
1779                                    let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
1780                                    paint_sign_out_icon(
1781                                        signing_out,
1782                                        phase_rad,
1783                                        cx,
1784                                        cy,
1785                                        so_icon_fg,
1786                                        window,
1787                                    );
1788                                },
1789                            )
1790                            .size(px(16.0)),
1791                        )
1792                        .child(
1793                            div()
1794                                .flex_1()
1795                                .min_w_0()
1796                                .child(div().mt(px(so_dy)).opacity(so_op).child(so_label)),
1797                        )
1798                        .when(!self.sign_out_keys.is_empty(), |this| {
1799                            this.child(
1800                                div()
1801                                    .flex_none()
1802                                    .flex()
1803                                    .flex_row()
1804                                    .items_center()
1805                                    .gap(px(2.0))
1806                                    .text_size(Typography::TEXT_XS)
1807                                    .text_color(colors.text_muted)
1808                                    .opacity(0.8)
1809                                    .children(
1810                                        self.sign_out_keys.into_iter().map(|k| div().child(k)),
1811                                    ),
1812                            )
1813                        })
1814                        .into_any_element(),
1815                );
1816            }
1817
1818            let panel_bounds_ref = snap.panel_bounds.clone();
1819            let panel_probe = canvas(
1820                move |rect, _, _| {
1821                    *panel_bounds_ref.borrow_mut() = Some(rect);
1822                },
1823                |_, _, _, _| {},
1824            )
1825            .absolute()
1826            .inset_0();
1827
1828            let stops = build_stops(item_count, show_status, self.show_theme);
1829            let int_key = internal.clone();
1830            let offsets_key = snap.item_offsets.clone();
1831            let so_offset_key = snap.sign_out_offset.clone();
1832            let on_status_key = self.on_status_change.clone();
1833            let on_theme_key = self.on_theme_change.clone();
1834            let on_sign_out_key = self.on_sign_out.clone();
1835            let on_open_key = self.on_open_change.clone();
1836            let focus_handle = snap.focus_handle.clone();
1837            let panel_id = ElementId::NamedChild(self.id.clone().into(), "panel".into());
1838            let align = self.align;
1839
1840            Some(
1841                deferred(
1842                    div()
1843                        .id(panel_id)
1844                        .test_support()
1845                        .track_focus(&focus_handle)
1846                        .role(Role::Menu)
1847                        .absolute()
1848                        .top(px(48.0 + panel_y))
1849                        .when(align == UserMenuAlign::End, |this| this.right_0())
1850                        .when(align == UserMenuAlign::Start, |this| this.left_0())
1851                        .when(align == UserMenuAlign::Center, |this| {
1852                            this.left(px(-PANEL_WIDTH * 0.5 + 20.0))
1853                        })
1854                        .w(px(PANEL_WIDTH))
1855                        .p(px(4.0))
1856                        .rounded(px(10.0))
1857                        .border_1()
1858                        .border_color(colors.border)
1859                        .bg(panel_surface)
1860                        .text_color(colors.foreground)
1861                        .shadow(Shadows::floating(theme.mode))
1862                        .opacity(p)
1863                        .flex()
1864                        .flex_col()
1865                        .on_key_down(move |event: &KeyDownEvent, window, cx| {
1866                            let key = event.keystroke.key.as_str();
1867                            match key {
1868                                "escape" | "tab" => {
1869                                    int_key.update(cx, |s, _| {
1870                                        s.open = false;
1871                                        s.active_stop = None;
1872                                    });
1873                                    if let Some(cb) = &on_open_key {
1874                                        cb(&false, window, cx);
1875                                    }
1876                                    window.refresh();
1877                                }
1878                                "down" | "up" | "home" | "end" => {
1879                                    if stops.is_empty() {
1880                                        return;
1881                                    }
1882                                    int_key.update(cx, |s, _| {
1883                                        s.pointer_mode = false;
1884                                        let pos = s
1885                                            .active_stop
1886                                            .and_then(|cur| stops.iter().position(|st| *st == cur));
1887                                        let next_pos = match key {
1888                                            "down" => match pos {
1889                                                Some(p) => (p + 1) % stops.len(),
1890                                                None => 0,
1891                                            },
1892                                            "up" => match pos {
1893                                                Some(p) => (p + stops.len() - 1) % stops.len(),
1894                                                None => stops.len() - 1,
1895                                            },
1896                                            "home" => 0,
1897                                            _ => stops.len() - 1,
1898                                        };
1899                                        let next_stop = stops[next_pos];
1900                                        s.active_stop = Some(next_stop);
1901                                        s.last_highlight_rect = match next_stop {
1902                                            MenuStop::Item(i) => {
1903                                                offsets_key.borrow().get(&i).copied()
1904                                            }
1905                                            MenuStop::SignOut => *so_offset_key.borrow(),
1906                                            _ => None,
1907                                        };
1908                                    });
1909                                    window.refresh();
1910                                }
1911                                "left" | "right" => {
1912                                    let delta: usize = if key == "right" { 1 } else { 2 };
1913                                    let active = int_key.read(cx).active_stop;
1914                                    match active {
1915                                        Some(MenuStop::StatusGroup) => {
1916                                            let next = UserStatus::from_index(
1917                                                current_status.index() + delta,
1918                                            );
1919                                            int_key.update(cx, |s, _| s.status = next);
1920                                            if let Some(cb) = &on_status_key {
1921                                                cb(&next, window, cx);
1922                                            }
1923                                            window.refresh();
1924                                        }
1925                                        Some(MenuStop::ThemeGroup) => {
1926                                            let next = ThemePreference::from_index(
1927                                                current_theme.index() + delta,
1928                                            );
1929                                            int_key.update(cx, |s, _| s.theme = next);
1930                                            if let Some(cb) = &on_theme_key {
1931                                                cb(&next, window, cx);
1932                                            }
1933                                            window.refresh();
1934                                        }
1935                                        _ => {}
1936                                    }
1937                                }
1938                                "enter" | "space" => {
1939                                    let active = int_key.read(cx).active_stop;
1940                                    match active {
1941                                        Some(MenuStop::Item(i)) => {
1942                                            int_key.update(cx, |s, _| {
1943                                                s.open = false;
1944                                                s.active_stop = None;
1945                                            });
1946                                            if let Some(cb) = &on_open_key {
1947                                                cb(&false, window, cx);
1948                                            }
1949                                            if let Some(it) = items_for_key.get(i)
1950                                                && let Some(cb) = &it.on_select
1951                                            {
1952                                                cb(&(), window, cx);
1953                                            }
1954                                            window.refresh();
1955                                        }
1956                                        Some(MenuStop::SignOut) => {
1957                                            if let Some(cb) = &on_sign_out_key {
1958                                                cb(&(), window, cx);
1959                                            } else {
1960                                                int_key.update(cx, |s, _| {
1961                                                    s.open = false;
1962                                                    s.active_stop = None;
1963                                                });
1964                                                if let Some(cb) = &on_open_key {
1965                                                    cb(&false, window, cx);
1966                                                }
1967                                            }
1968                                            window.refresh();
1969                                        }
1970                                        _ => {}
1971                                    }
1972                                }
1973                                _ => {}
1974                            }
1975                        })
1976                        .child(panel_probe)
1977                        .child(highlight_pill)
1978                        .child(header)
1979                        .children(list_children),
1980                )
1981                .with_priority(1),
1982            )
1983        } else {
1984            None
1985        };
1986
1987        div()
1988            .id(self.id)
1989            .relative()
1990            .self_start()
1991            .child(trigger_btn)
1992            .when_some(panel_el, |this, panel| this.child(panel))
1993    }
1994}
1995
1996#[cfg(test)]
1997mod tests {
1998    use std::{cell::Cell, rc::Rc};
1999
2000    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
2001    use gpui_kit::{
2002        Context, MouseButton, Render, Role, TestAppContext, div,
2003        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
2004    };
2005
2006    use super::*;
2007
2008    #[test]
2009    fn status_and_theme_indices_roundtrip_and_rows_stagger() {
2010        for (i, st) in UserStatus::ALL.into_iter().enumerate() {
2011            assert_eq!(st.index(), i);
2012            assert_eq!(UserStatus::from_index(i), st);
2013        }
2014        for (i, th) in ThemePreference::ALL.into_iter().enumerate() {
2015            assert_eq!(th.index(), i);
2016            assert_eq!(ThemePreference::from_index(i), th);
2017        }
2018        let r0 = row_stagger_progress(0.05, 0, false);
2019        let r3 = row_stagger_progress(0.05, 3, false);
2020        assert!(r0 > r3);
2021        assert_eq!(row_stagger_progress(0.0, 4, true), 1.0);
2022    }
2023
2024    struct Host {
2025        status: Rc<Cell<UserStatus>>,
2026        signed_out: Rc<Cell<usize>>,
2027    }
2028
2029    impl Render for Host {
2030        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2031            let status = self.status.clone();
2032            let signed_out = self.signed_out.clone();
2033            div().p(Spacing::S6).child(
2034                UserMenu::new(
2035                    "top-user-menu",
2036                    UserMenuUser::new("Elia Kuratli", "elia@uiarc.dev").plan("Pro"),
2037                )
2038                .show_name(true)
2039                .default_status(UserStatus::Available)
2040                .on_status_change(cx.listener(move |_, next: &UserStatus, _, _| {
2041                    status.set(*next);
2042                }))
2043                .items([UserMenuItem::new("Profile").keys(["⌘", "P"])])
2044                .on_sign_out(cx.listener(move |_, _, _, _| {
2045                    signed_out.set(signed_out.get() + 1);
2046                })),
2047            )
2048        }
2049    }
2050
2051    #[gpui_kit::test]
2052    fn user_menu_keeps_open_on_status_switch_and_fires_sign_out(cx: &mut TestAppContext) {
2053        cx.update(|cx| {
2054            gpui_kit::init(cx);
2055            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
2056        });
2057        let status = Rc::new(Cell::new(UserStatus::Available));
2058        let signed_out = Rc::new(Cell::new(0));
2059        let (_view, cx) = cx.add_window_view(|_, _| Host {
2060            status: status.clone(),
2061            signed_out: signed_out.clone(),
2062        });
2063
2064        cx.update(|window, cx| {
2065            window.render_frame(cx);
2066            let trigger = window.find_by_label("Account menu, Elia Kuratli, Available");
2067            assert_eq!(trigger.role(), Some(Role::Button));
2068            let tpos = trigger.bounds().center();
2069            window.pointer_down(tpos, MouseButton::Left, cx);
2070            window.pointer_up(tpos, MouseButton::Left, cx);
2071            window.render_frame(cx);
2072
2073            // Choosing "Busy" inside the status segmented control updates status and keeps the menu open.
2074            let busy = window.find_by_label("Busy");
2075            assert_eq!(busy.role(), Some(Role::MenuItemRadio));
2076            let bpos = busy.bounds().center();
2077            window.pointer_down(bpos, MouseButton::Left, cx);
2078            window.pointer_up(bpos, MouseButton::Left, cx);
2079            window.render_frame(cx);
2080            assert_eq!(status.get(), UserStatus::Busy);
2081
2082            // Menu is still open so we can click "Sign out".
2083            let sign_out = window.find_by_label("Sign out");
2084            let spos = sign_out.bounds().center();
2085            window.pointer_down(spos, MouseButton::Left, cx);
2086            window.pointer_up(spos, MouseButton::Left, cx);
2087            assert_eq!(signed_out.get(), 1);
2088        });
2089    }
2090}