{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sidebar",
  "type": "registry:item",
  "title": "Sidebar",
  "description": "Application navigation with responsive layouts, icon rails, nested menus, and mobile sheets.",
  "files": [
    {
      "path": "registry/theme/locale.rs",
      "type": "registry:file",
      "target": "~/src/ui/locale.rs",
      "content": "//! Layout direction and the built-in strings components draw.\n//!\n//! Components read the [`Direction`] from [`UiTheme::direction`] and mirror\n//! rows, insets, chevrons, popup sides and arrow keys in right-to-left\n//! layouts. Change it with [`set_direction`], which also keeps it across\n//! theme swaps.\n//!\n//! Every word a component draws or announces on its own, such as \"Close\" or\n//! \"Search emoji\", is a [`UiText`]. [`set_strings`] installs the\n//! application's translations; anything it leaves out stays English. Text the\n//! application passes in, such as a button label, is never translated here.\n\nuse std::rc::Rc;\n\nuse gpui_kit::{App, Global, SharedString, Styled, TextAlign, px};\n\nuse super::UiTheme;\n\n/// The order in which a layout reads: left to right or right to left.\n#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]\npub enum Direction {\n    /// Left to right, as in English.\n    #[default]\n    Ltr,\n    /// Right to left, as in Arabic, Hebrew, Persian and Urdu.\n    Rtl,\n}\n\nimpl Direction {\n    /// Whether this is right to left.\n    pub fn is_rtl(self) -> bool {\n        self == Self::Rtl\n    }\n\n    /// The text alignment of the reading start edge.\n    pub fn start_align(self) -> TextAlign {\n        match self {\n            Self::Ltr => TextAlign::Left,\n            Self::Rtl => TextAlign::Right,\n        }\n    }\n\n    /// The keystroke key with `left` and `right` swapped in right-to-left\n    /// layouts, so a handler written for left to right moves toward the\n    /// reading start on the start-side arrow. Other keys pass through.\n    pub fn logical_key(self, key: &str) -> &str {\n        match (self, key) {\n            (Self::Rtl, \"left\") => \"right\",\n            (Self::Rtl, \"right\") => \"left\",\n            _ => key,\n        }\n    }\n\n    /// The Kit placement mirrored for this direction: Left and Right swap in\n    /// right-to-left layouts, Top and Bottom stay.\n    pub fn placement(self, placement: gpui_kit::base::Placement) -> gpui_kit::base::Placement {\n        use gpui_kit::base::Placement;\n        match (self, placement) {\n            (Self::Rtl, Placement::Left) => Placement::Right,\n            (Self::Rtl, Placement::Right) => Placement::Left,\n            _ => placement,\n        }\n    }\n\n    /// The Kit alignment mirrored for this direction along a horizontal edge:\n    /// Start and End swap in right-to-left layouts.\n    pub fn align(self, align: gpui_kit::base::Align) -> gpui_kit::base::Align {\n        use gpui_kit::base::Align;\n        match (self, align) {\n            (Self::Rtl, Align::Start) => Align::End,\n            (Self::Rtl, Align::End) => Align::Start,\n            _ => align,\n        }\n    }\n\n    /// The popup corner mirrored for this direction: left and right corners\n    /// swap in right-to-left layouts.\n    pub fn anchor(self, anchor: gpui_kit::Anchor) -> gpui_kit::Anchor {\n        use gpui_kit::Anchor;\n        if !self.is_rtl() {\n            return anchor;\n        }\n        match anchor {\n            Anchor::TopLeft => Anchor::TopRight,\n            Anchor::TopRight => Anchor::TopLeft,\n            Anchor::BottomLeft => Anchor::BottomRight,\n            Anchor::BottomRight => Anchor::BottomLeft,\n            Anchor::LeftCenter => Anchor::RightCenter,\n            Anchor::RightCenter => Anchor::LeftCenter,\n            other => other,\n        }\n    }\n\n    /// The chevron or arrow pointing toward the reading end (`forward`) or\n    /// start, from the left-to-right `right` icon and `left` icon.\n    pub fn icon<T>(self, forward: bool, left: T, right: T) -> T {\n        if forward == self.is_rtl() {\n            left\n        } else {\n            right\n        }\n    }\n}\n\n/// The key context a right-to-left text input adds around Kit's `Input`, so\n/// the arrow keys move toward the visual side they point to.\n#[doc(hidden)]\npub const RTL_INPUT_CONTEXT: &str = \"GpuicnRtl\";\n\n/// Binds the mirrored arrow keys of right-to-left text inputs.\n#[doc(hidden)]\npub fn bind_keys(cx: &mut App) {\n    use gpui_kit::KeyBinding;\n    use gpui_kit::base::actions::{SelectLeft, SelectRight};\n    use gpui_kit::base::input::{\n        MoveLeft, MoveRight, MoveToNextWord, MoveToPreviousWord, SelectToNextWordEnd,\n        SelectToPreviousWordStart,\n    };\n    let context = Some(\"GpuicnRtl > Input\");\n    // Word movement uses Alt on macOS and Ctrl elsewhere, as in Kit.\n    let words = if cfg!(target_os = \"macos\") {\n        [\"alt-left\", \"alt-right\", \"alt-shift-left\", \"alt-shift-right\"]\n    } else {\n        [\n            \"ctrl-left\",\n            \"ctrl-right\",\n            \"ctrl-shift-left\",\n            \"ctrl-shift-right\",\n        ]\n    };\n    cx.bind_keys([\n        KeyBinding::new(\"left\", MoveRight, context),\n        KeyBinding::new(\"right\", MoveLeft, context),\n        KeyBinding::new(\"shift-left\", SelectRight, context),\n        KeyBinding::new(\"shift-right\", SelectLeft, context),\n        KeyBinding::new(words[0], MoveToNextWord, context),\n        KeyBinding::new(words[1], MoveToPreviousWord, context),\n        KeyBinding::new(words[2], SelectToNextWordEnd, context),\n        KeyBinding::new(words[3], SelectToPreviousWordStart, context),\n    ]);\n}\n\n#[derive(Clone, Copy, Default)]\nstruct DirectionState(Direction);\nimpl Global for DirectionState {}\n\n/// Sets the layout direction for every window and redraws them.\npub fn set_direction(cx: &mut App, direction: Direction) {\n    cx.set_global(DirectionState(direction));\n    if cx.has_global::<UiTheme>() {\n        let mut theme = UiTheme::read(cx).clone();\n        theme.direction = direction;\n        UiTheme::set(cx, theme);\n    }\n}\n\n/// The layout direction, left to right until [`set_direction`] says otherwise.\npub fn direction(cx: &App) -> Direction {\n    cx.try_global::<DirectionState>()\n        .map(|state| state.0)\n        .unwrap_or_default()\n}\n\n/// Wraps text the application supplies, such as a person's name, in Unicode\n/// first-strong isolates, so a right-to-left name does not reorder the\n/// punctuation and words around it, and a left-to-right name inside\n/// right-to-left text keeps its own order.\npub fn isolate(text: impl AsRef<str>) -> SharedString {\n    let text = text.as_ref();\n    if text.is_empty() || text.starts_with('\\u{2068}') {\n        return SharedString::from(text.to_owned());\n    }\n    format!(\"\\u{2068}{text}\\u{2069}\").into()\n}\n\n/// Logical inline-direction styles: start and end are left and right in\n/// left-to-right layouts and swap in right-to-left ones.\npub trait DirectionalStyled: Styled + Sized {\n    /// A flex row whose first child sits at the reading start.\n    fn flex_row_in(self, direction: Direction) -> Self {\n        let element = self.flex();\n        match direction {\n            Direction::Ltr => element.flex_row(),\n            Direction::Rtl => element.flex_row_reverse(),\n        }\n    }\n\n    /// Reverses an existing flex row in right-to-left layouts.\n    fn mirror_row(self, direction: Direction) -> Self {\n        if direction.is_rtl() {\n            self.flex_row_reverse()\n        } else {\n            self\n        }\n    }\n\n    /// Padding on the reading start edge.\n    fn padding_start(mut self, direction: Direction, value: gpui_kit::Pixels) -> Self {\n        let padding = &mut self.style().padding;\n        match direction {\n            Direction::Ltr => padding.left = Some(value.into()),\n            Direction::Rtl => padding.right = Some(value.into()),\n        }\n        self\n    }\n\n    /// Padding on the reading end edge.\n    fn padding_end(mut self, direction: Direction, value: gpui_kit::Pixels) -> Self {\n        let padding = &mut self.style().padding;\n        match direction {\n            Direction::Ltr => padding.right = Some(value.into()),\n            Direction::Rtl => padding.left = Some(value.into()),\n        }\n        self\n    }\n\n    /// Margin on the reading start edge.\n    fn margin_start(mut self, direction: Direction, value: gpui_kit::Pixels) -> Self {\n        let margin = &mut self.style().margin;\n        match direction {\n            Direction::Ltr => margin.left = Some(value.into()),\n            Direction::Rtl => margin.right = Some(value.into()),\n        }\n        self\n    }\n\n    /// Margin on the reading end edge.\n    fn margin_end(mut self, direction: Direction, value: gpui_kit::Pixels) -> Self {\n        let margin = &mut self.style().margin;\n        match direction {\n            Direction::Ltr => margin.right = Some(value.into()),\n            Direction::Rtl => margin.left = Some(value.into()),\n        }\n        self\n    }\n\n    /// Distance of a positioned element from the reading start edge.\n    fn inset_start(mut self, direction: Direction, value: gpui_kit::Pixels) -> Self {\n        let inset = &mut self.style().inset;\n        match direction {\n            Direction::Ltr => inset.left = Some(value.into()),\n            Direction::Rtl => inset.right = Some(value.into()),\n        }\n        self\n    }\n\n    /// Distance of a positioned element from the reading end edge.\n    fn inset_end(mut self, direction: Direction, value: gpui_kit::Pixels) -> Self {\n        let inset = &mut self.style().inset;\n        match direction {\n            Direction::Ltr => inset.right = Some(value.into()),\n            Direction::Rtl => inset.left = Some(value.into()),\n        }\n        self\n    }\n\n    /// A one-pixel border on the reading start edge.\n    fn border_start_1(mut self, direction: Direction) -> Self {\n        let border = &mut self.style().border_widths;\n        match direction {\n            Direction::Ltr => border.left = Some(px(1.).into()),\n            Direction::Rtl => border.right = Some(px(1.).into()),\n        }\n        self\n    }\n\n    /// A one-pixel border on the reading end edge.\n    fn border_end_1(mut self, direction: Direction) -> Self {\n        let border = &mut self.style().border_widths;\n        match direction {\n            Direction::Ltr => border.right = Some(px(1.).into()),\n            Direction::Rtl => border.left = Some(px(1.).into()),\n        }\n        self\n    }\n\n    /// Rounds the two corners on the reading start edge.\n    fn rounded_start(mut self, direction: Direction, radius: gpui_kit::Pixels) -> Self {\n        let corners = &mut self.style().corner_radii;\n        let radius = Some(radius.into());\n        match direction {\n            Direction::Ltr => (corners.top_left, corners.bottom_left) = (radius, radius),\n            Direction::Rtl => (corners.top_right, corners.bottom_right) = (radius, radius),\n        }\n        self\n    }\n\n    /// Rounds the two corners on the reading end edge.\n    fn rounded_end(mut self, direction: Direction, radius: gpui_kit::Pixels) -> Self {\n        let corners = &mut self.style().corner_radii;\n        let radius = Some(radius.into());\n        match direction {\n            Direction::Ltr => (corners.top_right, corners.bottom_right) = (radius, radius),\n            Direction::Rtl => (corners.top_left, corners.bottom_left) = (radius, radius),\n        }\n        self\n    }\n\n    /// A two-pixel border on the reading start edge, as on a highlighted row.\n    fn border_start_2(mut self, direction: Direction) -> Self {\n        let border = &mut self.style().border_widths;\n        match direction {\n            Direction::Ltr => border.left = Some(px(2.).into()),\n            Direction::Rtl => border.right = Some(px(2.).into()),\n        }\n        self\n    }\n\n    /// Removes the border on the reading start edge.\n    fn border_start_0(mut self, direction: Direction) -> Self {\n        let border = &mut self.style().border_widths;\n        match direction {\n            Direction::Ltr => border.left = Some(px(0.).into()),\n            Direction::Rtl => border.right = Some(px(0.).into()),\n        }\n        self\n    }\n\n    /// Text aligned to the reading start edge.\n    fn text_start(self, direction: Direction) -> Self {\n        self.text_align(direction.start_align())\n    }\n}\n\nimpl<T: Styled> DirectionalStyled for T {}\n\n/// A word or sentence a component draws or announces on its own.\n///\n/// Match on it in [`set_strings`] to translate; [`UiText::key`] gives a stable\n/// identifier for message catalogs such as Fluent, and the values a variant\n/// carries are the arguments to place.\n#[derive(Clone, Debug, Eq, Hash, PartialEq)]\n#[non_exhaustive]\npub enum UiText {\n    /// \"Close\", on dialogs, drawers, lightboxes and window controls.\n    Close,\n    /// \"Close notification\", on toasts.\n    CloseNotification,\n    /// \"Loading\", the spinner's accessible name.\n    Loading,\n    /// \"Read only\", announced on read-only fields.\n    ReadOnly,\n    /// \"{label} (required)\", a required field's accessible name.\n    Required(SharedString),\n    /// \"One-time code\", the OTP field's default accessible name.\n    OneTimeCode,\n    /// \"Invalid value\", announced on invalid inputs.\n    InvalidValue,\n    /// \"Unavailable\", announced on disabled list rows and commands.\n    Unavailable,\n    /// \"No results found.\", the command palette's empty state.\n    NoResults,\n    /// \"No items\", the virtual list's empty state.\n    NoItems,\n    /// \"Use arrow keys to navigate and Enter to activate.\", the virtual list's hint.\n    ListInstructions,\n    /// The multi-select virtual list's hint.\n    MultiSelectInstructions,\n    /// \"Selection\", a select's default accessible name.\n    Selection,\n    /// \"Select…\", a select's default placeholder.\n    SelectPlaceholder,\n    /// \"{label} (invalid value)\", an invalid select's accessible name.\n    InvalidSelection(SharedString),\n    /// \"Navigation\", the sidebar's accessible name.\n    Navigation,\n    /// \"Toggle sidebar\".\n    ToggleSidebar,\n    /// \"current destination\", read after the selected sidebar item.\n    CurrentDestination,\n    /// \"expanded\", read after an open disclosure.\n    Expanded,\n    /// \"collapsed\", read after a closed disclosure.\n    Collapsed,\n    /// \"Cut\", in the text context menu.\n    Cut,\n    /// \"Copy\", in the text context menu.\n    Copy,\n    /// \"Paste\", in the text context menu.\n    Paste,\n    /// \"Select All\", in the text context menu.\n    SelectAll,\n    /// \"Decrease value\", on number fields.\n    DecreaseValue,\n    /// \"Increase value\", on number fields.\n    IncreaseValue,\n    /// \"Minimize\", a title bar window control.\n    Minimize,\n    /// \"Maximize\", a title bar window control.\n    Maximize,\n    /// \"Restore\", a title bar window control.\n    Restore,\n    /// \"Uploading… {percent}%\", an attachment's progress.\n    Uploading(u32),\n    /// \"Upload failed\".\n    UploadFailed,\n    /// \"Remove {name}\", on attachments and tags.\n    Remove(SharedString),\n    /// \"Retry uploading {name}\".\n    RetryUpload(SharedString),\n    /// \"Previous month\", on calendars.\n    PreviousMonth,\n    /// \"Next month\", on calendars.\n    NextMonth,\n    /// A weekday name, 0 for \"Sunday\" through 6 for \"Saturday\".\n    Weekday(u8),\n    /// A two-letter weekday heading, 0 for \"Su\" through 6 for \"Sa\".\n    WeekdayShort(u8),\n    /// A month name, 1 for \"January\" through 12 for \"December\".\n    Month(u8),\n    /// A calendar's heading, such as \"March 2026\".\n    MonthYear {\n        /// 1 to 12.\n        month: u8,\n        /// The year.\n        year: i32,\n    },\n    /// A date read aloud, such as \"Saturday, March 14, 2026\".\n    LongDate {\n        /// 0 for Sunday through 6 for Saturday.\n        weekday: u8,\n        /// 1 to 12.\n        month: u8,\n        /// 1 to 31.\n        day: u8,\n        /// The year.\n        year: i32,\n    },\n    /// A compact date, such as \"Mar 14, 2026\".\n    ShortDate {\n        /// 1 to 12.\n        month: u8,\n        /// 1 to 31.\n        day: u8,\n        /// The year.\n        year: i32,\n    },\n    /// \"today\", appended to today's date in a calendar.\n    Today,\n    /// \"Pick a date\", the date picker's placeholder.\n    PickDate,\n    /// \"Pick a date and time\", the date and time picker's placeholder.\n    PickDateTime,\n    /// \"Time, {time}\", the time field's accessible name.\n    TimeField(SharedString),\n    /// \"Hour\".\n    Hour,\n    /// \"AM\", before noon on a 12-hour clock.\n    Am,\n    /// \"PM\", after noon on a 12-hour clock.\n    Pm,\n    /// \"AM or PM\", the time field's period segment.\n    DayPeriod,\n    /// \"Minute\".\n    Minute,\n    /// \"Done\", closing the date and time picker.\n    Done,\n    /// \"Carousel\", the carousel's default accessible name.\n    Carousel,\n    /// \"Previous slide\".\n    PreviousSlide,\n    /// \"Next slide\".\n    NextSlide,\n    /// \"Search commands\", the command palette's input.\n    SearchCommands,\n    /// \"Commands\", the command list and the composer's slash suggestions.\n    Commands,\n    /// \"Command palette\".\n    CommandPalette,\n    /// \"Message\", the composer's accessible name.\n    Message,\n    /// \"People\", the composer's @ suggestions.\n    People,\n    /// \"Channels\", the composer's ~ suggestions.\n    Channels,\n    /// \"Emoji\", the composer's : suggestions and the emoji grid.\n    Emoji,\n    /// \"Suggestions\", the composer's other suggestions.\n    Suggestions,\n    /// \"Load image\", on image placeholders.\n    LoadImage,\n    /// \"Load image from {host}\".\n    LoadImageFrom(SharedString),\n    /// \"Show image preview\", on link embeds.\n    ExpandPreview,\n    /// \"Hide image preview\", on link embeds.\n    CollapsePreview,\n    /// \"Remove preview\", on link embeds.\n    RemovePreview,\n    /// \"Attachment\", an untitled attachment embed.\n    Attachment,\n    /// \"Jump\", on quoted messages.\n    Jump,\n    /// \"Jump to the message from {author}\".\n    JumpToMessageFrom(SharedString),\n    /// \"Originally posted in {channel}\".\n    OriginallyPostedIn(SharedString),\n    /// \"Show more\", expanding long quotes.\n    ShowMore,\n    /// \"Show less\", collapsing long quotes.\n    ShowLess,\n    /// \"Copy code\", on a code block's copy button.\n    CopyCode,\n    /// \"Copied\", after a copy button copied.\n    Copied,\n    /// \"Quoted message from {author}\".\n    QuotedMessageFrom(SharedString),\n    /// \"Search emoji\", the emoji picker's placeholder and input name.\n    SearchEmoji,\n    /// \"Search results\", the emoji picker's results heading.\n    SearchResults,\n    /// \"Frequently used\", an emoji picker heading.\n    FrequentlyUsed,\n    /// \"Recently used\", an emoji picker heading.\n    RecentlyUsed,\n    /// \"Custom\", the emoji picker's custom emoji heading.\n    CustomEmoji,\n    /// \"Emoji categories\", the emoji picker's tab list.\n    EmojiCategories,\n    /// \"No emoji found.\", the emoji picker's empty state.\n    NoEmoji,\n    /// \"Skin tone\", the emoji picker's skin tone menu.\n    SkinTone,\n    /// A skin tone name, 0 for \"Default skin tone\" through 5 for \"Dark skin tone\".\n    SkinToneName(u8),\n    /// \"Previous image\", in the lightbox.\n    PreviousImage,\n    /// \"Next image\", in the lightbox.\n    NextImage,\n    /// \"Image\", an untitled image.\n    Image,\n    /// \"Zoom out\", in the lightbox.\n    ZoomOut,\n    /// \"Zoom in\", in the lightbox.\n    ZoomIn,\n    /// \"Image viewer: {name}\", the lightbox's accessible name.\n    ImageViewer(SharedString),\n    /// \"{index} of {count}\", the lightbox's position, counting from 1.\n    Position {\n        /// The current item, from 1.\n        index: usize,\n        /// How many there are.\n        count: usize,\n    },\n    /// \"Zoom {percent}%\", the lightbox's zoom status.\n    Zoom(u32),\n    /// \"Message failed to send.\".\n    MessageFailed,\n    /// \"Retry\", resending a failed message.\n    Retry,\n    /// \"Delete\", discarding a failed message.\n    Delete,\n    /// \"Add reaction\".\n    AddReaction,\n    /// \"Jump to latest\", the message list's default jump label.\n    JumpToLatest,\n    /// \"1 new message\" or \"{count} new messages\", the message list's jump\n    /// label while messages arrived out of view.\n    NewMessages(usize),\n    /// \"online\", an avatar status.\n    StatusOnline,\n    /// \"away\", an avatar status.\n    StatusAway,\n    /// \"do not disturb\", an avatar status.\n    StatusDnd,\n    /// \"offline\", an avatar status.\n    StatusOffline,\n    /// A list of names, such as \"Ana, Ben and Chen\", for avatar stacks.\n    Names(Vec<SharedString>),\n    /// \"Clear selection\", on a searchable select.\n    ClearSelection,\n    /// \"Show options\", on a searchable select.\n    ShowOptions,\n    /// \"Hue\", the Color Picker's hue slider.\n    ColorHue,\n    /// \"Chroma\", the Color Picker's colorfulness slider.\n    ColorChroma,\n    /// \"Lightness\", the Color Picker's lightness slider.\n    ColorLightness,\n    /// How to move a sortable row with the keyboard; the keys are already\n    /// in reading order.\n    SortInstructions {\n        /// The key that moves toward the start, such as \"Up\".\n        previous: SharedString,\n        /// The key that moves toward the end, such as \"Down\".\n        next: SharedString,\n    },\n    /// A sortable group header's label with its move keys.\n    SortGroup {\n        /// The group's name.\n        label: SharedString,\n        /// The key that moves toward the start.\n        previous: SharedString,\n        /// The key that moves toward the end.\n        next: SharedString,\n    },\n    /// The announcement after a keyboard move in a sortable list.\n    Moved {\n        /// The moved row or group.\n        label: SharedString,\n        /// The new place, counted from 1.\n        position: usize,\n        /// How many places there are.\n        count: usize,\n        /// The group the row moved into, if rows are grouped.\n        group: Option<SharedString>,\n    },\n}\n\nconst WEEKDAYS: [&str; 7] = [\n    \"Sunday\",\n    \"Monday\",\n    \"Tuesday\",\n    \"Wednesday\",\n    \"Thursday\",\n    \"Friday\",\n    \"Saturday\",\n];\nconst MONTHS: [&str; 12] = [\n    \"January\",\n    \"February\",\n    \"March\",\n    \"April\",\n    \"May\",\n    \"June\",\n    \"July\",\n    \"August\",\n    \"September\",\n    \"October\",\n    \"November\",\n    \"December\",\n];\nconst SKIN_TONES: [&str; 6] = [\n    \"Default skin tone\",\n    \"Light skin tone\",\n    \"Medium-light skin tone\",\n    \"Medium skin tone\",\n    \"Medium-dark skin tone\",\n    \"Dark skin tone\",\n];\n\nfn month_english(month: u8) -> &'static str {\n    MONTHS[usize::from(month.clamp(1, 12) - 1)]\n}\n\nimpl UiText {\n    /// A stable kebab-case identifier, such as `close` or `emoji-search`,\n    /// for looking the string up in a message catalog.\n    pub fn key(&self) -> &'static str {\n        match self {\n            Self::Close => \"close\",\n            Self::CloseNotification => \"close-notification\",\n            Self::Loading => \"loading\",\n            Self::ReadOnly => \"read-only\",\n            Self::Required(_) => \"required\",\n            Self::OneTimeCode => \"one-time-code\",\n            Self::InvalidValue => \"invalid-value\",\n            Self::Unavailable => \"unavailable\",\n            Self::NoResults => \"no-results\",\n            Self::NoItems => \"no-items\",\n            Self::ListInstructions => \"list-instructions\",\n            Self::MultiSelectInstructions => \"multi-select-instructions\",\n            Self::Selection => \"selection\",\n            Self::SelectPlaceholder => \"select-placeholder\",\n            Self::InvalidSelection(_) => \"invalid-selection\",\n            Self::Navigation => \"navigation\",\n            Self::ToggleSidebar => \"toggle-sidebar\",\n            Self::CurrentDestination => \"current-destination\",\n            Self::Expanded => \"expanded\",\n            Self::Collapsed => \"collapsed\",\n            Self::Cut => \"cut\",\n            Self::Copy => \"copy\",\n            Self::Paste => \"paste\",\n            Self::SelectAll => \"select-all\",\n            Self::DecreaseValue => \"decrease-value\",\n            Self::IncreaseValue => \"increase-value\",\n            Self::Minimize => \"minimize\",\n            Self::Maximize => \"maximize\",\n            Self::Restore => \"restore\",\n            Self::Uploading(_) => \"uploading\",\n            Self::UploadFailed => \"upload-failed\",\n            Self::Remove(_) => \"remove\",\n            Self::RetryUpload(_) => \"retry-upload\",\n            Self::PreviousMonth => \"previous-month\",\n            Self::NextMonth => \"next-month\",\n            Self::Weekday(_) => \"weekday\",\n            Self::WeekdayShort(_) => \"weekday-short\",\n            Self::Month(_) => \"month\",\n            Self::MonthYear { .. } => \"month-year\",\n            Self::LongDate { .. } => \"long-date\",\n            Self::ShortDate { .. } => \"short-date\",\n            Self::Today => \"today\",\n            Self::PickDate => \"pick-date\",\n            Self::PickDateTime => \"pick-date-time\",\n            Self::TimeField(_) => \"time-field\",\n            Self::Hour => \"hour\",\n            Self::Am => \"am\",\n            Self::Pm => \"pm\",\n            Self::DayPeriod => \"day-period\",\n            Self::Minute => \"minute\",\n            Self::Done => \"done\",\n            Self::Carousel => \"carousel\",\n            Self::PreviousSlide => \"previous-slide\",\n            Self::NextSlide => \"next-slide\",\n            Self::SearchCommands => \"search-commands\",\n            Self::Commands => \"commands\",\n            Self::CommandPalette => \"command-palette\",\n            Self::Message => \"message\",\n            Self::People => \"people\",\n            Self::Channels => \"channels\",\n            Self::Emoji => \"emoji\",\n            Self::Suggestions => \"suggestions\",\n            Self::LoadImage => \"load-image\",\n            Self::LoadImageFrom(_) => \"load-image-from\",\n            Self::ExpandPreview => \"expand-preview\",\n            Self::CollapsePreview => \"collapse-preview\",\n            Self::RemovePreview => \"remove-preview\",\n            Self::Attachment => \"attachment\",\n            Self::Jump => \"jump\",\n            Self::JumpToMessageFrom(_) => \"jump-to-message-from\",\n            Self::OriginallyPostedIn(_) => \"originally-posted-in\",\n            Self::ShowMore => \"show-more\",\n            Self::ShowLess => \"show-less\",\n            Self::CopyCode => \"copy-code\",\n            Self::Copied => \"copied\",\n            Self::QuotedMessageFrom(_) => \"quoted-message-from\",\n            Self::SearchEmoji => \"emoji-search\",\n            Self::SearchResults => \"emoji-search-results\",\n            Self::FrequentlyUsed => \"emoji-frequently-used\",\n            Self::RecentlyUsed => \"emoji-recently-used\",\n            Self::CustomEmoji => \"emoji-custom\",\n            Self::EmojiCategories => \"emoji-categories\",\n            Self::NoEmoji => \"emoji-none\",\n            Self::SkinTone => \"emoji-skin-tone\",\n            Self::SkinToneName(_) => \"emoji-skin-tone-name\",\n            Self::PreviousImage => \"previous-image\",\n            Self::NextImage => \"next-image\",\n            Self::Image => \"image\",\n            Self::ZoomOut => \"zoom-out\",\n            Self::ZoomIn => \"zoom-in\",\n            Self::ImageViewer(_) => \"image-viewer\",\n            Self::Position { .. } => \"position\",\n            Self::Zoom(_) => \"zoom\",\n            Self::MessageFailed => \"message-failed\",\n            Self::Retry => \"retry\",\n            Self::Delete => \"delete\",\n            Self::AddReaction => \"add-reaction\",\n            Self::JumpToLatest => \"jump-to-latest\",\n            Self::NewMessages(_) => \"new-messages\",\n            Self::StatusOnline => \"status-online\",\n            Self::StatusAway => \"status-away\",\n            Self::StatusDnd => \"status-dnd\",\n            Self::StatusOffline => \"status-offline\",\n            Self::Names(_) => \"names\",\n            Self::ClearSelection => \"clear-selection\",\n            Self::ShowOptions => \"show-options\",\n            Self::ColorHue => \"color-hue\",\n            Self::ColorChroma => \"color-chroma\",\n            Self::ColorLightness => \"color-lightness\",\n            Self::SortInstructions { .. } => \"sort-instructions\",\n            Self::SortGroup { .. } => \"sort-group\",\n            Self::Moved { .. } => \"moved\",\n        }\n    }\n\n    /// The English text, which components show when no translation is set.\n    pub fn english(&self) -> SharedString {\n        let text: &'static str = match self {\n            Self::Uploading(percent) => return format!(\"Uploading… {percent}%\").into(),\n            Self::NewMessages(1) => \"1 new message\",\n            Self::NewMessages(count) => return format!(\"{count} new messages\").into(),\n            Self::Required(label) => return format!(\"{label} (required)\").into(),\n            Self::InvalidSelection(label) => return format!(\"{label} (invalid value)\").into(),\n            Self::Remove(name) => return format!(\"Remove {name}\").into(),\n            Self::RetryUpload(name) => return format!(\"Retry uploading {name}\").into(),\n            Self::Weekday(day) => WEEKDAYS[usize::from(*day) % 7],\n            Self::WeekdayShort(day) => &WEEKDAYS[usize::from(*day) % 7][..2],\n            Self::Month(month) => month_english(*month),\n            Self::TimeField(time) => return format!(\"Time, {time}\").into(),\n            Self::MonthYear { month, year } => {\n                return format!(\"{} {year}\", month_english(*month)).into();\n            }\n            Self::LongDate {\n                weekday,\n                month,\n                day,\n                year,\n            } => {\n                let weekday = WEEKDAYS[usize::from(*weekday) % 7];\n                return format!(\"{weekday}, {} {day}, {year}\", month_english(*month)).into();\n            }\n            Self::ShortDate { month, day, year } => {\n                return format!(\"{} {day}, {year}\", &month_english(*month)[..3]).into();\n            }\n            Self::Today => \"today\",\n            Self::LoadImageFrom(host) => return format!(\"Load image from {host}\").into(),\n            Self::JumpToMessageFrom(author) => {\n                return format!(\"Jump to the message from {author}\").into();\n            }\n            Self::OriginallyPostedIn(channel) => {\n                return format!(\"Originally posted in {channel}\").into();\n            }\n            Self::QuotedMessageFrom(author) => {\n                return format!(\"Quoted message from {author}\").into();\n            }\n            Self::ImageViewer(name) => return format!(\"Image viewer: {name}\").into(),\n            Self::Names(names) => {\n                return match names.as_slice() {\n                    [] => SharedString::default(),\n                    [only] => only.clone(),\n                    [rest @ .., last] => format!(\n                        \"{} and {last}\",\n                        rest.iter()\n                            .map(SharedString::as_ref)\n                            .collect::<Vec<_>>()\n                            .join(\", \")\n                    )\n                    .into(),\n                };\n            }\n            Self::Position { index, count } => return format!(\"{index} of {count}\").into(),\n            Self::SortInstructions { previous, next } => {\n                return format!(\n                    \"Press Alt+Shift+{previous} or Alt+Shift+{next} to move the focused row.\"\n                )\n                .into();\n            }\n            Self::SortGroup {\n                label,\n                previous,\n                next,\n            } => return format!(\"{label}, move with Alt+Shift+{previous} or {next}\").into(),\n            Self::Moved {\n                label,\n                position,\n                count,\n                group,\n            } => {\n                return match group {\n                    Some(group) => {\n                        format!(\"{label} moved to position {position} of {count} in {group}\")\n                    }\n                    None => format!(\"{label} moved to position {position} of {count}\"),\n                }\n                .into();\n            }\n            Self::ClearSelection => \"Clear selection\",\n            Self::ShowOptions => \"Show options\",\n            Self::ColorHue => \"Hue\",\n            Self::ColorChroma => \"Chroma\",\n            Self::ColorLightness => \"Lightness\",\n            Self::Zoom(percent) => return format!(\"Zoom {percent}%\").into(),\n            Self::SkinToneName(tone) => SKIN_TONES[usize::from(*tone).min(SKIN_TONES.len() - 1)],\n            Self::Close => \"Close\",\n            Self::CloseNotification => \"Close notification\",\n            Self::Loading => \"Loading\",\n            Self::ReadOnly => \"Read only\",\n            Self::OneTimeCode => \"One-time code\",\n            Self::InvalidValue => \"Invalid value\",\n            Self::Unavailable => \"Unavailable\",\n            Self::NoResults => \"No results found.\",\n            Self::NoItems => \"No items\",\n            Self::ListInstructions => \"Use arrow keys to navigate and Enter to activate.\",\n            Self::MultiSelectInstructions => {\n                \"Multi-select list. Use arrows to navigate, Shift for a range, Command or Control to toggle.\"\n            }\n            Self::Selection => \"Selection\",\n            Self::SelectPlaceholder => \"Select…\",\n            Self::Navigation => \"Navigation\",\n            Self::ToggleSidebar => \"Toggle sidebar\",\n            Self::CurrentDestination => \"current destination\",\n            Self::Expanded => \"expanded\",\n            Self::Collapsed => \"collapsed\",\n            Self::Cut => \"Cut\",\n            Self::Copy => \"Copy\",\n            Self::Paste => \"Paste\",\n            Self::SelectAll => \"Select All\",\n            Self::DecreaseValue => \"Decrease value\",\n            Self::IncreaseValue => \"Increase value\",\n            Self::Minimize => \"Minimize\",\n            Self::Maximize => \"Maximize\",\n            Self::Restore => \"Restore\",\n            Self::UploadFailed => \"Upload failed\",\n            Self::PreviousMonth => \"Previous month\",\n            Self::NextMonth => \"Next month\",\n            Self::PickDate => \"Pick a date\",\n            Self::PickDateTime => \"Pick a date and time\",\n            Self::Hour => \"Hour\",\n            Self::Am => \"AM\",\n            Self::Pm => \"PM\",\n            Self::DayPeriod => \"AM or PM\",\n            Self::Minute => \"Minute\",\n            Self::Done => \"Done\",\n            Self::Carousel => \"Carousel\",\n            Self::PreviousSlide => \"Previous slide\",\n            Self::NextSlide => \"Next slide\",\n            Self::SearchCommands => \"Search commands\",\n            Self::Commands => \"Commands\",\n            Self::CommandPalette => \"Command palette\",\n            Self::Message => \"Message\",\n            Self::People => \"People\",\n            Self::Channels => \"Channels\",\n            Self::Emoji => \"Emoji\",\n            Self::Suggestions => \"Suggestions\",\n            Self::LoadImage => \"Load image\",\n            Self::ExpandPreview => \"Show image preview\",\n            Self::CollapsePreview => \"Hide image preview\",\n            Self::RemovePreview => \"Remove preview\",\n            Self::Attachment => \"Attachment\",\n            Self::Jump => \"Jump\",\n            Self::ShowMore => \"Show more\",\n            Self::ShowLess => \"Show less\",\n            Self::CopyCode => \"Copy code\",\n            Self::Copied => \"Copied\",\n            Self::SearchEmoji => \"Search emoji\",\n            Self::SearchResults => \"Search results\",\n            Self::FrequentlyUsed => \"Frequently used\",\n            Self::RecentlyUsed => \"Recently used\",\n            Self::CustomEmoji => \"Custom\",\n            Self::EmojiCategories => \"Emoji categories\",\n            Self::NoEmoji => \"No emoji found.\",\n            Self::SkinTone => \"Skin tone\",\n            Self::PreviousImage => \"Previous image\",\n            Self::NextImage => \"Next image\",\n            Self::Image => \"Image\",\n            Self::ZoomOut => \"Zoom out\",\n            Self::ZoomIn => \"Zoom in\",\n            Self::MessageFailed => \"Message failed to send.\",\n            Self::Retry => \"Retry\",\n            Self::Delete => \"Delete\",\n            Self::AddReaction => \"Add reaction\",\n            Self::JumpToLatest => \"Jump to latest\",\n            Self::StatusOnline => \"online\",\n            Self::StatusAway => \"away\",\n            Self::StatusDnd => \"do not disturb\",\n            Self::StatusOffline => \"offline\",\n        };\n        SharedString::new_static(text)\n    }\n}\n\ntype Translate = Rc<dyn Fn(&UiText) -> Option<SharedString>>;\n\n#[derive(Clone)]\nstruct Strings(Translate);\nimpl Global for Strings {}\n\n/// Installs the application's translations of the built-in strings and\n/// redraws every window. Return `None` for a string to keep its English.\n///\n/// ```ignore\n/// locale::set_strings(cx, move |text| match text {\n///     UiText::Close => Some(\"إغلاق\".into()),\n///     UiText::Remove(name) => Some(format!(\"إزالة {name}\").into()),\n///     _ => None,\n/// });\n/// ```\npub fn set_strings(cx: &mut App, translate: impl Fn(&UiText) -> Option<SharedString> + 'static) {\n    cx.set_global(Strings(Rc::new(translate)));\n    cx.refresh_windows();\n}\n\n/// Removes the application's translations, so every built-in string is English.\npub fn clear_strings(cx: &mut App) {\n    if cx.has_global::<Strings>() {\n        cx.remove_global::<Strings>();\n        cx.refresh_windows();\n    }\n}\n\n/// The application's translation of a built-in string, or its English.\npub fn text(cx: &App, text: UiText) -> SharedString {\n    cx.try_global::<Strings>()\n        .and_then(|strings| (strings.0)(&text))\n        .unwrap_or_else(|| text.english())\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn english_covers_arguments_and_tables() {\n        assert_eq!(UiText::Remove(\"a.png\".into()).english(), \"Remove a.png\");\n        assert_eq!(UiText::Month(1).english(), \"January\");\n        assert_eq!(UiText::Month(12).english(), \"December\");\n        assert_eq!(UiText::WeekdayShort(0).english(), \"Su\");\n        assert_eq!(UiText::SkinToneName(5).english(), \"Dark skin tone\");\n        assert_eq!(UiText::Uploading(40).english(), \"Uploading… 40%\");\n        assert_eq!(UiText::NewMessages(1).english(), \"1 new message\");\n        assert_eq!(UiText::NewMessages(3).english(), \"3 new messages\");\n        let date = UiText::LongDate {\n            weekday: 6,\n            month: 3,\n            day: 14,\n            year: 2026,\n        };\n        assert_eq!(date.english(), \"Saturday, March 14, 2026\");\n        let date = UiText::ShortDate {\n            month: 3,\n            day: 14,\n            year: 2026,\n        };\n        assert_eq!(date.english(), \"Mar 14, 2026\");\n    }\n\n    #[test]\n    fn logical_keys_swap_only_in_rtl() {\n        assert_eq!(Direction::Ltr.logical_key(\"left\"), \"left\");\n        assert_eq!(Direction::Rtl.logical_key(\"left\"), \"right\");\n        assert_eq!(Direction::Rtl.logical_key(\"right\"), \"left\");\n        assert_eq!(Direction::Rtl.logical_key(\"up\"), \"up\");\n    }\n\n    #[test]\n    fn isolate_wraps_once() {\n        let name = isolate(\"سارة\");\n        assert_eq!(name.as_ref(), \"\\u{2068}سارة\\u{2069}\");\n        assert_eq!(isolate(&name), name);\n        assert_eq!(isolate(\"\"), \"\");\n    }\n\n    #[gpui_kit::test]\n    fn translations_replace_english_and_fall_back(cx: &mut gpui_kit::TestAppContext) {\n        cx.update(|cx| {\n            assert_eq!(text(cx, UiText::Close), \"Close\");\n            set_strings(cx, |text| match text {\n                UiText::Close => Some(\"إغلاق\".into()),\n                UiText::Remove(name) => Some(format!(\"إزالة {name}\").into()),\n                _ => None,\n            });\n            assert_eq!(text(cx, UiText::Close), \"إغلاق\");\n            assert_eq!(text(cx, UiText::Remove(\"a\".into())), \"إزالة a\");\n            assert_eq!(text(cx, UiText::Done), \"Done\");\n            clear_strings(cx);\n            assert_eq!(text(cx, UiText::Close), \"Close\");\n        });\n    }\n\n    #[gpui_kit::test]\n    fn direction_survives_theme_swaps(cx: &mut gpui_kit::TestAppContext) {\n        cx.update(|cx| {\n            super::super::init(cx);\n            set_direction(cx, Direction::Rtl);\n            assert_eq!(UiTheme::read(cx).direction, Direction::Rtl);\n            UiTheme::switch(cx, super::super::ThemeMode::Dark);\n            assert_eq!(UiTheme::read(cx).direction, Direction::Rtl);\n            UiTheme::set(cx, UiTheme::neutral_light());\n            assert_eq!(direction(cx), Direction::Rtl);\n            assert_eq!(UiTheme::read(cx).direction, Direction::Rtl);\n        });\n    }\n}\n"
    },
    {
      "path": "registry/theme/primitives.rs",
      "type": "registry:file",
      "target": "~/src/ui/primitives.rs",
      "content": "//! Shared visual recipes between the theme tokens and the components.\n//!\n//! shadcn expresses these as Tailwind class strings; here each one is a function\n//! that applies the same styles to any GPUI element, so every component draws\n//! surfaces, controls, focus, text and images the same way, and a change to a\n//! recipe reaches the whole catalog. The registry lint fails components that\n//! rewrite one of these by hand. Everything takes `&UiTheme` so it works in\n//! `RenderOnce` and `Render` alike without re-reading the global.\n\nuse gpui_icons::{LucideIcon, lucide};\nuse gpui_kit::{\n    AnyElement, Axis, BoxShadow, Div, FontWeight, ImageSource, Img, InteractiveElement,\n    IntoElement, MouseButton, ObjectFit, ParentElement, Pixels, Rgba, SharedString,\n    StatefulInteractiveElement, StyleRefinement, Styled, StyledImage as _, Window, div, img, px,\n};\n\nuse super::{UiTextStyle, UiTheme};\n\n/// Text sizes from the type scale, each with its line height and the body font.\npub mod text {\n    use super::*;\n\n    /// Applies one step of the type scale and the body font.\n    pub fn style<T: Styled>(element: T, theme: &UiTheme, style: UiTextStyle) -> T {\n        let style = theme.text_style(style);\n        element\n            .font_family(theme.fonts.body.clone())\n            .text_size(style.size)\n            .line_height(style.line_height)\n    }\n    /// Captions, key caps and timestamps.\n    pub fn xs<T: Styled>(element: T, theme: &UiTheme) -> T {\n        style(element, theme, theme.typography.xs)\n    }\n    /// Controls and body copy; the Nova default.\n    pub fn sm<T: Styled>(element: T, theme: &UiTheme) -> T {\n        style(element, theme, theme.typography.sm)\n    }\n    /// Prose and dialog titles.\n    pub fn base<T: Styled>(element: T, theme: &UiTheme) -> T {\n        style(element, theme, theme.typography.base)\n    }\n    /// Section headings.\n    pub fn lg<T: Styled>(element: T, theme: &UiTheme) -> T {\n        style(element, theme, theme.typography.lg)\n    }\n    /// Page headings.\n    pub fn xl<T: Styled>(element: T, theme: &UiTheme) -> T {\n        style(element, theme, theme.typography.xl)\n    }\n    /// A medium-weight heading in the heading font at the given step.\n    pub fn heading<T: Styled>(element: T, theme: &UiTheme, size: UiTextStyle) -> T {\n        style(element, theme, size)\n            .font_family(theme.fonts.heading.clone())\n            .font_weight(FontWeight::MEDIUM)\n    }\n    /// Switches to the monospace font, keeping the current size.\n    pub fn mono<T: Styled>(element: T, theme: &UiTheme) -> T {\n        element.font_family(theme.fonts.mono.clone())\n    }\n    /// Muted supporting text at the small size.\n    pub fn muted<T: Styled>(element: T, theme: &UiTheme) -> T {\n        sm(element, theme).text_color(theme.colors.muted_foreground)\n    }\n\n    /// How tall a line box has to be, as a multiple of the font size, for\n    /// a glyph to fit inside it: Geist and IBM Plex Sans both reach 1.3em\n    /// from the top of an accent to the bottom of a g. A shorter box is fine\n    /// until something clips it; `truncate()` and `overflow_hidden()` clip\n    /// to the box and cut the bottoms off g, p and y.\n    pub const INK: f32 = 1.3;\n\n    /// The line height for text drawn at `size` (already scaled): the type\n    /// scale's own when `size` is one of its steps, otherwise 1.4 times the\n    /// size rounded up to a whole pixel. Never shorter than [`INK`].\n    pub fn line_height(theme: &UiTheme, size: Pixels) -> Pixels {\n        let t = &theme.typography;\n        [t.xs, t.sm, t.base, t.lg, t.xl]\n            .into_iter()\n            .map(|step| theme.text_style(step))\n            .find(|step| (step.size - size).abs() < px(0.01))\n            .map(|step| step.line_height)\n            .unwrap_or_else(|| px((f32::from(size) * 1.4).ceil()))\n            .max(size * INK)\n    }\n\n    /// Sets a control's text size and a line box its glyphs fit in.\n    ///\n    /// GPUI Kit's base `Button`, `Toggle` and `Tab` set\n    /// `line_height(relative(1.))`, a box exactly the font size, so a\n    /// truncated label inside one loses its descenders. Every gpuicn control\n    /// built on one of them sets its text here instead of `text_size`.\n    pub fn control<T: Styled>(element: T, theme: &UiTheme, size: Pixels) -> T {\n        element\n            .text_size(size)\n            .line_height(line_height(theme, size))\n    }\n}\n\n/// Icon sizes in spacing units, so icons scale with control density.\npub mod icon {\n    use super::*;\n\n    /// 12px: inside badges and tags.\n    pub fn xs(theme: &UiTheme) -> Pixels {\n        theme.space(3.)\n    }\n    /// 14px: inside small buttons and chips.\n    pub fn sm(theme: &UiTheme) -> Pixels {\n        theme.space(3.5)\n    }\n    /// 16px: the default inside controls and menu items.\n    pub fn md(theme: &UiTheme) -> Pixels {\n        theme.space(4.)\n    }\n    /// 20px: list leading icons.\n    pub fn lg(theme: &UiTheme) -> Pixels {\n        theme.space(5.)\n    }\n    /// 24px: empty states and headers.\n    pub fn xl(theme: &UiTheme) -> Pixels {\n        theme.space(6.)\n    }\n}\n\n/// Keyboard focus treatment: shadcn Nova's `ring-3 ring-ring/50` outside the\n/// border, with the border taking the ring color. Apply through\n/// `focus_visible` so pointer presses leave it alone.\npub mod focus {\n    use super::*;\n\n    /// The ring as a box shadow, for elements that draw their own border.\n    pub fn shadow(color: Rgba) -> Vec<BoxShadow> {\n        vec![BoxShadow::new(px(0.), px(0.), color.into()).spread_radius(px(3.))]\n    }\n    /// The focus ring for an ordinary control.\n    pub fn ring(style: StyleRefinement, theme: &UiTheme) -> StyleRefinement {\n        let control = theme.control();\n        style\n            .border_color(theme.colors.ring)\n            .shadow(shadow(control.ring))\n    }\n    /// The focus ring for an invalid control, in the destructive color.\n    pub fn invalid_ring(style: StyleRefinement, theme: &UiTheme) -> StyleRefinement {\n        let control = theme.control();\n        style\n            .border_color(theme.colors.destructive)\n            .shadow(shadow(control.invalid_ring))\n    }\n    /// Picks the valid or invalid ring.\n    pub fn ring_for(style: StyleRefinement, theme: &UiTheme, invalid: bool) -> StyleRefinement {\n        if invalid {\n            invalid_ring(style, theme)\n        } else {\n            ring(style, theme)\n        }\n    }\n    /// Draws the ring on `element` while `focused`, for controls whose focus is\n    /// tracked on a parent (a grouped checkbox or radio draws it on its box).\n    pub fn shown<T: Styled>(element: T, theme: &UiTheme, focused: bool) -> T {\n        shown_for(element, theme, focused, false)\n    }\n    /// [`shown`] with the invalid ring when `invalid`.\n    pub fn shown_for<T: Styled>(element: T, theme: &UiTheme, focused: bool, invalid: bool) -> T {\n        if focused {\n            super::super::apply_style(\n                element,\n                &ring_for(StyleRefinement::default(), theme, invalid),\n            )\n        } else {\n            element\n        }\n    }\n}\n\n/// Disabled and interactive cursor treatment.\npub mod disabled {\n    use super::*;\n\n    /// Nova's `disabled:opacity-50` plus the blocked cursor.\n    pub fn style<T: Styled>(element: T) -> T {\n        element.opacity(0.5).cursor_not_allowed()\n    }\n    /// A pointer cursor when enabled, the disabled treatment otherwise.\n    pub fn interactive<T: Styled>(element: T, disabled: bool) -> T {\n        if disabled {\n            style(element)\n        } else {\n            element.cursor_pointer()\n        }\n    }\n    /// Half opacity while `dimmed`, for content that is unavailable rather than\n    /// a control that is disabled: uploading pictures, disabled list rows.\n    pub fn dim<T: Styled>(element: T, dimmed: bool) -> T {\n        if dimmed {\n            element.opacity(0.5)\n        } else {\n            element\n        }\n    }\n}\n\n/// Elevated surfaces. One rule per kind, so every popover, menu, dialog, card\n/// and tooltip in the catalog shares border, radius, shadow and text defaults.\npub mod surface {\n    use super::*;\n\n    /// Starts text at the reading edge. Floating surfaces paint outside\n    /// their trigger's tree, so they cannot inherit the window's alignment.\n    fn reading_start<T: Styled>(element: T, theme: &UiTheme) -> T {\n        if theme.direction.is_rtl() {\n            element.text_align(gpui_kit::TextAlign::Right)\n        } else {\n            element\n        }\n    }\n    fn popover_base<T: Styled>(element: T, theme: &UiTheme) -> T {\n        reading_start(text::sm(element, theme), theme)\n            .border_1()\n            .border_color(theme.control().surface_border)\n            .bg(theme.colors.popover)\n            .text_color(theme.colors.popover_foreground)\n    }\n    /// Popovers, hover cards, select and combobox lists: `rounded-lg shadow-md`.\n    pub fn popover<T: Styled>(element: T, theme: &UiTheme) -> T {\n        popover_base(element, theme)\n            .rounded(theme.radius.lg)\n            .shadow(theme.shadows.md.to_vec())\n    }\n    /// Menus and context menus: a popover with Nova's 4px inset.\n    pub fn menu<T: Styled>(element: T, theme: &UiTheme) -> T {\n        popover(element, theme).p(theme.space(1.))\n    }\n    /// Dialogs and command palettes: `rounded-xl shadow-lg`.\n    pub fn modal<T: Styled>(element: T, theme: &UiTheme) -> T {\n        popover_base(element, theme)\n            .rounded(theme.radius.xl)\n            .shadow(theme.shadows.lg.to_vec())\n    }\n    /// A sheet or drawer panel: the modal surface without a radius, which the\n    /// caller rounds on the open edge.\n    pub fn sheet<T: Styled>(element: T, theme: &UiTheme) -> T {\n        popover_base(element, theme).border_color(theme.colors.border)\n    }\n    /// Toasts: `rounded-2xl` on the popover surface with the plain border.\n    pub fn toast<T: Styled>(element: T, theme: &UiTheme) -> T {\n        popover_base(element, theme)\n            .rounded(theme.radius.two_xl)\n            .border_color(theme.colors.border)\n            .shadow(theme.shadows.lg.to_vec())\n    }\n    /// Cards and empty states: `rounded-xl border shadow-sm` on the card color.\n    pub fn card<T: Styled>(element: T, theme: &UiTheme) -> T {\n        reading_start(text::sm(element, theme), theme)\n            .rounded(theme.radius.xl)\n            .border_1()\n            .border_color(theme.colors.border)\n            .bg(theme.colors.card)\n            .text_color(theme.colors.card_foreground)\n            .shadow(theme.shadows.sm.to_vec())\n    }\n    /// A floating action bar over content, as on a hovered message.\n    pub fn floating<T: Styled>(element: T, theme: &UiTheme) -> T {\n        element\n            .rounded(theme.radius.lg)\n            .border_1()\n            .border_color(theme.colors.border)\n            .bg(theme.colors.background)\n            .shadow(theme.shadows.sm.to_vec())\n    }\n    /// Tooltips: the popover surface (so they follow light and dark mode)\n    /// at the medium radius and caption size.\n    pub fn tooltip<T: Styled>(element: T, theme: &UiTheme) -> T {\n        reading_start(text::xs(element, theme), theme)\n            .rounded(theme.radius.md)\n            .px(theme.space(3.))\n            .py(theme.space(1.5))\n            .border_1()\n            .border_color(theme.control().surface_border)\n            .bg(theme.colors.popover)\n            .text_color(theme.colors.popover_foreground)\n            .shadow(theme.shadows.md.to_vec())\n    }\n    /// A one-pixel rule in the border color, across or down.\n    pub fn divider<T: Styled>(element: T, theme: &UiTheme, axis: Axis) -> T {\n        let element = match axis {\n            Axis::Horizontal => element.w_full().h(px(1.)),\n            Axis::Vertical => element.h_full().w(px(1.)),\n        };\n        element.bg(theme.colors.border)\n    }\n}\n\n/// Form control pieces shared by single controls and their grouped variants.\npub mod control {\n    use super::*;\n\n    /// Corner radius of a 16px check box: Nova's `rounded-[4px]` at the default radius.\n    pub fn box_radius(theme: &UiTheme) -> Pixels {\n        theme.radius.sm * (2. / 3.)\n    }\n\n    /// The frame every text-like control shares: inputs, textareas, selects,\n    /// number and OTP cells. Large radius, input border and fill, small text.\n    /// Callers set the size: `h(theme.space(8.))` and `px(theme.space(2.5))`\n    /// for a single-line control.\n    pub fn frame<T: Styled>(element: T, theme: &UiTheme, invalid: bool) -> T {\n        let control = theme.control();\n        text::sm(element, theme)\n            .rounded(theme.radius.lg)\n            .border_1()\n            .border_color(if invalid {\n                theme.colors.destructive\n            } else {\n                control.border\n            })\n            .bg(control.background)\n            .text_color(theme.colors.foreground)\n    }\n\n    /// Styles `element` as the 16px check box with its mark, for checkboxes and\n    /// grouped checkboxes. The element is the interactive root of the control.\n    pub fn checkbox_box<T: Styled + ParentElement>(\n        element: T,\n        theme: &UiTheme,\n        checked: bool,\n        indeterminate: bool,\n    ) -> T {\n        let colors = theme.colors;\n        let control = theme.control();\n        let selected = checked || indeterminate;\n        let element = element\n            .flex()\n            .flex_shrink_0()\n            .items_center()\n            .justify_center()\n            .size(theme.space(4.))\n            .rounded(box_radius(theme))\n            .border_1()\n            .border_color(if selected {\n                colors.primary\n            } else {\n                control.border\n            })\n            .bg(if selected {\n                colors.primary\n            } else {\n                control.background\n            });\n        if selected {\n            element.child(\n                lucide(if indeterminate {\n                    LucideIcon::Minus\n                } else {\n                    LucideIcon::Check\n                })\n                .size(icon::sm(theme))\n                .text_color(colors.primary_foreground),\n            )\n        } else {\n            element\n        }\n    }\n\n    /// Styles `element` as the 16px radio circle with its dot.\n    pub fn radio_dot<T: Styled + ParentElement>(element: T, theme: &UiTheme, checked: bool) -> T {\n        let colors = theme.colors;\n        let control = theme.control();\n        let element = element\n            .flex()\n            .flex_shrink_0()\n            .items_center()\n            .justify_center()\n            .size(theme.space(4.))\n            .rounded_full()\n            .border_1()\n            .border_color(if checked {\n                colors.primary\n            } else {\n                control.border\n            })\n            .bg(if checked {\n                colors.primary\n            } else {\n                control.background\n            });\n        if checked {\n            element.child(\n                div()\n                    .size(theme.space(2.))\n                    .rounded_full()\n                    .bg(colors.primary_foreground),\n            )\n        } else {\n            element\n        }\n    }\n\n    /// The toggle look shared by Toggle and Toggle Group items: transparent at\n    /// rest, muted when hovered or pressed, an input border when outlined.\n    pub fn toggle<T: Styled>(\n        element: T,\n        theme: &UiTheme,\n        pressed: bool,\n        disabled: bool,\n        outline: bool,\n    ) -> T {\n        let colors = theme.colors;\n        let control = theme.control();\n        let element = text::sm(element, theme)\n            .border_1()\n            .border_color(if outline {\n                control.border\n            } else {\n                colors.background.opacity(0.)\n            })\n            .text_color(colors.foreground)\n            .bg(if pressed {\n                control.pressed\n            } else {\n                colors.background.opacity(0.)\n            });\n        disabled::interactive(element, disabled)\n    }\n}\n\n/// The switch track and thumb colors for a checked or unchecked switch.\npub fn switch_colors(theme: &UiTheme, checked: bool) -> (Rgba, Rgba) {\n    let control = theme.control();\n    if checked {\n        (theme.colors.primary, control.thumb_checked)\n    } else {\n        (control.track, control.thumb)\n    }\n}\n\n/// A GPUI `img` that plays animated GIFs and WebPs.\n///\n/// GPUI only advances an image's frames when the element has an id, so this\n/// names the picture after its source: two pictures of the same file share a\n/// frame clock, and a new source starts from the first frame. Animation stops\n/// while [`App::reduce_motion`](gpui_kit::App) is on, as for any `img`. Use it\n/// wherever a component draws a caller's picture.\npub fn image(source: impl Into<ImageSource>) -> Img {\n    let source = source.into();\n    let id = image_id(&source);\n    let mut image = img(source);\n    image.interactivity().element_id = Some(id);\n    image\n}\n\n/// The element id [`image`] gives a picture of `source`.\npub fn image_id(source: &ImageSource) -> gpui_kit::ElementId {\n    use std::hash::{Hash as _, Hasher as _};\n    let mut hasher = std::collections::hash_map::DefaultHasher::new();\n    match source {\n        ImageSource::Resource(resource) => resource.hash(&mut hasher),\n        ImageSource::Render(render) => (1u8, render.id.0).hash(&mut hasher),\n        ImageSource::Image(image) => (2u8, image.id).hash(&mut hasher),\n        ImageSource::Custom(load) => {\n            (3u8, std::sync::Arc::as_ptr(load) as *const () as usize).hash(&mut hasher)\n        }\n    }\n    gpui_kit::ElementId::NamedInteger(\"gpuicn-image\".into(), hasher.finish())\n}\n\n/// An image inside a rounded frame. GPUI clips children to rectangles, so the\n/// frame rounds itself and the image rounds to the frame's inner radius; the\n/// image fills the frame's box and never sizes the frame from its aspect ratio.\n/// Animated pictures play, through [`image`].\npub fn clipped_image(\n    source: impl Into<ImageSource>,\n    radius: Pixels,\n    fit: ObjectFit,\n    theme: &UiTheme,\n) -> Div {\n    clipped_image_with(source, radius, fit, theme, |image| image)\n}\n\n/// [`clipped_image`] with access to the picture, for loading and fallback views.\npub fn clipped_image_with(\n    source: impl Into<ImageSource>,\n    radius: Pixels,\n    fit: ObjectFit,\n    theme: &UiTheme,\n    configure: impl FnOnce(Img) -> Img,\n) -> Div {\n    div()\n        .relative()\n        .flex_shrink_0()\n        .overflow_hidden()\n        .rounded(radius)\n        .bg(theme.colors.muted)\n        .child(configure(\n            image(source)\n                .absolute()\n                .inset_0()\n                .size_full()\n                .rounded(radius)\n                .object_fit(fit),\n        ))\n}\n\n/// A circular image, as in avatars.\npub fn round_image(source: impl Into<ImageSource>, size: Pixels, theme: &UiTheme) -> Div {\n    clipped_image(source, size / 2., ObjectFit::Cover, theme).size(size)\n}\n\n/// Dismisses an overlay from a press outside it or the Escape key.\npub mod dismiss {\n    use super::*;\n\n    /// Runs `handler` when Escape is pressed while focus is inside `element`.\n    /// `handler` returns whether it handled the key; when it did not, Escape\n    /// goes on to the overlay or shortcut around it.\n    ///\n    /// Escape arrives as the `Dismiss` action in its own key context, so it\n    /// wins over an application's Escape binding (bindings run before key\n    /// listeners, and a deeper context wins). The element takes that key\n    /// context, so don't use this on an element with a key context of its\n    /// own.\n    pub fn on_escape<E: InteractiveElement>(\n        element: E,\n        handler: impl Fn(&mut Window, &mut gpui_kit::App) -> bool + 'static,\n    ) -> E {\n        element\n            .key_context(super::super::DISMISS_CONTEXT)\n            .on_action(move |_: &super::super::Dismiss, window, cx| {\n                if !handler(window, cx) {\n                    cx.propagate();\n                }\n            })\n    }\n\n    /// Runs `handler` when the pointer presses outside `element` or Escape is\n    /// pressed while focus is inside it.\n    pub fn on_outside<E: StatefulInteractiveElement>(\n        element: E,\n        handler: impl Fn(&mut Window, &mut gpui_kit::App) + 'static,\n    ) -> E {\n        let handler = std::rc::Rc::new(handler);\n        let on_press = handler.clone();\n        on_escape(\n            element.on_mouse_down_out(move |event, window, cx| {\n                if event.button == MouseButton::Left {\n                    on_press(window, cx)\n                }\n            }),\n            move |window, cx| {\n                handler(window, cx);\n                true\n            },\n        )\n    }\n}\n\n/// Hover-revealed content that never changes layout: the element keeps its\n/// size and only its opacity follows `visible`.\npub fn hover_reveal<T: Styled>(element: T, visible: bool) -> T {\n    element.opacity(if visible { 1. } else { 0. })\n}\n\n/// Content shown while the pointer is over the enclosing `.group(name)`\n/// element, with no state and no re-render: opacity 0 at rest, 1 on hover.\n/// Pass `pinned` to keep it visible, as for a selected row's actions.\npub fn hover_reveal_in_group<T: Styled + InteractiveElement>(\n    element: T,\n    group: impl Into<SharedString>,\n    pinned: bool,\n) -> T {\n    if pinned {\n        element\n    } else {\n        element\n            .opacity(0.)\n            .group_hover(group, |style| style.opacity(1.))\n    }\n}\n\n/// Erases an element's type after styling, for callers that store children.\npub fn erase(element: impl IntoElement) -> AnyElement {\n    element.into_any_element()\n}\n\n/// A press that belongs to a control. GPUI runs a parent's click handler\n/// after its child's unless the child stops propagation, and the window's\n/// text selection starts from any press; a control that claims its press\n/// keeps both from happening, so a click on a button inside a clickable row\n/// is the button's alone and pressing it never starts a selection.\npub mod press {\n    use gpui_kit::{App, InteractiveElement, MouseButton, base::GlobalState};\n\n    /// Claims every left press on `element` for it.\n    pub fn claim<T: InteractiveElement>(element: T) -> T {\n        element.on_mouse_down(MouseButton::Left, |_, _, cx| claim_now(cx))\n    }\n\n    /// Claims the current press, from inside a mouse-down handler.\n    pub fn claim_now(cx: &mut App) {\n        GlobalState::init(cx);\n        GlobalState::suppress_text_selection(cx);\n    }\n\n    /// Whether a control claimed the current press. A clickable container\n    /// checks this in its click handler and leaves the click to the control.\n    pub fn claimed(cx: &App) -> bool {\n        cx.has_global::<GlobalState>() && GlobalState::is_text_selection_suppressed(cx)\n    }\n\n    /// Forgets the last press's claim. Call it in the capture phase of a\n    /// container's mouse down, so a claim never outlives its press in a\n    /// window without a selection root (which does this itself).\n    pub fn reset(cx: &mut App) {\n        if cx.has_global::<GlobalState>() {\n            GlobalState::reset_text_selection_suppression(cx);\n        }\n    }\n}\n"
    },
    {
      "path": "registry/theme/theme.rs",
      "type": "registry:file",
      "target": "~/src/ui/theme.rs",
      "content": "//! The app-owned shadcn Neutral theme for gpuicn.\n//!\n//! Source: shadcn/ui 4.19.0 at\n//! `1773ecfeeb4a04366978d353e69b5c7ded78dcb2`, Nova style.\n\nuse std::{sync::Arc, time::Duration};\n\nuse gpui_kit::{\n    App, BoxShadow, ElementId, Global, Pixels, Rgba, SharedString, Styled, Subscription, Window,\n    WindowAppearance, black, px,\n};\n\n#[path = \"locale.rs\"]\npub mod locale;\n#[path = \"primitives.rs\"]\npub mod primitives;\n\npub use locale::{Direction, UiText};\n\ngpui_kit::actions!(\n    gpuicn,\n    [\n        /// Move to the next keyboard tab stop.\n        FocusNext,\n        /// Move to the previous keyboard tab stop.\n        FocusPrevious,\n        /// Close the innermost dismissable overlay (Escape).\n        Dismiss\n    ]\n);\n\nstruct Initialized;\nimpl Global for Initialized {}\n\n/// The key context of an overlay that closes on Escape: dialogs, popovers\n/// and the lightbox. Its Escape binding is deeper than any application\n/// context around the overlay, so an app's own Escape shortcut (such as\n/// \"mark read\") never swallows the key while an overlay has focus.\npub const DISMISS_CONTEXT: &str = \"GpuicnDismiss\";\n\n/// The key context of a one-time-code field, which binds the paste shortcut.\n#[doc(hidden)]\npub const OTP_CONTEXT: &str = \"GpuicnOtp\";\n\n/// Installs component actions, keyboard traversal and the default theme once.\n/// Call this from application startup for both copied source and crate usage.\npub fn init(cx: &mut App) {\n    if cx.has_global::<Initialized>() {\n        return;\n    }\n    seed_component_fonts(cx);\n    gpui_kit::init(cx);\n    cx.set_global(Initialized);\n    if !cx.has_global::<UiTheme>() {\n        UiTheme::set(cx, UiTheme::neutral_light());\n    } else {\n        let theme = UiTheme::read(cx).clone();\n        sync_component_theme(cx, theme);\n    }\n    cx.bind_keys([\n        gpui_kit::KeyBinding::new(\"tab\", FocusNext, None),\n        gpui_kit::KeyBinding::new(\"shift-tab\", FocusPrevious, None),\n        gpui_kit::KeyBinding::new(\"escape\", Dismiss, Some(DISMISS_CONTEXT)),\n    ]);\n    locale::bind_keys(cx);\n    {\n        use gpui_kit::{KeyBinding, base::input::Paste};\n        let context = Some(OTP_CONTEXT);\n        #[cfg(any(target_os = \"macos\", target_family = \"wasm\"))]\n        cx.bind_keys([KeyBinding::new(\"cmd-v\", Paste, context)]);\n        #[cfg(not(target_os = \"macos\"))]\n        cx.bind_keys([KeyBinding::new(\"ctrl-v\", Paste, context)]);\n    }\n    cx.on_action(|_: &FocusNext, cx| advance_focus(false, cx));\n    cx.on_action(|_: &FocusPrevious, cx| advance_focus(true, cx));\n    // Scoped component bindings take precedence over these window-wide defaults.\n    #[cfg(target_family = \"wasm\")]\n    {\n        // Browser previews also accept macOS editing shortcuts.\n        use gpui_kit::KeyBinding;\n        use gpui_kit::base::input::{\n            Copy, Cut, MoveEnd, MoveHome, MoveToNextWord, MoveToPreviousWord, Paste, Redo,\n            SelectAll, SelectToNextWordEnd, SelectToPreviousWordStart, Undo,\n        };\n        cx.bind_keys([\n            KeyBinding::new(\"cmd-a\", SelectAll, Some(\"Input\")),\n            KeyBinding::new(\"cmd-c\", Copy, Some(\"Input\")),\n            KeyBinding::new(\"cmd-v\", Paste, Some(\"Input\")),\n            KeyBinding::new(\"cmd-x\", Cut, Some(\"Input\")),\n            KeyBinding::new(\"cmd-left\", MoveHome, Some(\"Input\")),\n            KeyBinding::new(\"cmd-right\", MoveEnd, Some(\"Input\")),\n            KeyBinding::new(\"cmd-z\", Undo, Some(\"Input\")),\n            KeyBinding::new(\"cmd-shift-z\", Redo, Some(\"Input\")),\n            KeyBinding::new(\"alt-left\", MoveToPreviousWord, Some(\"Input\")),\n            KeyBinding::new(\"alt-right\", MoveToNextWord, Some(\"Input\")),\n            KeyBinding::new(\"alt-shift-left\", SelectToPreviousWordStart, Some(\"Input\")),\n            KeyBinding::new(\"alt-shift-right\", SelectToNextWordEnd, Some(\"Input\")),\n        ]);\n    }\n}\n\nfn seed_component_fonts(cx: &mut App) {\n    use gpui_kit::component::Theme;\n\n    if cx.has_global::<Theme>() {\n        return;\n    }\n    let fonts = if cx.has_global::<UiTheme>() {\n        UiTheme::read(cx).fonts.clone()\n    } else {\n        UiTheme::neutral_light().fonts\n    };\n    let mut component = Theme::default();\n    component.font_family = fonts.body;\n    component.mono_font_family = fonts.mono;\n    cx.set_global(component);\n}\n\nfn advance_focus(reverse: bool, cx: &mut App) {\n    let Some(handle) = cx.active_window() else {\n        return;\n    };\n    // Action dispatch still holds the window borrow until this callback returns.\n    cx.defer(move |cx| {\n        let _ = handle.update(cx, |_, window, cx| {\n            if reverse {\n                window.focus_prev(cx);\n            } else {\n                window.focus_next(cx);\n            }\n        });\n    });\n}\n\n/// The active color mode.\n#[derive(Clone, Copy, Debug, Eq, PartialEq)]\npub enum ThemeMode {\n    /// The Neutral light palette.\n    Light,\n    /// The Neutral dark palette.\n    Dark,\n}\n\n/// Which of an application's two palettes is shown.\n#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]\npub enum Appearance {\n    /// Always the light palette.\n    Light,\n    /// Always the dark palette.\n    Dark,\n    /// The palette matching the operating system's window appearance.\n    #[default]\n    System,\n}\n\nimpl Appearance {\n    /// The mode this appearance shows under the given system appearance.\n    pub fn resolve(self, system: WindowAppearance) -> ThemeMode {\n        match self {\n            Appearance::Light => ThemeMode::Light,\n            Appearance::Dark => ThemeMode::Dark,\n            Appearance::System => match system {\n                WindowAppearance::Dark | WindowAppearance::VibrantDark => ThemeMode::Dark,\n                WindowAppearance::Light | WindowAppearance::VibrantLight => ThemeMode::Light,\n            },\n        }\n    }\n}\n\n/// The application's light and dark themes and which one it shows.\n#[derive(Clone)]\nstruct ThemePair {\n    light: UiTheme,\n    dark: UiTheme,\n    appearance: Appearance,\n}\nimpl Global for ThemePair {}\n\n/// Swaps palettes when the operating system's appearance changes while the\n/// application follows it. Call it for each window the application opens and\n/// keep the subscription; `app::run` does this for the first window.\npub fn follow_system(window: &mut Window, cx: &mut App) -> Subscription {\n    UiTheme::apply_appearance(cx);\n    window.observe_window_appearance(|_, cx| UiTheme::apply_appearance(cx))\n}\n\n/// Semantic colors consumed by installed components.\n#[derive(Clone, Copy, Debug, PartialEq)]\npub struct UiColors {\n    /// App background.\n    pub background: Rgba,\n    /// Default foreground.\n    pub foreground: Rgba,\n    /// Card background.\n    pub card: Rgba,\n    /// Card foreground.\n    pub card_foreground: Rgba,\n    /// Popover background.\n    pub popover: Rgba,\n    /// Popover foreground.\n    pub popover_foreground: Rgba,\n    /// Primary control background.\n    pub primary: Rgba,\n    /// Primary control foreground.\n    pub primary_foreground: Rgba,\n    /// Secondary control background.\n    pub secondary: Rgba,\n    /// Secondary control foreground.\n    pub secondary_foreground: Rgba,\n    /// Muted background.\n    pub muted: Rgba,\n    /// Muted foreground.\n    pub muted_foreground: Rgba,\n    /// Accent background.\n    pub accent: Rgba,\n    /// Accent foreground.\n    pub accent_foreground: Rgba,\n    /// Destructive action color.\n    pub destructive: Rgba,\n    /// Text on a solid `destructive` surface.\n    pub destructive_foreground: Rgba,\n    /// Positive status, such as a completed upload or an online presence dot.\n    pub success: Rgba,\n    /// Text on a `success` fill.\n    pub success_foreground: Rgba,\n    /// Cautionary status, such as a permalink highlight or a pending state.\n    pub warning: Rgba,\n    /// Text on a `warning` fill.\n    pub warning_foreground: Rgba,\n    /// Informational status.\n    pub info: Rgba,\n    /// Text on an `info` fill.\n    pub info_foreground: Rgba,\n    /// Default border.\n    pub border: Rgba,\n    /// Input border.\n    pub input: Rgba,\n    /// Focus ring.\n    pub ring: Rgba,\n    /// First chart color.\n    pub chart_1: Rgba,\n    /// Second chart color.\n    pub chart_2: Rgba,\n    /// Third chart color.\n    pub chart_3: Rgba,\n    /// Fourth chart color.\n    pub chart_4: Rgba,\n    /// Fifth chart color.\n    pub chart_5: Rgba,\n    /// Sidebar background.\n    pub sidebar: Rgba,\n    /// Sidebar foreground.\n    pub sidebar_foreground: Rgba,\n    /// Sidebar primary background.\n    pub sidebar_primary: Rgba,\n    /// Sidebar primary foreground.\n    pub sidebar_primary_foreground: Rgba,\n    /// Sidebar accent background.\n    pub sidebar_accent: Rgba,\n    /// Sidebar accent foreground.\n    pub sidebar_accent_foreground: Rgba,\n    /// Sidebar border.\n    pub sidebar_border: Rgba,\n    /// Sidebar focus border color.\n    pub sidebar_ring: Rgba,\n    /// Scrim behind modal surfaces.\n    pub overlay: Rgba,\n    /// Markdown link text. `None` follows `primary`; read it with `link()`.\n    pub link: Option<Rgba>,\n    /// Fill behind a mention of the reader, and the tint of a mention row.\n    /// `None` follows `primary`; read it with `mention_highlight()`.\n    pub mention_highlight: Option<Rgba>,\n    /// Text on `mention_highlight`. `None` follows `primary_foreground`.\n    pub mention_highlight_foreground: Option<Rgba>,\n    /// The rule and label marking where new messages start. `None` follows\n    /// `destructive`; read it with `new_messages()`.\n    pub new_messages: Option<Rgba>,\n    /// Quiet sidebar text: read rows, icons and section labels. `None`\n    /// follows `sidebar_foreground` at 70%.\n    pub sidebar_muted_foreground: Option<Rgba>,\n    /// Sidebar mention badges. `None` follows `sidebar_primary`.\n    pub sidebar_badge: Option<Rgba>,\n    /// Text on `sidebar_badge`. `None` follows `sidebar_primary_foreground`.\n    pub sidebar_badge_foreground: Option<Rgba>,\n}\n\nimpl UiColors {\n    /// Markdown link text: `link`, or `primary`.\n    pub fn link(&self) -> Rgba {\n        self.link.unwrap_or(self.primary)\n    }\n    /// Mention fill: `mention_highlight`, or `primary`.\n    pub fn mention_highlight(&self) -> Rgba {\n        self.mention_highlight.unwrap_or(self.primary)\n    }\n    /// Text on the mention fill: `mention_highlight_foreground`, or `primary_foreground`.\n    pub fn mention_highlight_foreground(&self) -> Rgba {\n        self.mention_highlight_foreground\n            .unwrap_or(self.primary_foreground)\n    }\n    /// The new-messages rule: `new_messages`, or `destructive`.\n    pub fn new_messages(&self) -> Rgba {\n        self.new_messages.unwrap_or(self.destructive)\n    }\n    /// Quiet sidebar text: `sidebar_muted_foreground`, or `sidebar_foreground` at 70%.\n    pub fn sidebar_muted_foreground(&self) -> Rgba {\n        self.sidebar_muted_foreground\n            .unwrap_or(self.sidebar_foreground.opacity(0.7))\n    }\n    /// Sidebar mention badge fill: `sidebar_badge`, or `sidebar_primary`.\n    pub fn sidebar_badge(&self) -> Rgba {\n        self.sidebar_badge.unwrap_or(self.sidebar_primary)\n    }\n    /// Text on a sidebar mention badge: `sidebar_badge_foreground`, or\n    /// `sidebar_primary_foreground`.\n    pub fn sidebar_badge_foreground(&self) -> Rgba {\n        self.sidebar_badge_foreground\n            .unwrap_or(self.sidebar_primary_foreground)\n    }\n}\n\n/// Theme font family names. Applications own font loading.\n#[derive(Clone, Debug, PartialEq)]\npub struct UiFonts {\n    /// Default body family.\n    pub body: SharedString,\n    /// Default heading family.\n    pub heading: SharedString,\n    /// Default monospace family.\n    pub mono: SharedString,\n}\n\n/// Corner radii derived from shadcn's 10px base radius.\n#[derive(Clone, Copy, Debug, PartialEq)]\npub struct UiRadius {\n    /// Backward-compatible alias for [`Self::lg`].\n    pub base: Pixels,\n    /// Six pixels (`radius * 0.6`).\n    pub sm: Pixels,\n    /// Eight pixels (`radius * 0.8`).\n    pub md: Pixels,\n    /// Ten pixels (the configured base radius).\n    pub lg: Pixels,\n    /// Fourteen pixels (`radius * 1.4`).\n    pub xl: Pixels,\n    /// Eighteen pixels (`radius * 1.8`).\n    pub two_xl: Pixels,\n    /// Twenty-two pixels (`radius * 2.2`).\n    pub three_xl: Pixels,\n    /// Twenty-six pixels (`radius * 2.6`).\n    pub four_xl: Pixels,\n}\n\nimpl UiRadius {\n    /// Derives the complete Nova radius scale from one nonnegative base radius.\n    pub fn new(base: Pixels) -> Self {\n        assert!(f32::from(base).is_finite() && base >= px(0.));\n        Self {\n            base,\n            sm: base * 0.6,\n            md: base * 0.8,\n            lg: base,\n            xl: base * 1.4,\n            two_xl: base * 1.8,\n            three_xl: base * 2.2,\n            four_xl: base * 2.6,\n        }\n    }\n}\n\n/// Shared UI transition durations. Honor these alongside `App::reduce_motion()`.\n#[derive(Clone, Copy, Debug, PartialEq)]\npub struct UiMotion {\n    /// Thumb and small-state transitions (150ms by default).\n    pub fast: Duration,\n    /// Panel/layout transitions (200ms by default).\n    pub normal: Duration,\n    /// Application preference; true removes movement without removing state feedback.\n    pub reduced: bool,\n    /// Shared easing for reversible state transitions.\n    pub easing: UiEasing,\n}\nimpl Default for UiMotion {\n    fn default() -> Self {\n        Self {\n            fast: Duration::from_millis(150),\n            normal: Duration::from_millis(200),\n            reduced: false,\n            easing: UiEasing::EaseInOut,\n        }\n    }\n}\n\n/// Curves supported by the shared native transition helper.\n#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]\npub enum UiEasing {\n    /// Constant-speed motion, as used by shadcn sidebar layout transitions.\n    Linear,\n    /// Fast response followed by a smooth stop.\n    EaseOut,\n    /// Smooth acceleration and deceleration for changes within a layout.\n    #[default]\n    EaseInOut,\n    /// Quick start and a long settle (`cubic-bezier(0.22, 1, 0.36, 1)`), for\n    /// surfaces that slide in from an edge, such as drawers and sheets.\n    Emphasized,\n}\nimpl UiEasing {\n    fn sample(self, progress: f32) -> f32 {\n        match self {\n            Self::Linear => progress,\n            Self::EaseOut => gpui_kit::ease_out_quint()(progress),\n            Self::EaseInOut => gpui_kit::ease_in_out(progress),\n            Self::Emphasized => gpui_kit::base::motion::Easing::CubicBezier {\n                x1: 0.22,\n                y1: 1.,\n                x2: 0.36,\n                y2: 1.,\n            }\n            .sample(progress),\n        }\n    }\n}\n\n/// Steps per second of a looping indicator, such as a spinner or a skeleton's pulse.\n/// A loop drawn every frame redraws its view 60 or 120 times a second for as long\n/// as it shows, which can be minutes for a connection banner; a dozen steps read\n/// as the same motion.\npub const LOOP_STEPS_PER_SECOND: u32 = 12;\n\n/// Where a looping indicator is in its cycle of `period`, from 0 to 1. The value\n/// moves in [`LOOP_STEPS_PER_SECOND`] steps on one clock shared by every loop, and\n/// the view that draws it is asked to redraw once at the next step, however many\n/// loops it holds, and only while its window is active: a loop in a background\n/// window costs nothing until the window comes forward (activation redraws it).\npub fn loop_phase(period: Duration, window: &mut Window, cx: &mut App) -> f32 {\n    thread_local! {\n        static EPOCH: std::cell::OnceCell<web_time::Instant> = const { std::cell::OnceCell::new() };\n        static WAITING: std::cell::RefCell<std::collections::HashSet<gpui_kit::EntityId>> =\n            Default::default();\n    }\n    let step = Duration::from_secs(1) / LOOP_STEPS_PER_SECOND;\n    // The executor's clock, so the steps follow simulated time in tests.\n    let now = cx.background_executor().now();\n    let elapsed = EPOCH.with(|epoch| now.duration_since(*epoch.get_or_init(|| now)));\n    let steps = (period.as_secs_f64() / step.as_secs_f64()).round().max(1.);\n    let at = (elapsed.as_secs_f64() / step.as_secs_f64()).floor();\n    let phase = ((at % steps) / steps) as f32;\n    let view = window.current_view();\n    if window.is_window_active() && WAITING.with(|waiting| waiting.borrow_mut().insert(view)) {\n        let next = step.mul_f64(at + 1.);\n        let wait = next.saturating_sub(elapsed);\n        cx.spawn(async move |cx| {\n            cx.background_executor().timer(wait).await;\n            WAITING.with(|waiting| waiting.borrow_mut().remove(&view));\n            cx.update(|cx| cx.notify(view));\n        })\n        .detach();\n    }\n    phase\n}\n\n/// Returns a smoothly retargetable value for one stable, caller-named property.\n/// Starts at the target on mount; rapid reversals continue from the current value.\n/// Honors theme and GPUI reduced-motion settings and schedules no idle frames.\n/// Use for state changes, never for pointer-drag coordinates or keyboard navigation.\n/// Native layout transitions perform layout work; retain expensive child entities.\npub fn transition_value(\n    id: impl Into<ElementId>,\n    target: f32,\n    duration: Duration,\n    window: &mut Window,\n    cx: &mut App,\n) -> f32 {\n    let easing = UiTheme::read(cx).motion.easing;\n    transition_with(id, target, duration, easing, window, cx)\n}\n\n/// [`transition_value`] with an explicit curve, for the few surfaces whose motion\n/// differs from the theme default (drawers slide with [`UiEasing::Emphasized`]).\npub fn transition_with(\n    id: impl Into<ElementId>,\n    target: f32,\n    duration: Duration,\n    easing: UiEasing,\n    window: &mut Window,\n    cx: &mut App,\n) -> f32 {\n    assert!(target.is_finite(), \"transition targets must be finite\");\n    gpui_kit::base::motion::transition(\n        id.into(),\n        target,\n        motion_policy(duration, easing, cx),\n        window,\n        cx,\n    )\n}\n\n/// Shares the theme's disclosure and notification timing with Kit's presence lifecycle.\n/// Returns a sample whose `progress` runs 0→1 while entering and 1→0 while leaving, so\n/// a surface fades or scales with it; `should_render()` keeps the element mounted\n/// until the exit transition has finished.\n#[doc(hidden)]\npub fn presence(\n    id: impl Into<ElementId>,\n    present: bool,\n    window: &mut Window,\n    cx: &mut App,\n) -> gpui_kit::base::motion::PresenceSample {\n    let motion = UiTheme::read(cx).motion;\n    presence_with(id, present, motion.fast, motion.easing, window, cx)\n}\n\n/// [`presence`] with explicit timing and curve, for panels that take the theme's\n/// `normal` duration or a different easing.\n#[doc(hidden)]\npub fn presence_with(\n    id: impl Into<ElementId>,\n    present: bool,\n    duration: Duration,\n    easing: UiEasing,\n    window: &mut Window,\n    cx: &mut App,\n) -> gpui_kit::base::motion::PresenceSample {\n    gpui_kit::base::motion::Presence::new(id.into(), present)\n        .transition(motion_policy(duration, easing, cx))\n        .sample(window, cx)\n}\n\n/// The one place motion honors the theme and platform reduced-motion settings.\nfn motion_policy(\n    duration: Duration,\n    easing: UiEasing,\n    cx: &App,\n) -> gpui_kit::base::motion::Transition {\n    let duration = if UiTheme::read(cx).motion.reduced || cx.reduce_motion() {\n        Duration::ZERO\n    } else {\n        duration\n    };\n    gpui_kit::base::motion::Transition::new(duration).ease(move |progress| easing.sample(progress))\n}\n\n/// Shared shadcn elevation tokens. Each level is shared, so cloning a theme\n/// every render costs no allocation; `to_vec()` the level you apply.\n#[derive(Clone, Debug, PartialEq)]\npub struct UiShadows {\n    /// Tailwind `shadow-sm`.\n    pub sm: Arc<[BoxShadow]>,\n    /// Tailwind `shadow-md`.\n    pub md: Arc<[BoxShadow]>,\n    /// Tailwind `shadow-lg`.\n    pub lg: Arc<[BoxShadow]>,\n}\n\n/// One step of the type scale: a text size and the line height that goes with it.\n#[derive(Clone, Copy, Debug, PartialEq)]\npub struct UiTextStyle {\n    /// Font size before `text_scale`.\n    pub size: Pixels,\n    /// Line height before `text_scale`.\n    pub line_height: Pixels,\n}\n\n/// The type scale, Tailwind's by default. Components read sizes from here through\n/// `primitives::text`, so `text_scale` and a custom scale reach every label.\n#[derive(Clone, Copy, Debug, PartialEq)]\npub struct UiTypography {\n    /// Captions and key caps (12/16).\n    pub xs: UiTextStyle,\n    /// Controls and body copy in dense desktop layouts (14/20); the Nova default.\n    pub sm: UiTextStyle,\n    /// Prose and dialog titles (16/24).\n    pub base: UiTextStyle,\n    /// Section headings (18/28).\n    pub lg: UiTextStyle,\n    /// Page headings (20/28).\n    pub xl: UiTextStyle,\n}\n\nimpl Default for UiTypography {\n    fn default() -> Self {\n        let style = |size: f32, line_height: f32| UiTextStyle {\n            size: px(size),\n            line_height: px(line_height),\n        };\n        Self {\n            xs: style(12., 16.),\n            sm: style(14., 20.),\n            base: style(16., 24.),\n            lg: style(18., 28.),\n            xl: style(20., 28.),\n        }\n    }\n}\n\n/// Window widths at which layouts change shape.\n#[derive(Clone, Copy, Debug, PartialEq)]\npub struct UiBreakpoints {\n    /// Below this width, sidebars become sheets and drawers fill the window (768px).\n    pub mobile: Pixels,\n    /// Below this width, side drawers take three quarters of the window (640px).\n    pub compact: Pixels,\n}\n\nimpl Default for UiBreakpoints {\n    fn default() -> Self {\n        Self {\n            mobile: px(768.),\n            compact: px(640.),\n        }\n    }\n}\n\n/// Colors every form control shares, derived once from the palette and mode so\n/// no component chooses its own dark-mode alpha. These follow shadcn Nova's\n/// `dark:bg-input/30`, `dark:hover:bg-input/50` and `dark:border-input` rules.\n#[derive(Clone, Copy, Debug, PartialEq)]\npub struct ControlColors {\n    /// Resting fill of inputs, checkboxes, radios and outline buttons.\n    pub background: Rgba,\n    /// Resting border of the same controls.\n    pub border: Rgba,\n    /// Hover fill of outline, ghost and toggle controls.\n    pub hover: Rgba,\n    /// Hover fill of ghost buttons and plain icon buttons.\n    pub ghost_hover: Rgba,\n    /// Fill of a pressed toggle or selected tab.\n    pub pressed: Rgba,\n    /// Fill of the pressed option of a segmented toggle group, raised on\n    /// the group's muted track.\n    pub segment: Rgba,\n    /// Unchecked switch track.\n    pub track: Rgba,\n    /// Switch thumb on the unchecked track.\n    pub thumb: Rgba,\n    /// Switch thumb on the checked (`primary`) track.\n    pub thumb_checked: Rgba,\n    /// Tinted destructive fill, for destructive buttons, badges and tags.\n    pub destructive_background: Rgba,\n    /// Hover of the tinted destructive fill.\n    pub destructive_hover: Rgba,\n    /// Hairline around tinted destructive chips.\n    pub destructive_border: Rgba,\n    /// Focus ring color at Nova's 50% opacity.\n    pub ring: Rgba,\n    /// Focus ring of an invalid control.\n    pub invalid_ring: Rgba,\n    /// Hairline around popovers and dialogs (`ring-foreground/10`).\n    pub surface_border: Rgba,\n}\n\n/// Base spacing unit from the pinned Nova style.\n#[derive(Clone, Copy, Debug, PartialEq)]\npub struct UiSpacing {\n    /// Four pixels.\n    pub unit: Pixels,\n}\n\n/// The application-owned theme stored in GPUI global state.\n#[derive(Clone, Debug, PartialEq)]\npub struct UiTheme {\n    /// Active color mode.\n    pub mode: ThemeMode,\n    /// Active semantic colors.\n    pub colors: UiColors,\n    /// Font family names.\n    pub fonts: UiFonts,\n    /// Base corner radius.\n    pub radius: UiRadius,\n    /// Base spacing unit.\n    pub spacing: UiSpacing,\n    /// Shared elevation tokens.\n    pub shadows: UiShadows,\n    /// Shared motion durations and reduced-motion preference.\n    pub motion: UiMotion,\n    /// Typography scale, independent of control density (1 by default).\n    pub text_scale: f32,\n    /// Text sizes and line heights, multiplied by `text_scale` when applied.\n    pub typography: UiTypography,\n    /// Window widths at which layouts change shape.\n    pub breakpoints: UiBreakpoints,\n    /// Syntax colors and surface of Markdown code blocks.\n    pub code_theme: CodeTheme,\n    /// Layout direction. [`locale::set_direction`] sets it and keeps it\n    /// across theme swaps; [`UiTheme::set`] overwrites it with that setting.\n    pub direction: Direction,\n}\n\n/// The syntax theme of Markdown code blocks, as in Mattermost's `codeTheme`.\n///\n/// `Default` follows the light or dark mode on the theme's muted code\n/// surface. The named themes bring their own background and text color, so\n/// a dark code theme stays readable in a light window.\n#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]\npub enum CodeTheme {\n    /// GPUI Kit's light or dark syntax colors, by mode.\n    #[default]\n    Default,\n    /// GitHub's light syntax colors.\n    GitHub,\n    /// Monokai: bright syntax on a dark olive surface.\n    Monokai,\n    /// Solarized, dark variant.\n    SolarizedDark,\n    /// Solarized, light variant.\n    SolarizedLight,\n}\n\nimpl CodeTheme {\n    /// Every code theme, for a settings picker.\n    pub const ALL: [CodeTheme; 5] = [\n        CodeTheme::Default,\n        CodeTheme::GitHub,\n        CodeTheme::Monokai,\n        CodeTheme::SolarizedDark,\n        CodeTheme::SolarizedLight,\n    ];\n\n    /// Reads Mattermost's names: `github`, `monokai`, `solarized-dark`,\n    /// `solarized-light`, and `default`.\n    pub fn from_name(name: &str) -> Option<Self> {\n        Some(match name.trim().to_ascii_lowercase().as_str() {\n            \"default\" | \"\" => Self::Default,\n            \"github\" => Self::GitHub,\n            \"monokai\" => Self::Monokai,\n            \"solarized-dark\" | \"solarized_dark\" => Self::SolarizedDark,\n            \"solarized-light\" | \"solarized_light\" => Self::SolarizedLight,\n            _ => return None,\n        })\n    }\n\n    /// The name `from_name` reads.\n    pub fn name(self) -> &'static str {\n        match self {\n            Self::Default => \"default\",\n            Self::GitHub => \"github\",\n            Self::Monokai => \"monokai\",\n            Self::SolarizedDark => \"solarized-dark\",\n            Self::SolarizedLight => \"solarized-light\",\n        }\n    }\n\n    /// The code block's own background and text color, or `None` for the\n    /// theme's muted surface.\n    pub fn surface(self) -> Option<(Rgba, Rgba)> {\n        let hex = |value: u32| gpui_kit::rgb(value);\n        match self {\n            Self::Default => None,\n            Self::GitHub => Some((hex(0xf6f8fa), hex(0x24292e))),\n            Self::Monokai => Some((hex(0x272822), hex(0xf8f8f2))),\n            Self::SolarizedDark => Some((hex(0x002b36), hex(0x839496))),\n            Self::SolarizedLight => Some((hex(0xfdf6e3), hex(0x657b83))),\n        }\n    }\n\n    /// The Kit highlight theme for this code theme in `mode`, built once.\n    #[doc(hidden)]\n    pub fn highlight_theme(\n        self,\n        mode: ThemeMode,\n    ) -> Arc<gpui_kit::component::highlighter::HighlightTheme> {\n        use gpui_kit::component::highlighter::HighlightTheme;\n        use std::sync::OnceLock;\n        static BUILT: [OnceLock<Arc<HighlightTheme>>; 4] = [const { OnceLock::new() }; 4];\n        // (keyword, string, comment, function, number, type, tag, attribute,\n        //  property, operator, variable)\n        let (index, palette, dark) = match self {\n            Self::Default => {\n                return match mode {\n                    ThemeMode::Light => HighlightTheme::default_light(),\n                    ThemeMode::Dark => HighlightTheme::default_dark(),\n                };\n            }\n            Self::GitHub => (\n                0,\n                [\n                    \"#d73a49\", \"#032f62\", \"#6a737d\", \"#6f42c1\", \"#005cc5\", \"#e36209\", \"#22863a\",\n                    \"#6f42c1\", \"#005cc5\", \"#d73a49\", \"#24292e\",\n                ],\n                false,\n            ),\n            Self::Monokai => (\n                1,\n                [\n                    \"#f92672\", \"#e6db74\", \"#75715e\", \"#a6e22e\", \"#ae81ff\", \"#66d9ef\", \"#f92672\",\n                    \"#a6e22e\", \"#fd971f\", \"#f92672\", \"#f8f8f2\",\n                ],\n                true,\n            ),\n            Self::SolarizedDark => (\n                2,\n                [\n                    \"#859900\", \"#2aa198\", \"#586e75\", \"#268bd2\", \"#d33682\", \"#b58900\", \"#268bd2\",\n                    \"#93a1a1\", \"#268bd2\", \"#859900\", \"#839496\",\n                ],\n                true,\n            ),\n            Self::SolarizedLight => (\n                3,\n                [\n                    \"#859900\", \"#2aa198\", \"#93a1a1\", \"#268bd2\", \"#d33682\", \"#b58900\", \"#268bd2\",\n                    \"#586e75\", \"#268bd2\", \"#859900\", \"#657b83\",\n                ],\n                false,\n            ),\n        };\n        BUILT[index]\n            .get_or_init(|| {\n                let [\n                    keyword,\n                    string,\n                    comment,\n                    function,\n                    number,\n                    kind,\n                    tag,\n                    attribute,\n                    property,\n                    operator,\n                    variable,\n                ] = palette;\n                let color = |value: &str| gpui_kit::private::serde_json::json!({ \"color\": value });\n                let json = gpui_kit::private::serde_json::json!({\n                    \"name\": self.name(),\n                    \"appearance\": if dark { \"dark\" } else { \"light\" },\n                    \"style\": {\n                        \"syntax\": {\n                            \"keyword\": color(keyword),\n                            \"string\": color(string),\n                            \"string.escape\": color(number),\n                            \"comment\": { \"color\": comment, \"font_style\": \"italic\" },\n                            \"comment.doc\": { \"color\": comment, \"font_style\": \"italic\" },\n                            \"function\": color(function),\n                            \"constructor\": color(function),\n                            \"number\": color(number),\n                            \"boolean\": color(number),\n                            \"constant\": color(number),\n                            \"type\": color(kind),\n                            \"enum\": color(kind),\n                            \"tag\": color(tag),\n                            \"attribute\": color(attribute),\n                            \"property\": color(property),\n                            \"operator\": color(operator),\n                            \"variable\": color(variable),\n                            \"punctuation\": color(variable),\n                            \"title\": { \"color\": function, \"font_weight\": 700 },\n                            \"link_uri\": color(string),\n                            \"link_text\": color(function),\n                        }\n                    }\n                });\n                Arc::new(\n                    gpui_kit::private::serde_json::from_value::<HighlightTheme>(json)\n                        .expect(\"the code theme palettes are valid\"),\n                )\n            })\n            .clone()\n    }\n}\n\nimpl Global for UiTheme {}\n\nimpl Default for UiTheme {\n    fn default() -> Self {\n        Self::neutral_light()\n    }\n}\n\nimpl UiTheme {\n    /// Creates the pinned Neutral light theme.\n    pub fn neutral_light() -> Self {\n        Self::new(ThemeMode::Light, neutral_light_colors())\n    }\n\n    /// Creates the pinned Neutral dark theme.\n    pub fn neutral_dark() -> Self {\n        Self::new(ThemeMode::Dark, neutral_dark_colors())\n    }\n\n    /// Installs light and dark themes together and shows the one the current\n    /// [`Appearance`] selects (System until [`UiTheme::set_appearance`] says\n    /// otherwise). [`follow_system`] keeps the pair in step with the OS.\n    pub fn set_pair(cx: &mut App, light: Self, dark: Self) {\n        let appearance = cx\n            .try_global::<ThemePair>()\n            .map_or(Appearance::System, |pair| pair.appearance);\n        cx.set_global(ThemePair {\n            light,\n            dark,\n            appearance,\n        });\n        Self::apply_appearance(cx);\n    }\n\n    /// Chooses which of the installed pair to show. Without a pair, the\n    /// pinned Neutral palettes stand in.\n    pub fn set_appearance(cx: &mut App, appearance: Appearance) {\n        match cx.try_global::<ThemePair>() {\n            Some(_) => cx.global_mut::<ThemePair>().appearance = appearance,\n            None => cx.set_global(ThemePair {\n                light: Self::neutral_light(),\n                dark: Self::neutral_dark(),\n                appearance,\n            }),\n        }\n        Self::apply_appearance(cx);\n    }\n\n    /// The appearance the application asked for, System when none was set.\n    pub fn appearance(cx: &App) -> Appearance {\n        cx.try_global::<ThemePair>()\n            .map_or(Appearance::System, |pair| pair.appearance)\n    }\n\n    /// Installs the pair member the appearance selects, if a pair is installed.\n    fn apply_appearance(cx: &mut App) {\n        let Some(pair) = cx.try_global::<ThemePair>().cloned() else {\n            return;\n        };\n        let theme = match pair.appearance.resolve(cx.window_appearance()) {\n            ThemeMode::Light => pair.light,\n            ThemeMode::Dark => pair.dark,\n        };\n        let current = cx.try_global::<Self>();\n        if current\n            .is_some_and(|current| current.mode == theme.mode && current.colors == theme.colors)\n        {\n            return;\n        }\n        Self::set(cx, theme);\n    }\n\n    /// Installs a theme into the application.\n    pub fn set(cx: &mut App, mut theme: Self) {\n        theme.direction = locale::direction(cx);\n        assert!(f32::from(theme.spacing.unit).is_finite() && theme.spacing.unit > px(0.));\n        assert!(theme.text_scale.is_finite() && theme.text_scale > 0.);\n        sync_component_theme(cx, theme.clone());\n        cx.set_global(theme);\n        cx.refresh_windows();\n    }\n\n    /// Reads the installed theme.\n    ///\n    /// Panics when the application has not installed a theme.\n    #[track_caller]\n    pub fn read(cx: &App) -> &Self {\n        cx.try_global::<Self>().expect(\n            \"gpuicn theme is not installed: call `ui::theme::init(cx)` once at application startup\",\n        )\n    }\n\n    /// Builds a theme from shadcn theme CSS, such as the output of the shadcn\n    /// theme picker or tweakcn.\n    ///\n    /// Light reads `:root`; dark reads `:root` and then `.dark`, like the\n    /// browser cascade. Recognized `--background`, `--primary`, `--sidebar-*`,\n    /// `--chart-*` and `--radius` declarations replace the Neutral defaults;\n    /// other declarations are ignored. Colors may use `oklch()`, `hsl()`,\n    /// bare HSL triplets, `rgb()` or hex. Build both modes and call\n    /// [`UiTheme::set`] to switch; [`UiTheme::switch`] restores Neutral colors.\n    pub fn from_shadcn_css(css: &str, mode: ThemeMode) -> Result<Self, ThemeCssError> {\n        let blocks = css_blocks(css);\n        let mut theme = match mode {\n            ThemeMode::Light => Self::neutral_light(),\n            ThemeMode::Dark => Self::neutral_dark(),\n        };\n        let mut selectors = vec![\":root\"];\n        if mode == ThemeMode::Dark {\n            selectors.push(\".dark\");\n        }\n        for selector in selectors {\n            let declarations = blocks\n                .iter()\n                .filter(|(name, _)| name.split(',').any(|part| part.trim() == selector))\n                .flat_map(|(_, body)| body.split(';'))\n                .collect::<Vec<_>>();\n            if declarations.is_empty() {\n                return Err(ThemeCssError(format!(\"no `{selector}` block found\")));\n            }\n            for declaration in declarations {\n                let Some((name, value)) = declaration.split_once(':') else {\n                    continue;\n                };\n                let (name, value) = (name.trim(), value.trim());\n                let Some(name) = name.strip_prefix(\"--\") else {\n                    continue;\n                };\n                if name == \"radius\" {\n                    theme.radius = UiRadius::new(css_length(value).ok_or_else(|| {\n                        ThemeCssError(format!(\"unsupported length `--radius: {value}`\"))\n                    })?);\n                } else if let Some(slot) = theme.colors.slot(name) {\n                    *slot = css_color(value).ok_or_else(|| {\n                        ThemeCssError(format!(\"unsupported color `--{name}: {value}`\"))\n                    })?;\n                } else if let Some(slot) = theme.colors.optional_slot(name) {\n                    *slot = Some(css_color(value).ok_or_else(|| {\n                        ThemeCssError(format!(\"unsupported color `--{name}: {value}`\"))\n                    })?);\n                }\n            }\n        }\n        Ok(theme)\n    }\n\n    /// Selects the pinned palette, preserving non-color tokens or initializing defaults.\n    pub fn switch(cx: &mut App, mode: ThemeMode) {\n        let mut theme = cx\n            .try_global::<Self>()\n            .cloned()\n            .unwrap_or_else(Self::neutral_light);\n        theme.mode = mode;\n        theme.colors = match mode {\n            ThemeMode::Light => neutral_light_colors(),\n            ThemeMode::Dark => neutral_dark_colors(),\n        };\n        Self::set(cx, theme);\n    }\n\n    /// Returns a multiple of the configured spacing unit (2 means 8px by default).\n    pub fn space(&self, units: f32) -> Pixels {\n        self.spacing.unit * units\n    }\n\n    /// Scales typography independently of spacing; sizes use Nova's default pixels.\n    pub fn text(&self, size: f32) -> Pixels {\n        px(size * self.text_scale)\n    }\n\n    fn new(mode: ThemeMode, colors: UiColors) -> Self {\n        Self {\n            mode,\n            colors,\n            fonts: UiFonts {\n                body: \"Geist\".into(),\n                heading: \"Geist\".into(),\n                mono: \"Geist Mono\".into(),\n            },\n            radius: UiRadius::new(px(10.)),\n            motion: UiMotion::default(),\n            text_scale: 1.,\n            typography: UiTypography::default(),\n            breakpoints: UiBreakpoints::default(),\n            code_theme: CodeTheme::Default,\n            direction: Direction::Ltr,\n            spacing: UiSpacing { unit: px(4.) },\n            shadows: UiShadows {\n                sm: Arc::from([\n                    BoxShadow::new(px(0.), px(1.), black().alpha(0.10)).blur_radius(px(3.)),\n                    BoxShadow::new(px(0.), px(1.), black().alpha(0.10))\n                        .blur_radius(px(2.))\n                        .spread_radius(px(-1.)),\n                ]),\n                md: Arc::from([\n                    BoxShadow::new(px(0.), px(4.), black().alpha(0.10))\n                        .blur_radius(px(6.))\n                        .spread_radius(px(-1.)),\n                    BoxShadow::new(px(0.), px(2.), black().alpha(0.10))\n                        .blur_radius(px(4.))\n                        .spread_radius(px(-2.)),\n                ]),\n                lg: Arc::from([\n                    BoxShadow::new(px(0.), px(10.), black().alpha(0.10))\n                        .blur_radius(px(15.))\n                        .spread_radius(px(-3.)),\n                    BoxShadow::new(px(0.), px(4.), black().alpha(0.10))\n                        .blur_radius(px(6.))\n                        .spread_radius(px(-4.)),\n                ]),\n            },\n        }\n    }\n\n    /// The shared form-control colors for the active mode. See [`ControlColors`].\n    pub fn control(&self) -> ControlColors {\n        let colors = self.colors;\n        let dark = self.mode == ThemeMode::Dark;\n        ControlColors {\n            background: if dark {\n                colors.input.opacity(0.30)\n            } else {\n                colors.background.opacity(0.)\n            },\n            border: colors.input,\n            hover: if dark {\n                colors.input.opacity(0.50)\n            } else {\n                colors.muted\n            },\n            ghost_hover: if dark {\n                colors.muted.opacity(0.50)\n            } else {\n                colors.muted\n            },\n            pressed: colors.muted,\n            segment: if dark {\n                colors.secondary\n            } else {\n                colors.background\n            },\n            track: if dark {\n                colors.input.opacity(0.80)\n            } else {\n                colors.input\n            },\n            thumb: if dark {\n                colors.foreground\n            } else {\n                colors.background\n            },\n            thumb_checked: if dark {\n                colors.primary_foreground\n            } else {\n                colors.background\n            },\n            destructive_background: colors.destructive.opacity(if dark { 0.20 } else { 0.10 }),\n            destructive_hover: colors.destructive.opacity(if dark { 0.30 } else { 0.20 }),\n            destructive_border: colors.destructive.opacity(0.20),\n            ring: colors.ring.opacity(0.50),\n            invalid_ring: colors.destructive.opacity(0.20),\n            surface_border: colors.foreground.opacity(0.10),\n        }\n    }\n\n    /// `color` composited over the `background` token: the same color with\n    /// no transparency. A translucent fill lets a focus ring's shadow, which\n    /// GPUI paints under the whole box, show through it; this one does not.\n    pub fn opaque(&self, color: Rgba) -> Rgba {\n        let under = self.colors.background;\n        let alpha = color.a.clamp(0., 1.);\n        let mix = |top: f32, bottom: f32| top * alpha + bottom * (1. - alpha);\n        Rgba {\n            r: mix(color.r, under.r),\n            g: mix(color.g, under.g),\n            b: mix(color.b, under.b),\n            a: 1.,\n        }\n    }\n\n    /// A step of the type scale multiplied by `text_scale`.\n    pub fn text_style(&self, style: UiTextStyle) -> UiTextStyle {\n        UiTextStyle {\n            size: style.size * self.text_scale,\n            line_height: style.line_height * self.text_scale,\n        }\n    }\n}\n\nfn sync_component_theme(cx: &mut App, theme: UiTheme) {\n    use gpui_kit::component::{Theme, ThemeTokens};\n\n    if !cx.has_global::<Theme>() {\n        return;\n    }\n\n    let colors = theme.colors;\n    let component = Theme::global_mut(cx);\n    component.mode = match theme.mode {\n        ThemeMode::Light => gpui_kit::component::ThemeMode::Light,\n        ThemeMode::Dark => gpui_kit::component::ThemeMode::Dark,\n    };\n    // Start from Kit's palette for this mode, so colors gpuicn doesn't set\n    // below, such as scrollbar tracks, never keep the other mode's values.\n    component.colors = *match theme.mode {\n        ThemeMode::Light => gpui_kit::component::ThemeColor::light(),\n        ThemeMode::Dark => gpui_kit::component::ThemeColor::dark(),\n    };\n    component.font_family = theme.fonts.body;\n    component.mono_font_family = theme.fonts.mono;\n    component.radius = theme.radius.md;\n    component.radius_lg = theme.radius.lg;\n    component.background = colors.background.into();\n    component.foreground = colors.foreground.into();\n    component.popover = colors.popover.into();\n    component.popover_foreground = colors.popover_foreground.into();\n    component.primary = colors.primary.into();\n    component.primary_foreground = colors.primary_foreground.into();\n    component.secondary = colors.secondary.into();\n    component.secondary_foreground = colors.secondary_foreground.into();\n    component.muted = colors.muted.into();\n    component.muted_foreground = colors.muted_foreground.into();\n    component.accent = colors.accent.into();\n    component.accent_foreground = colors.accent_foreground.into();\n    component.primary_hover = colors.primary.opacity(0.9).into();\n    component.primary_active = colors.primary.opacity(0.8).into();\n    component.secondary_hover = colors.secondary.opacity(0.8).into();\n    component.secondary_active = colors.secondary.opacity(0.7).into();\n    component.border = colors.border.into();\n    component.input = colors.input.into();\n    component.ring = colors.ring.into();\n    component.overlay = colors.overlay.into();\n    component.caret = colors.foreground.into();\n    component.window_border = colors.border.into();\n    component.danger = colors.destructive.into();\n    component.danger_foreground = colors.destructive_foreground.into();\n    component.danger_hover = colors.destructive.opacity(0.9).into();\n    component.danger_active = colors.destructive.opacity(0.8).into();\n    component.success = colors.success.into();\n    component.success_foreground = colors.success_foreground.into();\n    component.success_hover = colors.success.opacity(0.9).into();\n    component.success_active = colors.success.opacity(0.8).into();\n    component.warning = colors.warning.into();\n    component.warning_foreground = colors.warning_foreground.into();\n    component.warning_hover = colors.warning.opacity(0.9).into();\n    component.warning_active = colors.warning.opacity(0.8).into();\n    component.info = colors.info.into();\n    component.info_foreground = colors.info_foreground.into();\n    component.info_hover = colors.info.opacity(0.9).into();\n    component.info_active = colors.info.opacity(0.8).into();\n    component.chart_1 = colors.chart_1.into();\n    component.chart_2 = colors.chart_2.into();\n    component.chart_3 = colors.chart_3.into();\n    component.chart_4 = colors.chart_4.into();\n    component.chart_5 = colors.chart_5.into();\n    component.chart_bullish = colors.success.into();\n    component.chart_bearish = colors.destructive.into();\n    component.chart_grid = colors.border.opacity(0.6).into();\n    // Buttons: Kit's plain button is shadcn `outline`; the variants follow their token.\n    component.button = colors.background.into();\n    component.button_foreground = colors.foreground.into();\n    component.button_hover = colors.accent.into();\n    component.button_active = colors.muted.into();\n    component.button_primary = component.primary;\n    component.button_primary_foreground = component.primary_foreground;\n    component.button_primary_hover = component.primary_hover;\n    component.button_primary_active = component.primary_active;\n    component.button_secondary = component.secondary;\n    component.button_secondary_foreground = component.secondary_foreground;\n    component.button_secondary_hover = component.secondary_hover;\n    component.button_secondary_active = component.secondary_active;\n    component.button_danger = component.danger;\n    component.button_danger_foreground = component.danger_foreground;\n    component.button_danger_hover = component.danger_hover;\n    component.button_danger_active = component.danger_active;\n    component.button_success = component.success;\n    component.button_success_foreground = component.success_foreground;\n    component.button_success_hover = component.success_hover;\n    component.button_success_active = component.success_active;\n    component.button_warning = component.warning;\n    component.button_warning_foreground = component.warning_foreground;\n    component.button_warning_hover = component.warning_hover;\n    component.button_warning_active = component.warning_active;\n    component.button_info = component.info;\n    component.button_info_foreground = component.info_foreground;\n    component.button_info_hover = component.info_hover;\n    component.button_info_active = component.info_active;\n    // Nova scrollbars float over content with no track.\n    component.scrollbar = gpui_kit::transparent_black();\n    component.scrollbar_thumb = colors.border.into();\n    component.scrollbar_thumb_hover = colors.muted_foreground.opacity(0.72).into();\n    component.sidebar = colors.sidebar.into();\n    component.sidebar_foreground = colors.sidebar_foreground.into();\n    component.sidebar_border = colors.sidebar_border.into();\n    component.sidebar_accent = colors.sidebar_accent.into();\n    component.sidebar_accent_foreground = colors.sidebar_accent_foreground.into();\n    component.sidebar_primary = colors.sidebar_primary.into();\n    component.sidebar_primary_foreground = colors.sidebar_primary_foreground.into();\n    component.title_bar = colors.sidebar.into();\n    component.title_bar_border = colors.border.into();\n    component.status_bar = colors.sidebar.into();\n    component.status_bar_border = colors.border.into();\n    // Rich text: links, selection, table headings and code highlighting.\n    component.link = colors.link().into();\n    component.link_hover = colors.link().opacity(0.9).into();\n    component.link_active = colors.link().opacity(0.8).into();\n    component.selection = colors.ring.opacity(0.3).into();\n    component.description_list_label = colors.muted.into();\n    component.description_list_label_foreground = colors.muted_foreground.into();\n    component.group_box = colors.card.into();\n    component.group_box_foreground = colors.card_foreground.into();\n    component.accordion = colors.card.into();\n    // Lists and tables share the `muted` zebra and the `accent` hover of menus.\n    component.colors.list = colors.background.into();\n    component.list_even = colors.muted.opacity(0.5).into();\n    component.list_head = colors.muted.into();\n    component.list_hover = colors.accent.into();\n    // Kit draws query matches in Select, Combobox and Command with this.\n    component.list_highlight_foreground = colors.primary.into();\n    component.list_active = colors.accent.into();\n    component.list_active_border = colors.ring.into();\n    component.table = colors.background.into();\n    component.table_even = colors.muted.opacity(0.5).into();\n    component.table_hover = colors.muted.opacity(0.5).into();\n    component.table_active = colors.accent.into();\n    component.table_active_border = colors.ring.into();\n    component.table_row_border = colors.border.into();\n    component.table_head = colors.muted.into();\n    component.table_head_foreground = colors.foreground.into();\n    component.table_foot = colors.muted.opacity(0.5).into();\n    component.table_foot_foreground = colors.foreground.into();\n    // Controls: shadcn tracks are `input`, thumbs and active tabs are `background`.\n    component.switch = colors.input.into();\n    component.switch_thumb = colors.background.into();\n    component.slider_bar = colors.primary.into();\n    component.slider_thumb = colors.background.into();\n    component.progress_bar = colors.primary.into();\n    component.skeleton = colors.accent.into();\n    component.tab_bar = colors.muted.into();\n    component.tab_bar_segmented = colors.muted.into();\n    component.tab_foreground = colors.muted_foreground.into();\n    component.tab_active = colors.background.into();\n    component.tab_active_foreground = colors.foreground.into();\n    component.drag_border = colors.ring.into();\n    component.drop_target = colors.ring.opacity(0.15).into();\n    component.highlight_theme = theme.code_theme.highlight_theme(theme.mode);\n    component.tokens = ThemeTokens::from(&component.colors);\n\n    Theme::sync_base(cx);\n}\n\n/// Why [`UiTheme::from_shadcn_css`] could not read a theme.\n#[derive(Clone, Debug, PartialEq)]\npub struct ThemeCssError(pub String);\n\nimpl std::fmt::Display for ThemeCssError {\n    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        write!(formatter, \"shadcn theme CSS: {}\", self.0)\n    }\n}\n\nimpl std::error::Error for ThemeCssError {}\n\nimpl UiColors {\n    #[doc(hidden)]\n    pub fn slot(&mut self, variable: &str) -> Option<&mut Rgba> {\n        Some(match variable {\n            \"background\" => &mut self.background,\n            \"foreground\" => &mut self.foreground,\n            \"card\" => &mut self.card,\n            \"card-foreground\" => &mut self.card_foreground,\n            \"popover\" => &mut self.popover,\n            \"popover-foreground\" => &mut self.popover_foreground,\n            \"primary\" => &mut self.primary,\n            \"primary-foreground\" => &mut self.primary_foreground,\n            \"secondary\" => &mut self.secondary,\n            \"secondary-foreground\" => &mut self.secondary_foreground,\n            \"muted\" => &mut self.muted,\n            \"muted-foreground\" => &mut self.muted_foreground,\n            \"accent\" => &mut self.accent,\n            \"accent-foreground\" => &mut self.accent_foreground,\n            \"destructive\" => &mut self.destructive,\n            \"destructive-foreground\" => &mut self.destructive_foreground,\n            \"success\" => &mut self.success,\n            \"success-foreground\" => &mut self.success_foreground,\n            \"warning\" => &mut self.warning,\n            \"warning-foreground\" => &mut self.warning_foreground,\n            \"info\" => &mut self.info,\n            \"info-foreground\" => &mut self.info_foreground,\n            \"border\" => &mut self.border,\n            \"input\" => &mut self.input,\n            \"ring\" => &mut self.ring,\n            \"chart-1\" => &mut self.chart_1,\n            \"chart-2\" => &mut self.chart_2,\n            \"chart-3\" => &mut self.chart_3,\n            \"chart-4\" => &mut self.chart_4,\n            \"chart-5\" => &mut self.chart_5,\n            \"sidebar\" | \"sidebar-background\" => &mut self.sidebar,\n            \"sidebar-foreground\" => &mut self.sidebar_foreground,\n            \"sidebar-primary\" => &mut self.sidebar_primary,\n            \"sidebar-primary-foreground\" => &mut self.sidebar_primary_foreground,\n            \"sidebar-accent\" => &mut self.sidebar_accent,\n            \"sidebar-accent-foreground\" => &mut self.sidebar_accent_foreground,\n            \"sidebar-border\" => &mut self.sidebar_border,\n            \"sidebar-ring\" => &mut self.sidebar_ring,\n            _ => return None,\n        })\n    }\n\n    /// The optional tokens that follow another one until set.\n    #[doc(hidden)]\n    pub fn optional_slot(&mut self, variable: &str) -> Option<&mut Option<Rgba>> {\n        Some(match variable {\n            \"link\" => &mut self.link,\n            \"mention-highlight\" => &mut self.mention_highlight,\n            \"mention-highlight-foreground\" => &mut self.mention_highlight_foreground,\n            \"new-messages\" => &mut self.new_messages,\n            \"sidebar-muted-foreground\" => &mut self.sidebar_muted_foreground,\n            \"sidebar-badge\" => &mut self.sidebar_badge,\n            \"sidebar-badge-foreground\" => &mut self.sidebar_badge_foreground,\n            _ => return None,\n        })\n    }\n}\n\n/// Innermost `selector { body }` pairs with comments removed.\nfn css_blocks(css: &str) -> Vec<(String, String)> {\n    let mut text = String::with_capacity(css.len());\n    let mut rest = css;\n    while let Some(start) = rest.find(\"/*\") {\n        text.push_str(&rest[..start]);\n        rest = rest[start + 2..]\n            .split_once(\"*/\")\n            .map_or(\"\", |(_, after)| after);\n    }\n    text.push_str(rest);\n    let mut blocks = Vec::new();\n    let mut selector_start = 0;\n    let mut open = None;\n    for (index, character) in text.char_indices() {\n        match character {\n            '{' => {\n                open = Some((text[selector_start..index].trim().to_owned(), index + 1));\n                selector_start = index + 1;\n            }\n            '}' => {\n                if let Some((selector, body)) = open.take() {\n                    blocks.push((selector, text[body..index].to_owned()));\n                }\n                selector_start = index + 1;\n            }\n            ';' if open.is_none() => selector_start = index + 1,\n            _ => {}\n        }\n    }\n    blocks\n}\n\nfn css_length(value: &str) -> Option<Pixels> {\n    let value = value.trim();\n    let pixels = if let Some(rem) = value.strip_suffix(\"rem\") {\n        rem.trim().parse::<f32>().ok()? * 16.\n    } else if let Some(pixels) = value.strip_suffix(\"px\") {\n        pixels.trim().parse::<f32>().ok()?\n    } else {\n        value.parse::<f32>().ok().filter(|value| *value == 0.)?\n    };\n    (pixels.is_finite() && pixels >= 0.).then(|| px(pixels))\n}\n\n/// A CSS number or percentage; `percent` is the value of `100%`.\nfn css_number(value: &str, percent: f64) -> Option<f64> {\n    let value = value.trim();\n    let number = match value.strip_suffix('%') {\n        Some(value) => value.trim().parse::<f64>().ok()? / 100. * percent,\n        None => value\n            .strip_suffix(\"deg\")\n            .unwrap_or(value)\n            .parse::<f64>()\n            .ok()?,\n    };\n    number.is_finite().then_some(number)\n}\n\nfn css_color(value: &str) -> Option<Rgba> {\n    let value = value.trim().trim_end_matches(\"!important\").trim();\n    if let Some(hex) = value.strip_prefix('#') {\n        return css_hex(hex);\n    }\n    let (function, arguments) = match value.split_once('(') {\n        Some((function, arguments)) => (\n            function.trim().to_ascii_lowercase(),\n            arguments.strip_suffix(')')?,\n        ),\n        // shadcn v3 themes store bare HSL triplets such as `0 0% 100%`.\n        None => (\"hsl\".to_owned(), value),\n    };\n    let (channels, alpha) = match arguments.split_once('/') {\n        Some((channels, alpha)) => (channels, css_number(alpha, 1.)?),\n        None => (arguments, 1.),\n    };\n    let channels: Vec<_> = channels\n        .split(|character: char| character == ',' || character.is_whitespace())\n        .filter(|part| !part.is_empty())\n        .collect();\n    let (channels, alpha) = match channels.len() {\n        3 => (channels, alpha),\n        4 => (channels[..3].to_vec(), css_number(channels[3], 1.)?),\n        _ => return None,\n    };\n    let color = match function.as_str() {\n        \"oklch\" => oklch(\n            css_number(channels[0], 1.)?,\n            css_number(channels[1], 0.4)?,\n            css_number(channels[2], 1.)?,\n        ),\n        \"hsl\" | \"hsla\" => hsl(\n            css_number(channels[0], 1.)?,\n            css_number(channels[1], 1.)?,\n            css_number(channels[2], 1.)?,\n        ),\n        \"rgb\" | \"rgba\" => [\n            css_number(channels[0], 255.)? / 255.,\n            css_number(channels[1], 255.)? / 255.,\n            css_number(channels[2], 255.)? / 255.,\n        ],\n        _ => return None,\n    };\n    Some(Rgba {\n        r: color[0].clamp(0., 1.) as f32,\n        g: color[1].clamp(0., 1.) as f32,\n        b: color[2].clamp(0., 1.) as f32,\n        a: alpha.clamp(0., 1.) as f32,\n    })\n}\n\nfn css_hex(hex: &str) -> Option<Rgba> {\n    if !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {\n        return None;\n    }\n    let digits: Vec<u8> = match hex.len() {\n        3 | 4 => hex\n            .chars()\n            .map(|digit| u8::from_str_radix(&format!(\"{digit}{digit}\"), 16).ok())\n            .collect::<Option<_>>()?,\n        6 | 8 => (0..hex.len())\n            .step_by(2)\n            .map(|index| u8::from_str_radix(&hex[index..index + 2], 16).ok())\n            .collect::<Option<_>>()?,\n        _ => return None,\n    };\n    Some(Rgba {\n        r: digits[0] as f32 / 255.,\n        g: digits[1] as f32 / 255.,\n        b: digits[2] as f32 / 255.,\n        a: digits.get(3).map_or(1., |alpha| *alpha as f32 / 255.),\n    })\n}\n\n/// OKLCH to gamma-encoded sRGB, matching the pinned Neutral conversion when chroma is 0.\nfn oklch(lightness: f64, chroma: f64, hue: f64) -> [f64; 3] {\n    let (a, b) = (\n        chroma * hue.to_radians().cos(),\n        chroma * hue.to_radians().sin(),\n    );\n    let l = (lightness + 0.396_337_777_4 * a + 0.215_803_757_3 * b).powi(3);\n    let m = (lightness - 0.105_561_345_8 * a - 0.063_854_172_8 * b).powi(3);\n    let s = (lightness - 0.089_484_177_5 * a - 1.291_485_548 * b).powi(3);\n    [\n        4.076_741_662_1 * l - 3.307_711_591_3 * m + 0.230_969_929_2 * s,\n        -1.268_438_004_6 * l + 2.609_757_401_1 * m - 0.341_319_396_5 * s,\n        -0.004_196_086_3 * l - 0.703_418_614_7 * m + 1.707_614_701 * s,\n    ]\n    .map(srgb_channel)\n}\n\nfn hsl(hue: f64, saturation: f64, lightness: f64) -> [f64; 3] {\n    let hue = hue.rem_euclid(360.) / 60.;\n    let chroma = (1. - (2. * lightness - 1.).abs()) * saturation;\n    let x = chroma * (1. - (hue % 2. - 1.).abs());\n    let (r, g, b) = match hue as u32 {\n        0 => (chroma, x, 0.),\n        1 => (x, chroma, 0.),\n        2 => (0., chroma, x),\n        3 => (0., x, chroma),\n        4 => (x, 0., chroma),\n        _ => (chroma, 0., x),\n    };\n    let base = lightness - chroma / 2.;\n    [r + base, g + base, b + base]\n}\n\nfn neutral_light_colors() -> UiColors {\n    UiColors {\n        background: neutral(1.0),\n        foreground: neutral(0.145),\n        card: neutral(1.0),\n        card_foreground: neutral(0.145),\n        popover: neutral(1.0),\n        popover_foreground: neutral(0.145),\n        primary: neutral(0.205),\n        primary_foreground: neutral(0.985),\n        secondary: neutral(0.97),\n        secondary_foreground: neutral(0.205),\n        muted: neutral(0.97),\n        muted_foreground: neutral(0.556),\n        accent: neutral(0.97),\n        accent_foreground: neutral(0.205),\n        destructive: srgb(0xdc, 0x26, 0x26),\n        destructive_foreground: neutral(0.985),\n        success: srgb(0x16, 0xa3, 0x4a),\n        success_foreground: neutral(0.985),\n        warning: srgb(0xd9, 0x77, 0x06),\n        warning_foreground: neutral(0.985),\n        info: srgb(0x25, 0x63, 0xeb),\n        info_foreground: neutral(0.985),\n        border: neutral(0.922),\n        input: neutral(0.922),\n        ring: neutral(0.708),\n        chart_1: neutral(0.87),\n        chart_2: neutral(0.556),\n        chart_3: neutral(0.439),\n        chart_4: neutral(0.371),\n        chart_5: neutral(0.269),\n        sidebar: neutral(0.985),\n        sidebar_foreground: neutral(0.145),\n        sidebar_primary: neutral(0.205),\n        sidebar_primary_foreground: neutral(0.985),\n        sidebar_accent: neutral(0.97),\n        sidebar_accent_foreground: neutral(0.205),\n        sidebar_border: neutral(0.922),\n        sidebar_ring: neutral(0.708),\n        overlay: black().alpha(0.10).into(),\n        link: None,\n        mention_highlight: None,\n        mention_highlight_foreground: None,\n        new_messages: None,\n        sidebar_muted_foreground: None,\n        sidebar_badge: None,\n        sidebar_badge_foreground: None,\n    }\n}\n\nfn neutral_dark_colors() -> UiColors {\n    UiColors {\n        background: neutral(0.145),\n        foreground: neutral(0.985),\n        card: neutral(0.205),\n        card_foreground: neutral(0.985),\n        popover: neutral(0.205),\n        popover_foreground: neutral(0.985),\n        primary: neutral(0.922),\n        primary_foreground: neutral(0.205),\n        secondary: neutral(0.269),\n        secondary_foreground: neutral(0.985),\n        muted: neutral(0.269),\n        muted_foreground: neutral(0.708),\n        accent: neutral(0.269),\n        accent_foreground: neutral(0.985),\n        destructive: srgb(0xff, 0x64, 0x67),\n        destructive_foreground: neutral(0.985),\n        success: srgb(0x4a, 0xde, 0x80),\n        success_foreground: neutral(0.145),\n        warning: srgb(0xfb, 0xbf, 0x24),\n        warning_foreground: neutral(0.145),\n        info: srgb(0x60, 0xa5, 0xfa),\n        info_foreground: neutral(0.145),\n        border: neutral_alpha(1.0, 0.10),\n        input: neutral_alpha(1.0, 0.15),\n        ring: neutral(0.556),\n        chart_1: neutral(0.87),\n        chart_2: neutral(0.556),\n        chart_3: neutral(0.439),\n        chart_4: neutral(0.371),\n        chart_5: neutral(0.269),\n        sidebar: neutral(0.205),\n        sidebar_foreground: neutral(0.985),\n        sidebar_primary: srgb(0x14, 0x47, 0xe6),\n        sidebar_primary_foreground: neutral(0.985),\n        sidebar_accent: neutral(0.269),\n        sidebar_accent_foreground: neutral(0.985),\n        sidebar_border: neutral_alpha(1.0, 0.10),\n        sidebar_ring: neutral(0.556),\n        // shadcn pairs black/10 with a backdrop blur GPUI lacks; without it a\n        // 10% scrim disappears on a near-black page.\n        overlay: black().alpha(0.50).into(),\n        link: None,\n        mention_highlight: None,\n        mention_highlight_foreground: None,\n        new_messages: None,\n        sidebar_muted_foreground: None,\n        sidebar_badge: None,\n        sidebar_badge_foreground: None,\n    }\n}\n\n#[doc(hidden)]\npub fn neutral(l: f64) -> Rgba {\n    neutral_alpha(l, 1.0)\n}\n\nfn neutral_alpha(l: f64, alpha: f64) -> Rgba {\n    let channel = srgb_channel(l * l * l) as f32;\n\n    Rgba {\n        r: channel,\n        g: channel,\n        b: channel,\n        a: alpha.clamp(0.0, 1.0) as f32,\n    }\n}\n\nconst fn srgb(red: u8, green: u8, blue: u8) -> Rgba {\n    Rgba {\n        r: red as f32 / 255.0,\n        g: green as f32 / 255.0,\n        b: blue as f32 / 255.0,\n        a: 1.0,\n    }\n}\n\nfn srgb_channel(channel: f64) -> f64 {\n    if channel >= 0.003_130_8 {\n        (1.055 * channel.powf(1.0 / 2.4) - 0.055).clamp(0.0, 1.0)\n    } else {\n        (12.92 * channel).clamp(0.0, 1.0)\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn code_themes_build_with_their_own_surface() {\n        for theme in CodeTheme::ALL {\n            assert_eq!(CodeTheme::from_name(theme.name()), Some(theme));\n            let built = theme.highlight_theme(ThemeMode::Light);\n            // Built once: the Kit shares one highlighter per theme instance.\n            assert!(Arc::ptr_eq(\n                &built,\n                &theme.highlight_theme(ThemeMode::Light)\n            ));\n            if theme.surface().is_some() {\n                assert_eq!(built.name, theme.name());\n                assert!(built.keyword.is_some());\n            }\n        }\n        assert_eq!(\n            CodeTheme::from_name(\"Solarized-Dark\"),\n            Some(CodeTheme::SolarizedDark)\n        );\n        assert_eq!(CodeTheme::from_name(\"dracula\"), None);\n    }\n\n    #[test]\n    fn optional_tokens_follow_their_base_until_set() {\n        let mut theme = UiTheme::neutral_light();\n        theme.colors.primary = gpui_kit::rgb(0x1c58d9);\n        assert_eq!(theme.colors.link(), theme.colors.primary);\n        assert_eq!(theme.colors.mention_highlight(), theme.colors.primary);\n        assert_eq!(theme.colors.new_messages(), theme.colors.destructive);\n        assert_eq!(theme.colors.sidebar_badge(), theme.colors.sidebar_primary);\n        theme.colors.link = Some(gpui_kit::rgb(0x2389d7));\n        assert_eq!(theme.colors.link(), gpui_kit::rgb(0x2389d7));\n        let css = \":root { --primary: #111111; --link: #2389d7; --sidebar-badge: #ff0000; }\";\n        let parsed = UiTheme::from_shadcn_css(css, ThemeMode::Light).unwrap();\n        assert_eq!(parsed.colors.link(), gpui_kit::rgb(0x2389d7));\n        assert_eq!(parsed.colors.sidebar_badge(), gpui_kit::rgb(0xff0000));\n        assert_eq!(parsed.colors.mention_highlight(), gpui_kit::rgb(0x111111));\n    }\n\n    #[test]\n    fn converts_pinned_neutral_tokens() {\n        assert_eq!(\n            neutral(1.0),\n            Rgba {\n                r: 1.0,\n                g: 1.0,\n                b: 1.0,\n                a: 1.0,\n            }\n        );\n        assert_eq!(\n            neutral(0.0),\n            Rgba {\n                r: 0.0,\n                g: 0.0,\n                b: 0.0,\n                a: 1.0,\n            }\n        );\n\n        assert_eq!(neutral_light_colors().destructive, srgb(0xdc, 0x26, 0x26));\n        assert_eq!(neutral_dark_colors().destructive, srgb(0xff, 0x64, 0x67));\n        assert_eq!(\n            neutral_dark_colors().sidebar_primary,\n            srgb(0x14, 0x47, 0xe6)\n        );\n    }\n\n    fn close(left: Rgba, right: Rgba) -> bool {\n        [\n            (left.r, right.r),\n            (left.g, right.g),\n            (left.b, right.b),\n            (left.a, right.a),\n        ]\n        .iter()\n        .all(|(left, right)| (left - right).abs() < 1.5 / 255.)\n    }\n\n    #[test]\n    fn imports_shadcn_theme_css() {\n        let css = r#\"\n            @layer base {\n              :root {\n                --radius: 0.5rem; /* 8px */\n                --background: oklch(1 0 0);\n                --foreground: oklch(0.145 0 0);\n                --primary: #2563eb;\n                --ring: rgb(37 99 235 / 50%);\n                --sidebar-background: 0 0% 98%;\n                --font-sans: Inter, sans-serif;\n              }\n              .dark {\n                --background: oklch(0.145 0 0);\n                --border: oklch(1 0 0 / 10%);\n                --sidebar-primary: oklch(0.488 0.243 264.376);\n                --chart-1: hsl(220 70% 50%);\n              }\n            }\n        \"#;\n        let light = UiTheme::from_shadcn_css(css, ThemeMode::Light).unwrap();\n        assert_eq!(light.mode, ThemeMode::Light);\n        assert_eq!(light.radius.lg, px(8.));\n        assert!(close(light.colors.background, neutral(1.0)));\n        assert!(close(light.colors.foreground, neutral(0.145)));\n        assert_eq!(light.colors.primary, srgb(0x25, 0x63, 0xeb));\n        assert!(close(\n            light.colors.ring,\n            Rgba {\n                a: 0.5,\n                ..srgb(37, 99, 235)\n            }\n        ));\n        assert!(close(light.colors.sidebar, neutral(0.985)));\n        // Variables the CSS leaves out keep the Neutral defaults.\n        assert_eq!(light.colors.muted, neutral_light_colors().muted);\n\n        let dark = UiTheme::from_shadcn_css(css, ThemeMode::Dark).unwrap();\n        assert_eq!(dark.mode, ThemeMode::Dark);\n        assert!(close(dark.colors.background, neutral(0.145)));\n        // `.dark` inherits `:root` values it does not override.\n        assert_eq!(dark.colors.primary, srgb(0x25, 0x63, 0xeb));\n        assert!(close(dark.colors.border, neutral_alpha(1.0, 0.10)));\n        assert!(close(dark.colors.sidebar_primary, srgb(0x14, 0x47, 0xe6)));\n        assert!(close(dark.colors.chart_1, srgb(0x26, 0x63, 0xd9)));\n\n        assert!(UiTheme::from_shadcn_css(\":root { --primary: blue; }\", ThemeMode::Light).is_err());\n        assert!(UiTheme::from_shadcn_css(\":root { --radius: 1em; }\", ThemeMode::Light).is_err());\n        assert!(UiTheme::from_shadcn_css(\":root { }\", ThemeMode::Dark).is_err());\n        assert_eq!(\n            css_hex(\"fff8\"),\n            Some(Rgba {\n                r: 1.,\n                g: 1.,\n                b: 1.,\n                a: 0x88 as f32 / 255.\n            })\n        );\n    }\n\n    #[test]\n    fn preserves_pinned_alpha_tokens() {\n        let dark = neutral_dark_colors();\n        assert_eq!(dark.border.a, 0.10);\n        assert_eq!(dark.input.a, 0.15);\n        assert_eq!(dark.sidebar_border.a, 0.10);\n        assert!((dark.input.opacity(0.30).a - 0.045).abs() < f32::EPSILON);\n    }\n\n    #[test]\n    fn derives_the_shadcn_radius_and_shadow_scales() {\n        let theme = UiTheme::neutral_light();\n        assert_eq!(theme.radius.sm, px(6.));\n        assert_eq!(theme.radius.md, px(8.));\n        assert_eq!(theme.radius.lg, px(10.));\n        assert_eq!(theme.radius.xl, px(14.));\n        assert_eq!(theme.shadows.sm.len(), 2);\n        assert_eq!(theme.shadows.md.len(), 2);\n        assert_eq!(theme.shadows.lg.len(), 2);\n    }\n\n    #[gpui_kit::test]\n    fn keeps_component_state_tokens_in_sync_with_ui_theme(cx: &mut gpui_kit::TestAppContext) {\n        cx.update(|cx| {\n            init(cx);\n            let component = gpui_kit::component::Theme::global(cx);\n            assert_eq!(component.mode, gpui_kit::component::ThemeMode::Light);\n            assert_eq!(\n                component.button_hover,\n                UiTheme::read(cx).colors.accent.into()\n            );\n\n            UiTheme::switch(cx, ThemeMode::Dark);\n            let component = gpui_kit::component::Theme::global(cx);\n            assert_eq!(component.mode, gpui_kit::component::ThemeMode::Dark);\n            assert_eq!(component.ring, UiTheme::read(cx).colors.ring.into());\n\n            let mut custom = UiTheme::read(cx).clone();\n            custom.colors.accent = srgb(0x22, 0x66, 0xaa);\n            custom.fonts.body = \"Custom Sans\".into();\n            custom.radius = UiRadius::new(px(12.));\n            let expected_accent = custom.colors.accent;\n            UiTheme::set(cx, custom);\n\n            let component = gpui_kit::component::Theme::global(cx);\n            assert_eq!(component.button_hover, expected_accent.into());\n            assert_eq!(component.font_family, \"Custom Sans\");\n            assert_eq!(component.radius, px(9.6));\n            assert_eq!(\n                component.tokens.button_hover.background,\n                expected_accent.into()\n            );\n\n            init(cx);\n            assert_eq!(\n                gpui_kit::component::Theme::global(cx).button_hover,\n                expected_accent.into()\n            );\n        });\n    }\n}\n\n// Refine the actual control after default styling; no extra layout or focus node.\n#[doc(hidden)]\npub fn apply_style<T: Styled>(mut element: T, style: &gpui_kit::StyleRefinement) -> T {\n    use gpui_kit::Refineable as _;\n    element.style().refine(style);\n    element\n}\n\n#[derive(gpui_kit::IntoElement)]\n#[doc(hidden)]\npub struct DisclosureIcon {\n    icon: gpui_kit::Svg,\n    open: bool,\n}\n#[doc(hidden)]\npub fn disclosure_icon(icon: gpui_kit::Svg, open: bool) -> DisclosureIcon {\n    DisclosureIcon { icon, open }\n}\nimpl gpui_kit::RenderOnce for DisclosureIcon {\n    fn render(self, window: &mut Window, cx: &mut App) -> impl gpui_kit::IntoElement {\n        let duration = UiTheme::read(cx).motion.fast;\n        let value = transition_value(\n            \"disclosure-rotation\",\n            if self.open { 1. } else { 0. },\n            duration,\n            window,\n            cx,\n        );\n        self.icon\n            .with_transformation(gpui_kit::Transformation::rotate(gpui_kit::radians(\n                value * std::f32::consts::PI,\n            )))\n    }\n}\n\n#[cfg(test)]\nmod motion_tests {\n    use super::*;\n    use gpui_kit::{\n        AppContext as _, Context, IntoElement, Render, TestAppContext, VisualTestContext, div,\n    };\n\n    struct View {\n        target: f32,\n        sampled: f32,\n    }\n    impl Render for View {\n        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {\n            self.sampled = transition_value(\n                \"test-motion\",\n                self.target,\n                Duration::from_millis(200),\n                window,\n                cx,\n            );\n            div()\n        }\n    }\n\n    #[gpui_kit::test]\n    fn theme_reduced_motion_snaps_an_active_upstream_transition(cx: &mut TestAppContext) {\n        cx.update(init);\n        let window = cx.add_window(|_, _| View {\n            target: 0.,\n            sampled: 0.,\n        });\n        let mut visual = VisualTestContext::from_window(window.into(), cx);\n        visual.update(|window, cx| window.draw(cx).clear(cx));\n        window\n            .update(cx, |view, _, cx| {\n                view.target = 1.;\n                cx.notify();\n            })\n            .unwrap();\n        visual.update(|window, cx| window.draw(cx).clear(cx));\n        assert_eq!(\n            cx.read_window(&window, |view, cx| view.read(cx).sampled)\n                .unwrap(),\n            0.\n        );\n        cx.update(|cx| {\n            let mut theme = UiTheme::read(cx).clone();\n            theme.motion.reduced = true;\n            UiTheme::set(cx, theme);\n        });\n        visual.update(|window, cx| window.draw(cx).clear(cx));\n        assert_eq!(\n            cx.read_window(&window, |view, cx| view.read(cx).sampled)\n                .unwrap(),\n            1.\n        );\n    }\n}\n\n/// Shared focus traversal for the tab, radio and toggle collections.\n#[doc(hidden)]\npub struct RovingFocus {\n    pub handles: Vec<Option<gpui_kit::FocusHandle>>,\n    active: gpui_kit::Entity<Option<gpui_kit::FocusHandle>>,\n}\nimpl RovingFocus {\n    pub fn new(\n        id: gpui_kit::ElementId,\n        items: &[(gpui_kit::ElementId, bool)],\n        selected: Option<usize>,\n        window: &mut gpui_kit::Window,\n        cx: &mut App,\n    ) -> Self {\n        let active =\n            window.use_keyed_state((id, \"active\"), cx, |_, _| None::<gpui_kit::FocusHandle>);\n        let mut handles: Vec<_> = items\n            .iter()\n            .map(|(id, disabled)| {\n                let handle = window\n                    .use_keyed_state((id.clone(), \"focus\"), cx, |_, cx| cx.focus_handle())\n                    .read(cx)\n                    .clone();\n                handle.clone().tab_stop(false);\n                (!disabled).then_some(handle)\n            })\n            .collect();\n        let index = handles\n            .iter()\n            .position(|h| h.as_ref().is_some_and(|h| h.is_focused(window)))\n            .or(selected.filter(|&i| handles.get(i).is_some_and(Option::is_some)))\n            .or_else(|| {\n                handles\n                    .iter()\n                    .position(|h| h.is_some() && h.as_ref() == active.read(cx).as_ref())\n            })\n            .or_else(|| handles.iter().position(Option::is_some));\n        if let Some(index) = index {\n            let handle = handles[index].as_ref().unwrap().clone().tab_stop(true);\n            handles[index] = Some(handle.clone());\n            active.update(cx, |value, _| *value = Some(handle));\n        }\n        Self { handles, active }\n    }\n    pub fn key(\n        &self,\n        event: &gpui_kit::KeyDownEvent,\n        axis: Option<gpui_kit::Axis>,\n        window: &mut gpui_kit::Window,\n        cx: &mut App,\n    ) -> Option<usize> {\n        if event.keystroke.modifiers.modified() {\n            return None;\n        }\n        let enabled: Vec<_> = self\n            .handles\n            .iter()\n            .enumerate()\n            .filter_map(|(i, h)| h.as_ref().map(|h| (i, h)))\n            .collect();\n        let current = enabled.iter().position(|(_, h)| h.is_focused(window))?;\n        let direction = UiTheme::read(cx).direction;\n        let next = match direction.logical_key(event.keystroke.key.as_str()) {\n            \"home\" => 0,\n            \"end\" => enabled.len() - 1,\n            \"left\" if axis != Some(gpui_kit::Axis::Vertical) => {\n                (current + enabled.len() - 1) % enabled.len()\n            }\n            \"right\" if axis != Some(gpui_kit::Axis::Vertical) => (current + 1) % enabled.len(),\n            \"up\" if axis != Some(gpui_kit::Axis::Horizontal) => {\n                (current + enabled.len() - 1) % enabled.len()\n            }\n            \"down\" if axis != Some(gpui_kit::Axis::Horizontal) => (current + 1) % enabled.len(),\n            _ => return None,\n        };\n        enabled[current].1.clone().tab_stop(false);\n        let handle = enabled[next].1.clone().tab_stop(true);\n        handle.focus(window, cx);\n        self.active.update(cx, |value, _| *value = Some(handle));\n        window.refresh();\n        cx.stop_propagation();\n        Some(enabled[next].0)\n    }\n}\n"
    },
    {
      "path": "registry/scroll_area/scroll_area.rs",
      "type": "registry:file",
      "target": "~/src/ui/scroll_area.rs",
      "content": "//! Native scrolling with Nova-styled GPUI Kit scrollbars.\n\nuse super::theme::UiTheme;\nuse gpui_kit::base::{Scrollbar, ScrollbarHandle, ScrollbarMode};\nuse gpui_kit::{\n    AnyElement, App, Axis, ElementId, InteractiveElement as _, IntoElement, ParentElement,\n    RenderOnce, Role, ScrollHandle, SharedString, StatefulInteractiveElement as _, Styled, Window,\n    div, prelude::FluentBuilder as _, px,\n};\n\n/// Overlay on a relative container holding a list or scroll viewport.\npub fn scroll_area_scrollbar_for<H: ScrollbarHandle + Clone>(\n    id: impl Into<ElementId>,\n    target: &H,\n    cx: &App,\n) -> Scrollbar {\n    let t = UiTheme::read(cx);\n    Scrollbar::vertical(target)\n        .id(id)\n        .mode(ScrollbarMode::Scrolling)\n        .styles(|styles| {\n            styles\n                // No rail: the thumb floats over content in every state.\n                .track(|style| style.width(t.space(2.5)).bg(gpui_kit::transparent_black()))\n                .track_hover(|style| style.bg(gpui_kit::transparent_black()))\n                .track_active(|style| {\n                    style\n                        .bg(gpui_kit::transparent_black())\n                        .border_color(gpui_kit::transparent_black())\n                })\n                .thumb(|style| {\n                    style\n                        .bg(t.colors.border)\n                        .width(t.space(2.))\n                        .inset(px(1.))\n                        .radius(t.space(1.))\n                })\n                .thumb_hover(|style| style.bg(t.colors.muted_foreground.opacity(0.72)))\n        })\n}\n\n#[derive(IntoElement)]\n/// A native scroll viewport with a Nova-styled Kit scrollbar.\npub struct ScrollArea {\n    id: ElementId,\n    style: gpui_kit::StyleRefinement,\n    label: Option<SharedString>,\n    axis: Axis,\n    scroll: Option<ScrollHandle>,\n    children: Vec<AnyElement>,\n}\nimpl ScrollArea {\n    /// Creates a `ScrollArea` with a stable caller-owned ID.\n    pub fn new(id: impl Into<ElementId>) -> Self {\n        Self {\n            id: id.into(),\n            style: Default::default(),\n            label: None,\n            axis: Axis::Vertical,\n            scroll: None,\n            children: vec![],\n        }\n    }\n    /// Sets the accessible name of the control.\n    pub fn aria_label(mut self, value: impl Into<SharedString>) -> Self {\n        self.label = Some(value.into());\n        self\n    }\n    /// Shares the scroll position with the caller, for example to scroll a\n    /// focused row into view. Without it the area keeps one per ID.\n    pub fn track_scroll(mut self, handle: &ScrollHandle) -> Self {\n        self.scroll = Some(handle.clone());\n        self\n    }\n    /// Selects horizontal or vertical layout and keyboard navigation.\n    pub fn axis(mut self, axis: Axis) -> Self {\n        self.axis = axis;\n        self\n    }\n}\nimpl ParentElement for ScrollArea {\n    fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {\n        self.children.extend(children);\n    }\n}\nimpl Styled for ScrollArea {\n    fn style(&mut self) -> &mut gpui_kit::StyleRefinement {\n        &mut self.style\n    }\n}\nimpl RenderOnce for ScrollArea {\n    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {\n        let t = UiTheme::read(cx).clone();\n        let handle = match self.scroll.clone() {\n            Some(handle) => handle,\n            None => window\n                .use_keyed_state((self.id.clone(), \"scroll\"), cx, |_, _| ScrollHandle::new())\n                .read(cx)\n                .clone(),\n        };\n        let keyboard = handle.clone();\n        // Repaint only the view that renders this area, so an app's other\n        // cached views are reused.\n        let view = window.current_view();\n        let axis = self.axis;\n        let viewport = div()\n            .id(\"viewport\")\n            .role(Role::ScrollView)\n            .focusable()\n            .size_full()\n            .track_scroll(&handle)\n            .when(axis == Axis::Vertical, |viewport| {\n                viewport.overflow_y_scroll()\n            })\n            .when(axis == Axis::Horizontal, |viewport| {\n                viewport.overflow_x_scroll()\n            })\n            .when_some(self.label, |viewport, label| viewport.aria_label(label))\n            .on_key_down(move |event, _, cx| {\n                if event.keystroke.modifiers.modified() {\n                    return;\n                }\n                let mut offset = keyboard.offset();\n                let max = if axis == Axis::Vertical {\n                    keyboard.max_offset().y\n                } else {\n                    keyboard.max_offset().x\n                };\n                let page = if axis == Axis::Vertical {\n                    keyboard.bounds().size.height\n                } else {\n                    keyboard.bounds().size.width\n                };\n                let value = if axis == Axis::Vertical {\n                    &mut offset.y\n                } else {\n                    &mut offset.x\n                };\n                *value = match event.keystroke.key.as_str() {\n                    \"up\" if axis == Axis::Vertical => *value + px(32.),\n                    \"down\" if axis == Axis::Vertical => *value - px(32.),\n                    \"left\" if axis == Axis::Horizontal => *value + px(32.),\n                    \"right\" if axis == Axis::Horizontal => *value - px(32.),\n                    \"pageup\" => *value + page,\n                    \"pagedown\" => *value - page,\n                    \"home\" => px(0.),\n                    \"end\" => -max,\n                    _ => return,\n                };\n                *value = (*value).clamp(-max.max(px(0.)), px(0.));\n                keyboard.set_offset(offset);\n                cx.notify(view);\n                cx.stop_propagation();\n            })\n            .child(div().flex().flex_col().min_w_full().children(self.children));\n        let scrollbar = scroll_area_scrollbar_for(\"scrollbar\", &handle, cx).axis(axis);\n        let root = div()\n            .id(self.id)\n            .relative()\n            .min_h_0()\n            .min_w_0()\n            .font_family(t.fonts.body)\n            .text_color(t.colors.foreground)\n            .child(viewport)\n            .child(scrollbar);\n        super::theme::apply_style(root, &self.style)\n    }\n}\n"
    },
    {
      "path": "registry/tooltip/tooltip.rs",
      "type": "registry:file",
      "target": "~/src/ui/tooltip.rs",
      "content": "//! Nova tooltips for pointer hover and keyboard focus.\nuse super::theme::{UiTheme, primitives::surface};\nuse gpui_kit::base::{\n    Button, ElementExt as _, Placement, Positioner, ResolvedPosition, Tooltip, TooltipDefaults,\n    TooltipOverlay, TooltipRequest,\n};\nuse gpui_kit::{\n    AnyView, AnyWindowHandle, App, AppContext as _, AvailableSpace, Background, Bounds, Context,\n    DispatchPhase, ElementId, Entity, FocusHandle, Global, HitboxBehavior, InteractiveElement as _,\n    IntoElement, MouseDownEvent, MouseMoveEvent, ParentElement, PathBuilder, Pixels, ScrollEvent,\n    SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, Task, WeakEntity,\n    Window, div, point, px,\n};\nuse std::{cell::Cell, rc::Rc};\n\n/// Adds a tooltip to one existing button, preserving a single focus target.\n/// The button must retain its own accessible name.\npub fn tooltip(\n    id: impl Into<ElementId>,\n    label: impl Into<SharedString>,\n    trigger: Button,\n    window: &mut Window,\n    cx: &mut App,\n) -> gpui_kit::Div {\n    let state = window.use_keyed_state(id.into(), cx, TooltipState::new);\n    state.update(cx, |state, _| state.label = label.into());\n    let focus = state.read(cx).focus.clone();\n    let overlay = state.read(cx).overlay.clone();\n    let hover = state.clone();\n    let measured = state.clone();\n    div()\n        .child(\n            trigger\n                .track_focus(&focus)\n                .on_prepaint(move |bounds, _, cx| {\n                    measured.update(cx, |state, _| state.bounds = bounds)\n                })\n                .on_hover(move |hovered, window, cx| {\n                    hover.update(cx, |state, cx| {\n                        state.hovered = *hovered;\n                        state.update_visibility(window, cx);\n                    })\n                }),\n        )\n        .child(overlay)\n}\n\nstruct TooltipState {\n    focus: FocusHandle,\n    overlay: Entity<TooltipOverlay>,\n    bounds: Bounds<Pixels>,\n    label: SharedString,\n    hovered: bool,\n    active: bool,\n    dismissed: bool,\n    _subscriptions: [Subscription; 2],\n}\n\n/// One Escape interceptor for every tooltip in the application, instead of\n/// one keystroke hook per tooltip. Active tooltips register here while shown.\n#[derive(Default)]\nstruct EscapeDismissal {\n    shown: Vec<(AnyWindowHandle, WeakEntity<TooltipState>)>,\n    _subscription: Option<Subscription>,\n}\nimpl Global for EscapeDismissal {}\nimpl EscapeDismissal {\n    fn install(cx: &mut App) {\n        if cx.default_global::<Self>()._subscription.is_some() {\n            return;\n        }\n        let subscription = cx.intercept_keystrokes(|event, window, cx| {\n            if event.keystroke.key != \"escape\" {\n                return;\n            }\n            let handle = window.window_handle();\n            let shown = std::mem::take(&mut cx.global_mut::<Self>().shown);\n            let mut dismissed = false;\n            for (owner, state) in shown {\n                if owner != handle {\n                    cx.global_mut::<Self>().shown.push((owner, state));\n                    continue;\n                }\n                state\n                    .update(cx, |state, cx| {\n                        if state.active {\n                            state.overlay.update(cx, |overlay, cx| overlay.hide(cx));\n                            state.active = false;\n                            state.dismissed = true;\n                            dismissed = true;\n                        }\n                    })\n                    .ok();\n            }\n            if dismissed {\n                cx.stop_propagation();\n            }\n        });\n        cx.global_mut::<Self>()._subscription = Some(subscription);\n    }\n    fn shown(window: &Window, state: WeakEntity<TooltipState>, cx: &mut App) {\n        let handle = window.window_handle();\n        let shown = &mut cx.global_mut::<Self>().shown;\n        shown.retain(|(_, other)| {\n            other.upgrade().is_some() && other.entity_id() != state.entity_id()\n        });\n        shown.push((handle, state));\n    }\n    fn hidden(state: &WeakEntity<TooltipState>, cx: &mut App) {\n        cx.global_mut::<Self>()\n            .shown\n            .retain(|(_, other)| other.entity_id() != state.entity_id());\n    }\n}\n\nimpl TooltipState {\n    fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {\n        EscapeDismissal::install(cx);\n        let focus = cx.focus_handle();\n        let subscriptions = [\n            cx.on_focus(&focus, window, |state, window, cx| {\n                state.update_visibility(window, cx)\n            }),\n            cx.on_blur(&focus, window, |state, window, cx| {\n                state.update_visibility(window, cx)\n            }),\n        ];\n        Self {\n            focus,\n            overlay: cx.new(|_| TooltipOverlay::new()),\n            bounds: Bounds::default(),\n            label: SharedString::default(),\n            hovered: false,\n            active: false,\n            dismissed: false,\n            _subscriptions: subscriptions,\n        }\n    }\n    fn update_visibility(&mut self, window: &mut Window, cx: &mut Context<Self>) {\n        let active = self.hovered || self.focus.is_focused(window);\n        if !active {\n            self.dismissed = false;\n        }\n        let active = active && !self.dismissed;\n        if active == self.active {\n            return;\n        }\n        self.active = active;\n        if active {\n            let label = self.label.clone();\n            let request =\n                TooltipRequest::new(self.bounds, move |_, cx| text_tooltip(label.clone(), cx));\n            self.overlay\n                .update(cx, |overlay, cx| overlay.request_show(request, window, cx));\n            EscapeDismissal::shown(window, cx.weak_entity(), cx);\n        } else {\n            self.overlay.update(cx, |overlay, cx| overlay.hide(cx));\n            EscapeDismissal::hidden(&cx.weak_entity(), cx);\n        }\n    }\n}\n\n/// Creates a tooltip view for GPUI's native `.tooltip(...)` attachment point.\n/// Use this on an existing interactive control to avoid nesting another button\n/// and tab stop. The host control must retain its own full accessible name.\npub fn text_tooltip(label: gpui_kit::SharedString, cx: &mut App) -> gpui_kit::AnyView {\n    use gpui_kit::AppContext as _;\n    cx.new(|_| TextTooltip(label)).into()\n}\nstruct TextTooltip(gpui_kit::SharedString);\nimpl gpui_kit::Render for TextTooltip {\n    fn render(\n        &mut self,\n        _: &mut gpui_kit::Window,\n        cx: &mut gpui_kit::Context<Self>,\n    ) -> impl gpui_kit::IntoElement {\n        use gpui_kit::ParentElement as _;\n        let theme = UiTheme::read(cx);\n        surface::tooltip(Tooltip::new(\"tooltip-content\"), theme).child(\n            div()\n                .debug_selector(|| \"tooltip-label\".into())\n                .child(self.0.clone()),\n        )\n    }\n}\n\n/// How far the arrow reaches out of the bubble, and how wide its base is.\nconst ARROW_DEPTH: f32 = 6.;\nconst ARROW_WIDTH: f32 = 12.;\n/// Between the arrow's tip and the trigger.\nconst ARROW_GAP: f32 = 2.;\n/// Kept between a tooltip and the window edge.\nconst EDGE_MARGIN: f32 = 8.;\n/// Above popups, as Base draws its own tooltips.\nconst TOOLTIP_PRIORITY: usize = 200;\n\n/// Hover tooltips anchored to their trigger: centered above it with an arrow\n/// pointing at it, below it when there is no room above, and kept inside the\n/// window. GPUI's native `.tooltip(...)` opens wherever the pointer happens to\n/// be, below and to the right of it, which reads as detached from the thing it\n/// describes.\npub trait AnchoredTooltip: ParentElement + Sized {\n    /// Shows `build`'s view, usually [`text_tooltip`], after the hover delay\n    /// and hides it when the pointer leaves, presses or scrolls. The element\n    /// keeps its own hover, click and focus behavior.\n    fn anchored_tooltip(self, build: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self {\n        self.child(anchor(Rc::new(build)))\n    }\n}\nimpl<T: ParentElement> AnchoredTooltip for T {}\n\ntype TipBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyView>;\n\n/// The one hovered trigger in the application: a pointer hovers one place at a\n/// time, so one slot serves every window.\n#[derive(Default)]\nstruct AnchoredTips {\n    active: Option<ActiveTip>,\n}\nimpl Global for AnchoredTips {}\n\nstruct ActiveTip {\n    window: AnyWindowHandle,\n    trigger: Bounds<Pixels>,\n    /// Built once the delay passes, then kept so the tip does not rebuild on\n    /// every frame.\n    view: Option<AnyView>,\n    dismissed: bool,\n    _delay: Option<Task<()>>,\n}\n\nimpl ActiveTip {\n    fn is(&self, window: AnyWindowHandle, trigger: Bounds<Pixels>) -> bool {\n        self.window == window && self.trigger == trigger\n    }\n}\n\nfn contains(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {\n    outer.left() <= inner.left()\n        && outer.top() <= inner.top()\n        && outer.right() >= inner.right()\n        && outer.bottom() >= inner.bottom()\n}\n\n/// An invisible layer over the trigger that watches the pointer without\n/// taking it, and draws the tooltip on top of everything while it is due.\n///\n/// Hover is read in the mouse listeners, against the frame the pointer moved\n/// over: a hitbox inserted during prepaint is not in that frame's hit test\n/// yet, so asking it there always says \"not hovered\".\nfn anchor(build: TipBuilder) -> impl IntoElement {\n    gpui_kit::canvas(\n        move |trigger, window, cx| {\n            let hitbox = window.insert_hitbox(trigger, HitboxBehavior::Normal);\n            let handle = window.window_handle();\n            let view = cx\n                .try_global::<AnchoredTips>()\n                .and_then(|tips| tips.active.as_ref())\n                .filter(|active| active.is(handle, trigger) && !active.dismissed)\n                .and_then(|active| active.view.clone());\n            let overlay = view.map(|view| {\n                let mut overlay = bubble(view, trigger, cx).into_any_element();\n                overlay.prepaint_as_root(trigger.origin, AvailableSpace::min_size(), window, cx);\n                overlay\n            });\n            (hitbox, overlay)\n        },\n        move |trigger, (hitbox, overlay), window, cx| {\n            if let Some(mut overlay) = overlay {\n                overlay.paint(window, cx);\n            }\n            let view_id = window.current_view();\n            let moved = hitbox.clone();\n            let build = build.clone();\n            window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {\n                if phase == DispatchPhase::Bubble {\n                    hover(\n                        moved.is_hovered(window),\n                        trigger,\n                        &build,\n                        view_id,\n                        window,\n                        cx,\n                    );\n                }\n            });\n            let pressed = hitbox.clone();\n            window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {\n                if phase == DispatchPhase::Bubble && pressed.is_hovered(window) {\n                    dismiss(window.window_handle(), trigger, cx);\n                    cx.notify(view_id);\n                }\n            });\n            window.on_mouse_event(move |_: &ScrollEvent, phase, window, cx| {\n                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {\n                    dismiss(window.window_handle(), trigger, cx);\n                    cx.notify(view_id);\n                }\n            });\n        },\n    )\n    .absolute()\n    .top_0()\n    .left_0()\n    .size_full()\n}\n\n/// Starts the delay when the pointer enters a trigger and forgets the tip\n/// when it leaves. Listeners run innermost first, so a trigger inside another\n/// (a status emoji in a row with its own tooltip) claims the slot and the\n/// outer one leaves it be while the pointer is over the inner one.\nfn hover(\n    hovered: bool,\n    trigger: Bounds<Pixels>,\n    build: &TipBuilder,\n    view_id: gpui_kit::EntityId,\n    window: &mut Window,\n    cx: &mut App,\n) {\n    let handle = window.window_handle();\n    let mouse = window.mouse_position();\n    let tips = cx.default_global::<AnchoredTips>();\n    let mine = tips\n        .active\n        .as_ref()\n        .is_some_and(|active| active.is(handle, trigger));\n    if !hovered {\n        if mine {\n            tips.active = None;\n            cx.notify(view_id);\n        }\n        return;\n    }\n    let inner = tips.active.as_ref().is_some_and(|active| {\n        !mine\n            && active.window == handle\n            && active.trigger.contains(&mouse)\n            && contains(trigger, active.trigger)\n    });\n    if mine || inner {\n        return;\n    }\n    let delay = TooltipDefaults::global(cx).show_delay();\n    let build = build.clone();\n    let task = window.spawn(cx, async move |cx| {\n        cx.background_executor().timer(delay).await;\n        cx.update(|window, cx| {\n            let due = cx\n                .global::<AnchoredTips>()\n                .active\n                .as_ref()\n                .is_some_and(|active| active.is(handle, trigger) && !active.dismissed);\n            if due {\n                let view = build(window, cx);\n                if let Some(active) = cx.global_mut::<AnchoredTips>().active.as_mut() {\n                    active.view = Some(view);\n                }\n                cx.notify(view_id);\n            }\n        })\n        .ok();\n    });\n    cx.global_mut::<AnchoredTips>().active = Some(ActiveTip {\n        window: handle,\n        trigger,\n        view: None,\n        dismissed: false,\n        _delay: Some(task),\n    });\n}\n\nfn dismiss(window: AnyWindowHandle, trigger: Bounds<Pixels>, cx: &mut App) {\n    if let Some(active) = cx.default_global::<AnchoredTips>().active.as_mut()\n        && active.is(window, trigger)\n    {\n        active.dismissed = true;\n        active.view = None;\n    }\n}\n\n/// The tip placed on its side of the trigger with the arrow drawn from the\n/// edge facing it, at the trigger's center (or as near as the corners allow\n/// when the tip is pushed in from the window edge).\nfn bubble(view: AnyView, trigger: Bounds<Pixels>, cx: &App) -> impl IntoElement {\n    let theme = UiTheme::read(cx);\n    let fill = theme.colors.popover;\n    let stroke = theme.control().surface_border;\n    let corner = theme.radius.md;\n    let resolved = Rc::new(Cell::new(None));\n    let placed = resolved.clone();\n    gpui_kit::deferred(\n        Positioner::side(trigger)\n            .placement(Placement::Top)\n            .offset(px(ARROW_DEPTH + ARROW_GAP))\n            .margin(px(EDGE_MARGIN))\n            .on_position(move |position| placed.set(Some(position)))\n            .child(\n                div()\n                    .debug_selector(|| \"anchored-tooltip\".into())\n                    .relative()\n                    .child(view)\n                    .child(\n                        gpui_kit::canvas(\n                            |_, _, _| {},\n                            move |_, _, window, _| {\n                                let Some(ResolvedPosition {\n                                    bounds,\n                                    placement: Some(placement),\n                                }) = resolved.get()\n                                else {\n                                    return;\n                                };\n                                paint_arrow(\n                                    bounds, placement, trigger, corner, fill, stroke, window,\n                                );\n                            },\n                        )\n                        .absolute()\n                        .top_0()\n                        .left_0()\n                        .size_full(),\n                    ),\n            ),\n    )\n    .with_priority(TOOLTIP_PRIORITY)\n}\n\nfn paint_arrow(\n    bubble: Bounds<Pixels>,\n    placement: Placement,\n    trigger: Bounds<Pixels>,\n    corner: Pixels,\n    fill: impl Into<Background> + Copy,\n    stroke: impl Into<Background> + Copy,\n    window: &mut Window,\n) {\n    let half = px(ARROW_WIDTH / 2.);\n    let low = bubble.left() + corner + half;\n    let high = bubble.right() - corner - half;\n    if low > high {\n        return;\n    }\n    let x = trigger.center().x.clamp(low, high);\n    let (edge, out) = match placement {\n        Placement::Top => (bubble.bottom(), px(1.)),\n        Placement::Bottom => (bubble.top(), px(-1.)),\n        Placement::Left | Placement::Right => return,\n    };\n    // The border-colored triangle, then the fill inset by about a pixel\n    // along its slanted sides. Both start a pixel inside the bubble, so the\n    // fill covers the bubble's border where the arrow leaves it.\n    let triangle = |inset: f32| {\n        let base = edge - out;\n        let mut path = PathBuilder::fill();\n        path.move_to(point(x - half + px(inset), base));\n        path.line_to(point(x + half - px(inset), base));\n        path.line_to(point(x, edge + out * (ARROW_DEPTH - inset)));\n        path.close();\n        path.build().ok()\n    };\n    if let Some(path) = triangle(0.) {\n        window.paint_path(path, stroke);\n    }\n    if let Some(path) = triangle(1.4) {\n        window.paint_path(path, fill);\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use gpui_kit::{IntoElement, Modifiers, Render, Styled, TestAppContext, px};\n    use std::time::Duration;\n\n    #[gpui_kit::test]\n    fn focus_and_hover_show_tooltip_and_escape_dismisses_it(cx: &mut TestAppContext) {\n        struct Probe;\n        impl Render for Probe {\n            fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {\n                div()\n                    .child(tooltip(\n                        \"test-tooltip\",\n                        \"Help\",\n                        Button::new(\"help\").size(px(100.)).child(\"Help\"),\n                        window,\n                        cx,\n                    ))\n                    .child(Button::new(\"after\").child(\"After\"))\n            }\n        }\n        cx.update(super::super::theme::init);\n        let (_, visual) = cx.add_window_view(|_, _| Probe);\n        visual.update(|window, cx| {\n            window.activate_window();\n            window.draw(cx).clear(cx);\n        });\n        visual.simulate_mouse_move(\n            gpui_kit::point(px(200.), px(200.)),\n            None,\n            Modifiers::default(),\n        );\n        visual.simulate_keystrokes(\"tab\");\n        visual.executor().advance_clock(Duration::from_millis(550));\n        visual.update(|window, cx| window.draw(cx).clear(cx));\n        assert!(visual.debug_bounds(\"tooltip-label\").is_some());\n        visual.simulate_keystrokes(\"escape\");\n        assert!(visual.debug_bounds(\"tooltip-label\").is_none());\n        visual.simulate_keystrokes(\"tab shift-tab\");\n        visual.executor().advance_clock(Duration::from_millis(550));\n        visual.update(|window, cx| window.draw(cx).clear(cx));\n        assert!(visual.debug_bounds(\"tooltip-label\").is_some());\n        visual.simulate_keystrokes(\"tab\");\n        visual.update(|window, cx| window.draw(cx).clear(cx));\n        assert!(visual.debug_bounds(\"tooltip-label\").is_none());\n        // Hover the first control while keyboard focus stays on the second.\n        visual.simulate_mouse_move(\n            gpui_kit::point(px(10.), px(10.)),\n            None,\n            Modifiers::default(),\n        );\n        visual.executor().advance_clock(Duration::from_millis(550));\n        visual.update(|window, cx| window.draw(cx).clear(cx));\n        assert!(visual.debug_bounds(\"tooltip-label\").is_some());\n        visual.simulate_keystrokes(\"escape\");\n        assert!(visual.debug_bounds(\"tooltip-label\").is_none());\n    }\n\n    #[gpui_kit::test]\n    fn anchored_tooltips_sit_centered_above_and_flip_below_at_the_top(cx: &mut TestAppContext) {\n        struct Probe;\n        impl Render for Probe {\n            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {\n                div()\n                    .size_full()\n                    .child(\n                        div()\n                            .id(\"top\")\n                            .absolute()\n                            .top(px(0.))\n                            .left(px(100.))\n                            .size(px(40.))\n                            .anchored_tooltip(|_, cx| text_tooltip(\"Top\".into(), cx)),\n                    )\n                    .child(\n                        div()\n                            .id(\"middle\")\n                            .absolute()\n                            .top(px(300.))\n                            .left(px(300.))\n                            .size(px(40.))\n                            .anchored_tooltip(|_, cx| text_tooltip(\"Middle\".into(), cx)),\n                    )\n            }\n        }\n        cx.update(super::super::theme::init);\n        let (_, visual) = cx.add_window_view(|_, _| Probe);\n        visual.update(|window, cx| window.draw(cx).clear(cx));\n        let mut show = |at: gpui_kit::Point<Pixels>| {\n            visual.simulate_mouse_move(at, None, Modifiers::default());\n            visual.executor().advance_clock(Duration::from_millis(550));\n            visual.run_until_parked();\n            visual.update(|window, cx| window.draw(cx).clear(cx));\n            visual.debug_bounds(\"anchored-tooltip\")\n        };\n\n        let tip = show(gpui_kit::point(px(320.), px(320.))).expect(\"shown after the delay\");\n        assert!(tip.bottom() < px(300.), \"{tip:?}\");\n        assert!((tip.center().x - px(320.)).abs() < px(1.), \"{tip:?}\");\n\n        let tip = show(gpui_kit::point(px(120.), px(20.))).expect(\"shown below the top one\");\n        assert!(tip.top() > px(40.), \"{tip:?}\");\n        assert!((tip.center().x - px(120.)).abs() < px(1.), \"{tip:?}\");\n\n        visual.simulate_mouse_move(\n            gpui_kit::point(px(600.), px(600.)),\n            None,\n            Modifiers::default(),\n        );\n        visual.update(|window, cx| window.draw(cx).clear(cx));\n        assert!(visual.debug_bounds(\"anchored-tooltip\").is_none());\n    }\n}\n"
    },
    {
      "path": "registry/button/button.rs",
      "type": "registry:file",
      "target": "~/src/ui/button.rs",
      "content": "//! The shadcn Nova Button visual port.\n//!\n//! Visual source: shadcn/ui 4.19.0 `button.tsx` and `style-nova.css` at\n//! `1773ecfeeb4a04366978d353e69b5c7ded78dcb2`. Interaction comes from the\n//! GPUI Kit headless button.\n\nuse std::rc::Rc;\n\nuse gpui_kit::base::Button as BaseButton;\nuse gpui_kit::{\n    AnyElement, App, ClickEvent, ElementId, FontWeight, IntoElement, ParentElement, RenderOnce,\n    Rgba, SharedString, Styled, Window, px,\n};\n\nuse super::theme::{\n    UiRadius, UiTheme,\n    locale::DirectionalStyled as _,\n    primitives::{disabled as disabled_style, focus, text},\n};\n\ntype ButtonClickHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;\ntype ButtonStyleHandler = Rc<dyn Fn(BaseButton) -> BaseButton>;\n\n/// The pinned shadcn Button visual variant.\n#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]\npub enum ButtonVariant {\n    /// Primary action.\n    #[default]\n    Default,\n    /// Bordered action.\n    Outline,\n    /// Secondary action.\n    Secondary,\n    /// Low-emphasis action.\n    Ghost,\n    /// Destructive action.\n    Destructive,\n    /// Link-styled action.\n    Link,\n    /// A low-emphasis action on the sidebar: clear at rest and hovering in\n    /// the sidebar's own colors, so it reads on a sidebar that is darker or\n    /// lighter than the page.\n    Sidebar,\n}\n\n/// The pinned shadcn Button size.\n#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]\npub enum ButtonSize {\n    /// 24px-high extra-small button.\n    Xs,\n    /// 28px-high small button.\n    Sm,\n    /// 32px-high default button.\n    #[default]\n    Default,\n    /// 36px-high large button.\n    Lg,\n    /// 24px square icon button.\n    IconXs,\n    /// 28px square icon button.\n    IconSm,\n    /// 32px square icon button.\n    Icon,\n    /// 36px square icon button.\n    IconLg,\n}\n\n#[derive(Clone, Copy, Debug, PartialEq)]\nstruct ButtonMetrics {\n    height: f32,\n    horizontal_padding: f32,\n    gap: f32,\n    radius: f32,\n    text_size: f32,\n    icon_only: bool,\n}\n\nimpl ButtonSize {\n    fn metrics(self, radii: UiRadius) -> ButtonMetrics {\n        let radius = f32::from(radii.lg);\n        let radius_md = f32::from(radii.md);\n        match self {\n            Self::Xs => ButtonMetrics::new(24.0, 8.0, 4.0, radius_md.min(10.0), 12.0, false),\n            Self::Sm => ButtonMetrics::new(28.0, 10.0, 4.0, radius_md.min(12.0), 12.8, false),\n            Self::Default => ButtonMetrics::new(32.0, 10.0, 6.0, radius, 14.0, false),\n            Self::Lg => ButtonMetrics::new(36.0, 10.0, 6.0, radius, 14.0, false),\n            Self::IconXs => ButtonMetrics::new(24.0, 0.0, 0.0, radius_md.min(10.0), 14.0, true),\n            Self::IconSm => ButtonMetrics::new(28.0, 0.0, 0.0, radius_md.min(12.0), 14.0, true),\n            Self::Icon => ButtonMetrics::new(32.0, 0.0, 0.0, radius, 14.0, true),\n            Self::IconLg => ButtonMetrics::new(36.0, 0.0, 0.0, radius, 14.0, true),\n        }\n    }\n}\n\nimpl ButtonMetrics {\n    const fn new(\n        height: f32,\n        horizontal_padding: f32,\n        gap: f32,\n        radius: f32,\n        text_size: f32,\n        icon_only: bool,\n    ) -> Self {\n        Self {\n            height,\n            horizontal_padding,\n            gap,\n            radius,\n            text_size,\n            icon_only,\n        }\n    }\n}\n\n/// A styled Button that keeps GPUI Kit's pointer and keyboard behavior.\n#[derive(IntoElement)]\npub struct Button {\n    style: gpui_kit::StyleRefinement,\n    id: ElementId,\n    variant: ButtonVariant,\n    size: ButtonSize,\n    disabled: bool,\n    aria_label: Option<SharedString>,\n    on_click: Option<ButtonClickHandler>,\n    style_with: Option<ButtonStyleHandler>,\n    tint: Option<Rgba>,\n    children: Vec<AnyElement>,\n}\n\nimpl Button {\n    /// Creates a Button with a caller-owned stable ID.\n    pub fn new(id: impl Into<ElementId>) -> Self {\n        Self {\n            style: gpui_kit::StyleRefinement::default(),\n            id: id.into(),\n            variant: ButtonVariant::default(),\n            size: ButtonSize::default(),\n            disabled: false,\n            aria_label: None,\n            on_click: None,\n            style_with: None,\n            tint: None,\n            children: Vec::new(),\n        }\n    }\n\n    /// Sets the visual variant.\n    pub fn variant(mut self, variant: ButtonVariant) -> Self {\n        self.variant = variant;\n        self\n    }\n\n    /// Sets the visual size.\n    pub fn size(mut self, size: ButtonSize) -> Self {\n        self.size = size;\n        self\n    }\n\n    /// Prevents activation and removes the Button from tab order.\n    pub fn disabled(mut self, disabled: bool) -> Self {\n        self.disabled = disabled;\n        self\n    }\n\n    /// Sets the accessible name for icon or custom content. Use `label` for plain text.\n    pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {\n        self.aria_label = Some(label.into());\n        self\n    }\n\n    /// Adds visible text and uses it as the accessible name unless one was supplied.\n    pub fn label(mut self, label: impl Into<SharedString>) -> Self {\n        let label = label.into();\n        self.aria_label.get_or_insert_with(|| label.clone());\n        self.children.push(label.into_any_element());\n        self\n    }\n\n    /// Runs for pointer, Enter, or Space activation.\n    pub fn on_click(\n        mut self,\n        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,\n    ) -> Self {\n        self.on_click = Some(Rc::new(handler));\n        self\n    }\n\n    /// Fills the button with one app-chosen color, such as an integration's\n    /// `#3f51b5`. Hover moves the fill toward the text, and the text is the\n    /// theme's foreground or background, whichever reads better on the fill,\n    /// so it keeps its contrast in light and dark mode. Replaces the variant.\n    pub fn tint(mut self, color: impl Into<Rgba>) -> Self {\n        self.tint = Some(color.into());\n        self\n    }\n\n    /// Replaces the visual styling while retaining button interaction.\n    /// Include a visible keyboard focus treatment in custom styles.\n    pub fn style_with(mut self, handler: impl Fn(BaseButton) -> BaseButton + 'static) -> Self {\n        self.style_with = Some(Rc::new(handler));\n        self\n    }\n}\n\nimpl ParentElement for Button {\n    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {\n        self.children.extend(elements);\n    }\n}\n\nimpl RenderOnce for Button {\n    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {\n        let theme = UiTheme::read(cx).clone();\n        let variant = self.variant;\n        let size = self.size;\n        let root = BaseButton::new(self.id).disabled(self.disabled);\n        let root = match (self.style_with, self.tint) {\n            (Some(style), _) => style(root),\n            (None, Some(tint)) => style_tinted_button(root, self.disabled, tint, size, &theme),\n            (None, None) => style_button(root, self.disabled, variant, size, &theme),\n        };\n        let mut root = super::theme::apply_style(root, &self.style).children(self.children);\n\n        if let Some(label) = self.aria_label {\n            root = root.accessibility_label(label);\n        }\n        if !self.disabled {\n            root = super::theme::primitives::press::claim(root);\n        }\n        if let Some(handler) = self.on_click {\n            root = root.on_click(move |event, window, cx| handler(event, window, cx));\n        }\n\n        root\n    }\n}\n\n#[doc(hidden)]\npub fn style_button<T: Styled + gpui_kit::InteractiveElement + gpui_kit::prelude::FluentBuilder>(\n    base: T,\n    disabled: bool,\n    variant: ButtonVariant,\n    size: ButtonSize,\n    theme: &UiTheme,\n) -> T {\n    style_button_with(base, disabled, variant, None, size, theme)\n}\n\nfn style_button_with<\n    T: Styled + gpui_kit::InteractiveElement + gpui_kit::prelude::FluentBuilder,\n>(\n    base: T,\n    disabled: bool,\n    variant: ButtonVariant,\n    tint: Option<Rgba>,\n    size: ButtonSize,\n    theme: &UiTheme,\n) -> T {\n    let colors = theme.colors;\n    let control = theme.control();\n    let metrics = size.metrics(theme.radius);\n    let invalid_ring = variant == ButtonVariant::Destructive;\n    let focus_theme = theme.clone();\n\n    let base = base\n        .flex_row_in(theme.direction)\n        .flex_shrink_0()\n        .items_center()\n        .justify_center()\n        .whitespace_nowrap()\n        .h(theme.space(metrics.height / 4.))\n        .gap(theme.space(metrics.gap / 4.))\n        .rounded(px(metrics.radius))\n        .border_1()\n        .border_color(colors.background.opacity(0.0))\n        .font_family(theme.fonts.body.clone())\n        .font_weight(FontWeight::MEDIUM)\n        .map(|base| text::control(base, theme, theme.text(metrics.text_size)))\n        .focus_visible(move |style| focus::ring_for(style, &focus_theme, invalid_ring))\n        .when(metrics.icon_only, |base| {\n            base.w(theme.space(metrics.height / 4.)).p_0()\n        })\n        .when(!metrics.icon_only, |base| {\n            base.px(theme.space(metrics.horizontal_padding / 4.))\n        });\n\n    if let Some(tint) = tint {\n        let (fill, hover, foreground) = tint_colors(tint, theme);\n        let base = base\n            .bg(fill)\n            .text_color(foreground)\n            .when(!disabled, |base| base.hover(move |style| style.bg(hover)));\n        return disabled_style::interactive(base, disabled);\n    }\n    let base = match variant {\n        ButtonVariant::Default => base\n            .bg(colors.primary)\n            .text_color(colors.primary_foreground)\n            .when(!disabled, |base| {\n                base.hover(move |style| style.bg(colors.primary.opacity(0.80)))\n            }),\n        ButtonVariant::Outline => base\n            .bg(control.background)\n            .text_color(colors.foreground)\n            .border_color(control.border)\n            .when(!disabled, |base| {\n                base.hover(move |style| style.bg(control.hover).text_color(colors.foreground))\n            }),\n        ButtonVariant::Secondary => {\n            let hover = colors\n                .secondary\n                .blend(colors.secondary_foreground.opacity(0.08));\n            base.bg(colors.secondary)\n                .text_color(colors.secondary_foreground)\n                .when(!disabled, |base| base.hover(move |style| style.bg(hover)))\n        }\n        ButtonVariant::Ghost => base\n            .bg(colors.background.opacity(0.0))\n            .text_color(colors.foreground)\n            .when(!disabled, |base| {\n                base.hover(move |style| style.bg(control.ghost_hover).text_color(colors.foreground))\n            }),\n        ButtonVariant::Destructive => base\n            .bg(control.destructive_background)\n            .text_color(colors.destructive)\n            .when(!disabled, |base| {\n                base.hover(move |style| style.bg(control.destructive_hover))\n            }),\n        ButtonVariant::Link => base\n            .bg(colors.background.opacity(0.0))\n            .text_color(colors.link())\n            .when(!disabled, |base| base.hover(|style| style.underline())),\n        ButtonVariant::Sidebar => base\n            .bg(colors.sidebar.opacity(0.0))\n            .text_color(colors.sidebar_foreground)\n            .when(!disabled, |base| {\n                base.hover(move |style| {\n                    style\n                        .bg(colors.sidebar_accent)\n                        .text_color(colors.sidebar_accent_foreground)\n                })\n            }),\n    };\n\n    disabled_style::interactive(base, disabled)\n}\n\n/// WCAG relative luminance of an opaque color.\nfn luminance(color: Rgba) -> f32 {\n    let channel = |c: f32| {\n        if c <= 0.039_28 {\n            c / 12.92\n        } else {\n            ((c + 0.055) / 1.055).powf(2.4)\n        }\n    };\n    0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b)\n}\n\n/// The WCAG contrast ratio between two opaque colors, from 1 to 21.\npub fn contrast_ratio(a: Rgba, b: Rgba) -> f32 {\n    let (a, b) = (luminance(a), luminance(b));\n    (a.max(b) + 0.05) / (a.min(b) + 0.05)\n}\n\n/// The fill, hover fill and text of a button tinted with `tint`.\npub fn tint_colors(tint: Rgba, theme: &UiTheme) -> (Rgba, Rgba, Rgba) {\n    let fill = theme.opaque(tint);\n    let colors = theme.colors;\n    let foreground =\n        if contrast_ratio(fill, colors.foreground) >= contrast_ratio(fill, colors.background) {\n            colors.foreground\n        } else {\n            colors.background\n        };\n    let hover = fill.blend(foreground.opacity(0.14));\n    (fill, hover, foreground)\n}\n\n#[doc(hidden)]\npub fn style_tinted_button<\n    T: Styled + gpui_kit::InteractiveElement + gpui_kit::prelude::FluentBuilder,\n>(\n    base: T,\n    disabled: bool,\n    tint: Rgba,\n    size: ButtonSize,\n    theme: &UiTheme,\n) -> T {\n    style_button_with(\n        base,\n        disabled,\n        ButtonVariant::Default,\n        Some(tint),\n        size,\n        theme,\n    )\n}\n\nimpl gpui_kit::Styled for Button {\n    fn style(&mut self) -> &mut gpui_kit::StyleRefinement {\n        &mut self.style\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn tints_pick_readable_text_in_both_themes() {\n        let indigo = Rgba::try_from(\"#3f51b5\").unwrap();\n        let lime = Rgba::try_from(\"#cddc39\").unwrap();\n        for theme in [UiTheme::neutral_light(), UiTheme::neutral_dark()] {\n            for tint in [indigo, lime] {\n                let (fill, hover, text) = tint_colors(tint, &theme);\n                assert!(contrast_ratio(fill, text) >= 4.5, \"{tint:?} reads\");\n                assert_ne!(fill, hover);\n            }\n            let (_, _, text) = tint_colors(indigo, &theme);\n            assert!(luminance(text) > 0.5, \"indigo takes light text\");\n            let (_, _, text) = tint_colors(lime, &theme);\n            assert!(luminance(text) < 0.1, \"lime takes dark text\");\n        }\n    }\n\n    #[test]\n    fn all_variants_expose_clickable_and_disabled_cursors() {\n        for theme in [UiTheme::neutral_light(), UiTheme::neutral_dark()] {\n            for variant in [\n                ButtonVariant::Default,\n                ButtonVariant::Outline,\n                ButtonVariant::Secondary,\n                ButtonVariant::Ghost,\n                ButtonVariant::Destructive,\n                ButtonVariant::Link,\n                ButtonVariant::Sidebar,\n            ] {\n                for disabled in [false, true] {\n                    let mut button = style_button(\n                        gpui_kit::div(),\n                        disabled,\n                        variant,\n                        ButtonSize::Default,\n                        &theme,\n                    );\n                    assert_eq!(\n                        button.style().mouse_cursor,\n                        Some(if disabled {\n                            gpui_kit::CursorStyle::OperationNotAllowed\n                        } else {\n                            gpui_kit::CursorStyle::PointingHand\n                        })\n                    );\n                }\n            }\n        }\n    }\n\n    #[test]\n    fn nova_sizes_are_exact() {\n        let sizes = [\n            (ButtonSize::Xs, 24.0, 8.0, 4.0, 8.0),\n            (ButtonSize::Sm, 28.0, 10.0, 4.0, 8.0),\n            (ButtonSize::Default, 32.0, 10.0, 6.0, 10.0),\n            (ButtonSize::Lg, 36.0, 10.0, 6.0, 10.0),\n            (ButtonSize::IconXs, 24.0, 0.0, 0.0, 8.0),\n            (ButtonSize::IconSm, 28.0, 0.0, 0.0, 8.0),\n            (ButtonSize::Icon, 32.0, 0.0, 0.0, 10.0),\n            (ButtonSize::IconLg, 36.0, 0.0, 0.0, 10.0),\n        ];\n\n        for (size, height, padding, gap, radius) in sizes {\n            let metrics = size.metrics(UiRadius::new(px(10.0)));\n            assert_eq!(metrics.height, height);\n            assert_eq!(metrics.horizontal_padding, padding);\n            assert_eq!(metrics.gap, gap);\n            assert_eq!(metrics.radius, radius);\n        }\n    }\n}\n"
    },
    {
      "path": "registry/dialog/dialog.rs",
      "type": "registry:file",
      "target": "~/src/ui/dialog.rs",
      "content": "//! Nova modal surfaces using Kit's dialog host and caller-owned handles.\n#[path = \"modal_focus.rs\"]\n#[doc(hidden)]\npub mod modal_focus;\nuse super::{\n    button::{Button, ButtonSize, ButtonVariant},\n    theme::{\n        UiText, UiTheme,\n        locale::{self, DirectionalStyled as _},\n        presence,\n        primitives::{dismiss, surface, text},\n    },\n};\nuse gpui_icons::{LucideIcon, lucide};\npub use gpui_kit::base::{Dialog, DialogChangeReason, DialogHandle};\nuse gpui_kit::{\n    AnyElement, App, Div, ElementId, FontWeight, InteractiveElement as _, IntoElement, MouseButton,\n    ParentElement, SharedString, Stateful, StatefulInteractiveElement as _, Styled, Window, div,\n    px,\n};\n\n#[derive(Clone, Copy)]\n#[doc(hidden)]\npub enum DialogControlAction {\n    Cancel,\n    Confirm,\n}\n\n/// A styled dialog button that routes its action through its own dialog tree.\n#[derive(IntoElement)]\npub struct DialogControl {\n    button: Button,\n    action: DialogControlAction,\n    anchor_key: &'static str,\n    anchor_id: ElementId,\n}\n\nimpl DialogControl {\n    #[doc(hidden)]\n    pub fn new(\n        id: impl Into<ElementId>,\n        action: DialogControlAction,\n        anchor_key: &'static str,\n    ) -> Self {\n        let id = id.into();\n        Self {\n            button: Button::new(id.clone()),\n            action,\n            anchor_key,\n            anchor_id: id,\n        }\n    }\n\n    /// Sets the visual variant.\n    pub fn variant(mut self, variant: ButtonVariant) -> Self {\n        self.button = self.button.variant(variant);\n        self\n    }\n\n    /// Sets the visual size.\n    pub fn size(mut self, size: ButtonSize) -> Self {\n        self.button = self.button.size(size);\n        self\n    }\n\n    /// Prevents activation and removes the button from tab order.\n    pub fn disabled(mut self, disabled: bool) -> Self {\n        self.button = self.button.disabled(disabled);\n        self\n    }\n\n    /// Sets the accessible name for icon or custom content.\n    pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {\n        self.button = self.button.aria_label(label);\n        self\n    }\n\n    /// Adds visible text and uses it as the accessible name.\n    pub fn label(mut self, label: impl Into<SharedString>) -> Self {\n        self.button = self.button.label(label);\n        self\n    }\n}\n\nimpl ParentElement for DialogControl {\n    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {\n        self.button.extend(elements);\n    }\n}\n\nimpl Styled for DialogControl {\n    fn style(&mut self) -> &mut gpui_kit::StyleRefinement {\n        self.button.style()\n    }\n}\n\nimpl gpui_kit::RenderOnce for DialogControl {\n    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {\n        let anchor = window\n            .use_keyed_state((self.anchor_id, self.anchor_key), cx, |_, cx| {\n                cx.focus_handle()\n            })\n            .read(cx)\n            .clone();\n        let dispatch_from = anchor.clone();\n        let action = self.action;\n\n        self.button\n            .child(div().absolute().size_0().track_focus(&anchor))\n            .on_click(move |_, window, cx| match action {\n                DialogControlAction::Cancel => {\n                    dispatch_from.dispatch_action(&gpui_kit::base::actions::Cancel, window, cx)\n                }\n                DialogControlAction::Confirm => dispatch_from.dispatch_action(\n                    &gpui_kit::base::actions::Confirm { secondary: false },\n                    window,\n                    cx,\n                ),\n            })\n    }\n}\n\n/// Like [`dialog`], but builds the popup only while the dialog is open.\n///\n/// Keep the host mounted while closed so it can return focus; `build` runs\n/// only on frames where `handle` is open, so a closed dialog costs no more\n/// than its focus bookkeeping. Prefer this over [`dialog`] whenever the\n/// content takes work to build.\npub fn dialog_with<E: IntoElement>(\n    id: impl Into<ElementId>,\n    handle: &DialogHandle,\n    build: impl FnOnce(&mut Window, &mut App) -> E,\n    window: &mut Window,\n    cx: &mut App,\n) -> Dialog {\n    let popup = lazy_popup(handle, build, window, cx);\n    dialog(id, handle, popup, window, cx)\n}\n\n/// The popup `build` returns while `handle` is open, and an empty element\n/// while it is closed.\n#[doc(hidden)]\npub fn lazy_popup<E: IntoElement>(\n    handle: &DialogHandle,\n    build: impl FnOnce(&mut Window, &mut App) -> E,\n    window: &mut Window,\n    cx: &mut App,\n) -> gpui_kit::AnyElement {\n    if handle.is_open() {\n        build(window, cx).into_any_element()\n    } else {\n        div().into_any_element()\n    }\n}\n\n/// Keep the host mounted while closed so it can restore focus after dismissal.\n///\n/// The caller builds `popup` on every frame, open or closed; use\n/// [`dialog_with`] to build it only while the dialog is open.\npub fn dialog(\n    id: impl Into<ElementId>,\n    handle: &DialogHandle,\n    popup: impl IntoElement,\n    window: &mut Window,\n    cx: &mut App,\n) -> Dialog {\n    let id = id.into();\n    let open = handle.is_open();\n    let focus = modal_focus::prepare(id.clone(), open, window, cx);\n    let scope = modal_focus::ModalFocus::new(id.clone());\n    // Kit removes the popup when the handle closes, so only the entrance is\n    // animated: a fade with a short rise, as in shadcn's `zoom-in-95`.\n    let entrance = presence((id.clone(), \"presence\"), open, window, cx).progress;\n    let t = UiTheme::read(cx).clone();\n    let popup = dismiss::on_escape(scope.trap(div(), true), |window, cx| {\n        window.dispatch_action(Box::new(gpui_kit::base::actions::Cancel), cx);\n        true\n    })\n    .id(id.clone())\n    .track_focus(&focus)\n    // The popup sets its own width: `dialog_popup` caps it at 384 px, and a\n    // wider sheet overrides that with its own `max_w`.\n    .w_full()\n    .relative()\n    .top(t.space(2.) * (1. - entrance))\n    .opacity(entrance)\n    .child(scope.boundary(false))\n    .child(scope.boundary(true))\n    .child(modal_viewport((id.clone(), \"viewport\"), popup, window, cx));\n    Dialog::new(cx)\n        .handle(handle.clone())\n        .close_on_escape(false)\n        .flex()\n        .items_center()\n        .justify_center()\n        .p(t.space(4.))\n        .backdrop(dismiss_backdrop(cx).opacity(entrance))\n        .popup(popup)\n        // Enter in an arbitrary child must not dismiss an unfinished form.\n        .on_ok(|_, _, _| false)\n}\n/// Keeps a modal's full content reachable even in a short window.\n///\n/// The wheel reaches this viewport only through surfaces that use\n/// `block_mouse_except_scroll()`, as `dialog_popup` does; a custom surface\n/// that calls `occlude()` hides the wheel from it and stays clipped.\n#[doc(hidden)]\npub fn modal_viewport(\n    id: impl Into<ElementId>,\n    popup: impl IntoElement,\n    window: &Window,\n    cx: &App,\n) -> Stateful<Div> {\n    div()\n        .id(id)\n        .max_h((window.viewport_size().height - UiTheme::read(cx).space(8.)).max(px(0.)))\n        .overflow_y_scroll()\n        .w_full()\n        .flex()\n        .flex_col()\n        .items_center()\n        .child(popup)\n}\n\n/// A keyboard-accessible button opening the caller's handle.\npub fn dialog_trigger(id: impl Into<ElementId>, handle: &DialogHandle) -> Button {\n    let handle = handle.clone();\n    Button::new(id)\n        .variant(ButtonVariant::Outline)\n        .on_click(move |_, window, cx| handle.open(window, cx))\n}\n/// Full-window modal backdrop.\npub fn dialog_backdrop(cx: &App) -> Div {\n    div()\n        .absolute()\n        .inset_0()\n        .bg(UiTheme::read(cx).colors.overlay)\n        .occlude()\n}\n/// A backdrop that dismisses its dialog when pressed. The occluding backdrop\n/// hides the press from Kit's host, so it routes Cancel through the dialog's\n/// veto callback itself.\n#[doc(hidden)]\npub fn dismiss_backdrop(cx: &App) -> Div {\n    dialog_backdrop(cx).on_mouse_down(MouseButton::Left, |_, window, cx| {\n        window.dispatch_action(Box::new(gpui_kit::base::actions::Cancel), cx);\n        cx.stop_propagation();\n    })\n}\n/// Stacked dialog heading content.\npub fn dialog_header(cx: &App) -> Div {\n    div().flex().flex_col().gap(UiTheme::read(cx).space(2.))\n}\n/// Inset action footer.\npub fn dialog_footer(cx: &App) -> Div {\n    let t = UiTheme::read(cx);\n    div()\n        .mx(-t.space(4.))\n        .mb(-t.space(4.))\n        .flex_row_in(t.direction)\n        .justify_end()\n        .gap(t.space(2.))\n        .rounded_b(t.radius.xl)\n        .border_t_1()\n        .border_color(t.colors.border)\n        .bg(t.colors.muted.opacity(0.5))\n        .p(t.space(4.))\n}\n/// Named popup surface with modal Tab traversal, including caller-owned inputs.\n///\n/// It is at most 384 px wide; call `.max_w(..)` on it for a wider sheet.\npub fn dialog_popup(\n    id: impl Into<ElementId>,\n    label: impl Into<SharedString>,\n    cx: &App,\n) -> Stateful<Div> {\n    let t = UiTheme::read(cx);\n    let id = id.into();\n    let popup = div()\n        .id(id)\n        .aria_label(label)\n        // Blocks clicks and hover behind the surface but lets the wheel reach\n        // the host's `modal_viewport`, which `occlude` would hide it from.\n        .block_mouse_except_scroll()\n        .w_full()\n        .min_w(px(0.))\n        .max_w(t.space(96.))\n        .flex()\n        .flex_col()\n        .gap(t.space(4.))\n        .p(t.space(4.));\n    // The host's viewport scrolls a tall dialog; the surface itself never does,\n    // so there is one scroll container and the footer stays with the content.\n    surface::modal(popup, t)\n}\n/// Medium-weight dialog title.\npub fn dialog_title(id: impl Into<ElementId>, cx: &App) -> Stateful<Div> {\n    let t = UiTheme::read(cx);\n    div()\n        .id(id)\n        .role(gpui_kit::Role::Heading)\n        .aria_level(2)\n        .font_family(t.fonts.heading.clone())\n        .font_weight(FontWeight::MEDIUM)\n        .text_size(t.text(16.))\n        .line_height(text::line_height(t, t.text(16.)))\n        .text_color(t.colors.popover_foreground)\n}\n/// Muted dialog description.\npub fn dialog_description(id: impl Into<ElementId>, cx: &App) -> Stateful<Div> {\n    let t = UiTheme::read(cx);\n    text::muted(div().id(id), t)\n}\n/// Icon-only close control; Kit routes Cancel through the owning dialog's veto callback.\npub fn dialog_close(id: impl Into<ElementId>, cx: &App) -> DialogControl {\n    let t = UiTheme::read(cx);\n    DialogControl::new(\n        id,\n        DialogControlAction::Cancel,\n        \"gpuicn-dialog-close-anchor\",\n    )\n    .aria_label(locale::text(cx, UiText::Close))\n    .variant(ButtonVariant::Ghost)\n    .size(ButtonSize::IconSm)\n    .absolute()\n    .top(t.space(2.))\n    .inset_end(t.direction, t.space(2.))\n    .child(\n        lucide(LucideIcon::X)\n            .size(t.space(4.))\n            .text_color(t.colors.popover_foreground),\n    )\n}\n/// Create form actions with `Button`; close the handle after successful validation.\npub fn dialog_action(id: impl Into<ElementId>, handle: &DialogHandle) -> Button {\n    let handle = handle.clone();\n    Button::new(id).on_click(move |_, window, cx| handle.close(window, cx))\n}\n\n#[cfg(test)]\nmod tests {\n    use std::{cell::Cell, rc::Rc};\n\n    use gpui_kit::{\n        Context, FocusHandle, Render, TestAppContext, point, prelude::FluentBuilder as _,\n    };\n\n    use super::*;\n\n    struct DialogControlHarness {\n        dialog_focus: FocusHandle,\n        retained_focus: FocusHandle,\n        handle: DialogHandle,\n        cancel_count: Rc<Cell<usize>>,\n    }\n\n    impl Render for DialogControlHarness {\n        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {\n            let cancel_count = self.cancel_count.clone();\n            div()\n                .child(div().absolute().size_0().track_focus(&self.retained_focus))\n                .child(\n                    Dialog::new(cx)\n                        .handle(self.handle.clone())\n                        .focus_handle(self.dialog_focus.clone())\n                        .on_cancel(move |_, _, _| {\n                            cancel_count.set(cancel_count.get() + 1);\n                            true\n                        })\n                        .popup(\n                            DialogControl::new(\n                                \"cancel\",\n                                DialogControlAction::Cancel,\n                                \"dialog-control-test-anchor\",\n                            )\n                            .size_full()\n                            .label(\"Cancel\"),\n                        ),\n                )\n        }\n    }\n\n    #[gpui_kit::test]\n    fn dialog_control_routes_from_its_own_anchor(cx: &mut TestAppContext) {\n        cx.update(super::super::theme::init);\n        let handle = DialogHandle::new(true);\n        let cancel_count = Rc::new(Cell::new(0));\n        let (view, cx) = cx.add_window_view({\n            let handle = handle.clone();\n            let cancel_count = cancel_count.clone();\n            move |_, cx| DialogControlHarness {\n                dialog_focus: cx.focus_handle(),\n                retained_focus: cx.focus_handle(),\n                handle,\n                cancel_count,\n            }\n        });\n        cx.update(|window, cx| {\n            let retained_focus = view.read(cx).retained_focus.clone();\n            retained_focus.focus(window, cx);\n            window.draw(cx).clear(cx);\n        });\n\n        cx.simulate_click(point(px(20.), px(20.)), Default::default());\n        cx.run_until_parked();\n\n        assert_eq!(cancel_count.get(), 1);\n        assert!(!handle.is_open());\n    }\n\n    struct TwoDialogControlHarness {\n        first_focus: FocusHandle,\n        second_focus: FocusHandle,\n        first_handle: DialogHandle,\n        second_handle: DialogHandle,\n        first_count: Rc<Cell<usize>>,\n        second_count: Rc<Cell<usize>>,\n    }\n\n    impl Render for TwoDialogControlHarness {\n        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {\n            let first_count = self.first_count.clone();\n            let second_count = self.second_count.clone();\n            div()\n                .child(\n                    Dialog::new(cx)\n                        .handle(self.first_handle.clone())\n                        .focus_handle(self.first_focus.clone())\n                        .on_cancel(move |_, _, _| {\n                            first_count.set(first_count.get() + 1);\n                            true\n                        })\n                        .popup(\n                            DialogControl::new(\n                                \"first-cancel\",\n                                DialogControlAction::Cancel,\n                                \"shared-dialog-control-anchor\",\n                            )\n                            .absolute()\n                            .left_0()\n                            .top_0()\n                            .w(px(40.))\n                            .h(px(40.))\n                            .label(\"First\"),\n                        ),\n                )\n                .child(\n                    Dialog::new(cx)\n                        .handle(self.second_handle.clone())\n                        .focus_handle(self.second_focus.clone())\n                        .on_cancel(move |_, _, _| {\n                            second_count.set(second_count.get() + 1);\n                            true\n                        })\n                        .popup(\n                            DialogControl::new(\n                                \"second-cancel\",\n                                DialogControlAction::Cancel,\n                                \"shared-dialog-control-anchor\",\n                            )\n                            .absolute()\n                            .left(px(60.))\n                            .top_0()\n                            .w(px(40.))\n                            .h(px(40.))\n                            .label(\"Second\"),\n                        ),\n                )\n        }\n    }\n\n    #[gpui_kit::test]\n    fn dialog_controls_keep_distinct_anchors_in_one_window(cx: &mut TestAppContext) {\n        cx.update(super::super::theme::init);\n        let first_handle = DialogHandle::new(true);\n        let second_handle = DialogHandle::new(true);\n        let first_count = Rc::new(Cell::new(0));\n        let second_count = Rc::new(Cell::new(0));\n        let (_, cx) = cx.add_window_view({\n            let first_handle = first_handle.clone();\n            let second_handle = second_handle.clone();\n            let first_count = first_count.clone();\n            let second_count = second_count.clone();\n            move |_, cx| TwoDialogControlHarness {\n                first_focus: cx.focus_handle(),\n                second_focus: cx.focus_handle(),\n                first_handle,\n                second_handle,\n                first_count,\n                second_count,\n            }\n        });\n        cx.update(|window, cx| window.draw(cx).clear(cx));\n\n        cx.simulate_click(point(px(80.), px(20.)), Default::default());\n        cx.run_until_parked();\n\n        assert_eq!(first_count.get(), 0);\n        assert_eq!(second_count.get(), 1);\n        assert!(first_handle.is_open());\n        assert!(!second_handle.is_open());\n    }\n\n    struct TallDialog {\n        handle: DialogHandle,\n    }\n\n    impl Render for TallDialog {\n        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {\n            let popup = dialog_popup(\"tall-popup\", \"Preferences\", cx)\n                .child(div().h(px(1200.)).flex_shrink_0().child(\"Settings\"))\n                .child(\n                    div()\n                        .h(px(32.))\n                        .flex_shrink_0()\n                        .debug_selector(|| \"tall-footer\".into())\n                        .child(\"Save\"),\n                );\n            div()\n                .size_full()\n                .child(\n                    div().id(\"page\").size_full().overflow_y_scroll().child(\n                        div()\n                            .h(px(4000.))\n                            .debug_selector(|| \"page-content\".into())\n                            .child(\"Page\"),\n                    ),\n                )\n                .child(dialog(\"tall\", &self.handle, popup, window, cx))\n        }\n    }\n\n    #[gpui_kit::test]\n    fn a_tall_dialog_scrolls_under_the_pointer(cx: &mut TestAppContext) {\n        use gpui_kit::{ScrollDelta, ScrollEvent};\n        cx.update(super::super::theme::init);\n        let handle = DialogHandle::new(true);\n        let (_, cx) = cx.add_window_view({\n            let handle = handle.clone();\n            move |_, _| TallDialog { handle }\n        });\n        cx.update(|window, cx| window.draw(cx).clear(cx));\n        let viewport = cx.update(|window, _| window.viewport_size());\n        let footer = cx.debug_bounds(\"tall-footer\").unwrap();\n        assert!(\n            footer.bottom() > viewport.height,\n            \"the footer starts below the fold\"\n        );\n\n        let page = cx.debug_bounds(\"page-content\").unwrap();\n        let center = point(viewport.width / 2., viewport.height / 2.);\n        cx.simulate_mouse_move(center, None, Default::default());\n        cx.simulate_event(ScrollEvent {\n            position: center,\n            delta: ScrollDelta::Pixels(point(px(0.), px(-1400.))),\n            ..Default::default()\n        });\n        cx.update(|window, cx| window.draw(cx).clear(cx));\n        let footer = cx.debug_bounds(\"tall-footer\").unwrap();\n        assert!(\n            footer.bottom() <= viewport.height,\n            \"the wheel over the surface scrolls the dialog: footer at {footer:?}\"\n        );\n        assert_eq!(\n            cx.debug_bounds(\"page-content\").unwrap(),\n            page,\n            \"the backdrop keeps the wheel from the page behind the dialog\"\n        );\n    }\n\n    struct SizedDialog {\n        handle: DialogHandle,\n        width: Option<f32>,\n    }\n\n    impl Render for SizedDialog {\n        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {\n            let popup = dialog_popup(\"sized-popup\", \"Accounts\", cx)\n                .debug_selector(|| \"sized-popup\".into())\n                .when_some(self.width, |popup, width| popup.max_w(px(width)));\n            div()\n                .size_full()\n                .child(dialog(\"sized\", &self.handle, popup, window, cx))\n        }\n    }\n\n    #[gpui_kit::test]\n    fn a_popup_sets_its_own_width_and_stays_centered(cx: &mut TestAppContext) {\n        cx.update(super::super::theme::init);\n        for (width, expected) in [(None, 384.), (Some(560.), 560.)] {\n            let handle = DialogHandle::new(true);\n            let (_, cx) = cx.add_window_view(move |_, _| SizedDialog { handle, width });\n            cx.update(|window, cx| window.draw(cx).clear(cx));\n            let viewport = cx.update(|window, _| window.viewport_size());\n            let popup = cx.debug_bounds(\"sized-popup\").unwrap();\n            assert_eq!(popup.size.width, px(expected));\n            assert_eq!(popup.center().x, viewport.width / 2.);\n        }\n    }\n\n    struct LazyDialog {\n        handle: DialogHandle,\n        builds: Rc<Cell<usize>>,\n    }\n\n    impl Render for LazyDialog {\n        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {\n            let builds = self.builds.clone();\n            div().size_full().child(dialog_with(\n                \"lazy\",\n                &self.handle,\n                move |_, cx| {\n                    builds.set(builds.get() + 1);\n                    dialog_popup(\"lazy-popup\", \"Settings\", cx)\n                },\n                window,\n                cx,\n            ))\n        }\n    }\n\n    #[gpui_kit::test]\n    fn dialog_with_builds_only_while_open(cx: &mut TestAppContext) {\n        cx.update(super::super::theme::init);\n        let handle = DialogHandle::new(false);\n        let builds = Rc::new(Cell::new(0));\n        let (_, cx) = cx.add_window_view({\n            let handle = handle.clone();\n            let builds = builds.clone();\n            move |_, _| LazyDialog { handle, builds }\n        });\n        cx.update(|window, cx| window.draw(cx).clear(cx));\n        cx.update(|window, cx| window.draw(cx).clear(cx));\n        assert_eq!(builds.get(), 0, \"a closed dialog builds nothing\");\n        cx.update(|window, cx| handle.open(window, cx));\n        cx.update(|window, cx| window.draw(cx).clear(cx));\n        assert!(builds.get() > 0, \"an open dialog builds its popup\");\n    }\n}\n"
    },
    {
      "path": "registry/dialog/modal_focus.rs",
      "type": "registry:file",
      "target": "~/src/ui/modal_focus.rs",
      "content": "//! Modal focus entry, traversal and restoration for Kit hosts.\nuse gpui_kit::{\n    App, Div, ElementId, FocusHandle, InteractiveElement as _, IntoElement, RenderOnce,\n    SharedString, Styled, Window, div, px,\n};\nuse std::{\n    cell::{Cell, RefCell},\n    rc::Rc,\n    sync::Arc,\n};\n\nstruct FocusState {\n    open: bool,\n    popup: FocusHandle,\n    return_to: Option<FocusHandle>,\n}\n#[doc(hidden)]\npub fn prepare(id: ElementId, open: bool, window: &mut Window, cx: &mut App) -> FocusHandle {\n    let state = window.use_keyed_state((id, \"modal-focus\"), cx, |_, cx| FocusState {\n        open: false,\n        popup: cx.focus_handle(),\n        return_to: None,\n    });\n    state.update(cx, |state, cx| {\n        if open && !state.open {\n            state.return_to = window.focused(cx);\n            state.popup.focus(window, cx);\n        } else if !open && state.open {\n            if (state.popup.contains_focused(window, cx) || window.focused(cx).is_none())\n                && let Some(previous) = state.return_to.take()\n            {\n                previous.focus(window, cx);\n            }\n            state.return_to = None;\n        }\n        state.open = open;\n        state.popup.clone()\n    })\n}\n\n#[derive(Clone)]\n#[doc(hidden)]\npub struct ModalFocus {\n    id: ElementId,\n    enabled: Rc<Cell<bool>>,\n    handles: Rc<RefCell<[Option<FocusHandle>; 2]>>,\n}\n\nimpl ModalFocus {\n    #[doc(hidden)]\n    pub fn new(id: ElementId) -> Self {\n        Self {\n            id,\n            enabled: Rc::default(),\n            handles: Rc::default(),\n        }\n    }\n\n    #[doc(hidden)]\n    pub fn boundary(&self, end: bool) -> impl IntoElement {\n        Boundary {\n            scope: self.clone(),\n            end,\n        }\n    }\n\n    #[doc(hidden)]\n    pub fn trap(&self, base: Div, enabled: bool) -> Div {\n        self.enabled.set(enabled);\n        if !enabled {\n            return base;\n        }\n        let next = self.clone();\n        let previous = self.clone();\n        base.tab_group()\n            .capture_action(move |_: &super::super::theme::FocusNext, window, cx| {\n                next.advance(false, window, cx)\n            })\n            .capture_action(move |_: &super::super::theme::FocusPrevious, window, cx| {\n                previous.advance(true, window, cx)\n            })\n    }\n\n    fn advance(&self, reverse: bool, window: &mut Window, cx: &mut App) {\n        let [Some(start), Some(end)] = self.handles.borrow().clone() else {\n            return;\n        };\n        let original = window.focused(cx);\n        if reverse {\n            // The initially focused popup is the ancestor of both boundaries.\n            // Enter from the end without focusing anything behind the modal.\n            if start.within_focused(window, cx) {\n                end.focus(window, cx);\n            }\n            window.focus_prev(cx);\n            if start.is_focused(window) {\n                end.focus(window, cx);\n                window.focus_prev(cx);\n            }\n        } else {\n            window.focus_next(cx);\n            if start.is_focused(window) {\n                window.focus_next(cx);\n            }\n            if end.is_focused(window) {\n                start.focus(window, cx);\n                window.focus_next(cx);\n            }\n        }\n        if (start.is_focused(window) || end.is_focused(window))\n            && let Some(original) = original\n        {\n            original.focus(window, cx);\n        }\n        window.prevent_default();\n        cx.stop_propagation();\n    }\n}\n\n#[derive(IntoElement)]\nstruct Boundary {\n    scope: ModalFocus,\n    end: bool,\n}\n\nimpl RenderOnce for Boundary {\n    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {\n        let index = usize::from(self.end);\n        let id = ElementId::NamedChild(\n            Arc::new(self.scope.id),\n            SharedString::from(if self.end { \"tab-end\" } else { \"tab-start\" }),\n        );\n        let handle = window\n            .use_keyed_state(id.clone(), cx, |_, cx| cx.focus_handle())\n            .read(cx)\n            .clone();\n        self.scope.handles.borrow_mut()[index] = Some(handle.clone());\n        // Out of layout and role-less. The end's group index follows all normal\n        // controls, including custom positive tab indices, although both boundaries are inserted first.\n        div().id(id).absolute().size(px(0.)).track_focus(\n            &handle\n                .tab_stop(self.scope.enabled.get())\n                .tab_index(if self.end { isize::MAX } else { 0 }),\n        )\n    }\n}\n"
    },
    {
      "path": "registry/input/input.rs",
      "type": "registry:file",
      "target": "~/src/ui/input.rs",
      "content": "//! Nova presentation for GPUI Kit's single-line and multi-line editing states.\n\nuse std::ops::Range;\nuse std::rc::Rc;\n\nuse super::theme::{\n    UiText, UiTheme, locale,\n    primitives::{control, disabled, focus},\n};\npub use gpui_kit::base::input::{InputEvent, InputState, TextareaState};\nuse gpui_kit::base::{\n    InputBase,\n    input::{InputBaseState, InputEditorStyle, InputModeKind},\n};\nuse gpui_kit::component::native_menu::NativeMenu;\nuse gpui_kit::{\n    AccessibleAction, App, ClipboardItem, ContentMask, Context, ElementId, Entity,\n    EntityInputHandler as _, EventEmitter, FocusHandle, Focusable as _, InteractiveElement as _,\n    IntoElement, MouseButton, ParentElement as _, RenderOnce, SharedString,\n    StatefulInteractiveElement as _, Styled, Subscription, UnderlineStyle, Window, canvas, point,\n    prelude::FluentBuilder as _, px,\n};\n\ntype PasteHandler = Rc<dyn Fn(&ClipboardItem, &mut Window, &mut App) -> bool>;\n\n/// The caller owns the editing state, focus and event subscriptions.\n#[derive(IntoElement)]\npub struct Input {\n    state: Entity<InputState>,\n    style: gpui_kit::StyleRefinement,\n    label: Option<SharedString>,\n    disabled: bool,\n    read_only: bool,\n    invalid: bool,\n    bordered: bool,\n    paste_handler: Option<PasteHandler>,\n}\n\n/// Nova presentation for GPUI Kit's ordinary multi-line editing state.\n#[derive(IntoElement)]\npub struct Textarea {\n    state: Entity<TextareaState>,\n    style: gpui_kit::StyleRefinement,\n    label: Option<SharedString>,\n    disabled: bool,\n    read_only: bool,\n    invalid: bool,\n    bordered: bool,\n    paste_handler: Option<PasteHandler>,\n    misspellings: Option<Entity<Misspellings>>,\n}\n\n/// Replaces a misspelled range with a suggestion in one undoable edit.\n///\n/// `SpellingMenu::suggestion` adds menu items that dispatch it; a textarea\n/// showing `Misspellings` handles it.\n#[derive(Clone, PartialEq, Debug, gpui_kit::Action)]\n#[action(namespace = gpuicn, no_json)]\npub struct ReplaceMisspelling {\n    /// The byte range to replace.\n    pub range: Range<usize>,\n    /// The replacement text.\n    pub text: SharedString,\n}\n\ntype SpellingMenuHandler = Rc<dyn Fn(&mut SpellingMenu, &mut Window, &mut App)>;\n\n/// Misspelled byte ranges in a textarea, drawn as wavy underlines.\n///\n/// The application checks the spelling itself, with the platform's checker,\n/// and passes the ranges to `set` a moment after typing stops. Edits shift\n/// the ranges after them and drop the ones they touch, so no underline sits\n/// on the wrong text before fresh ranges arrive. Attach it with\n/// `Textarea::misspellings`; `ComposerState` has one built in.\npub struct Misspellings {\n    input: Entity<TextareaState>,\n    ranges: Vec<Range<usize>>,\n    text: SharedString,\n    menu: Option<SpellingMenuHandler>,\n    _subscription: Subscription,\n}\n\n/// Notifications from `Misspellings`.\n#[derive(Clone, Debug, PartialEq)]\npub enum MisspellingsEvent {\n    /// A suggestion replaced a misspelled range.\n    Replaced {\n        /// The range that was replaced, in the text before the edit.\n        range: Range<usize>,\n        /// The text that replaced it.\n        text: SharedString,\n    },\n}\n\nimpl EventEmitter<MisspellingsEvent> for Misspellings {}\n\nimpl Misspellings {\n    /// Tracks misspellings for `input`.\n    pub fn new(input: &Entity<TextareaState>, cx: &mut Context<Self>) -> Self {\n        let subscription = cx.subscribe(input, |this, input, event, cx| {\n            if let InputEvent::Change = event {\n                let text = input.read(cx).value();\n                this.follow_edit(&text);\n                this.text = text;\n                cx.notify();\n            }\n        });\n        Self {\n            text: input.read(cx).value(),\n            input: input.clone(),\n            ranges: Vec::new(),\n            menu: None,\n            _subscription: subscription,\n        }\n    }\n\n    /// Replaces the misspelled ranges: byte offsets into the current value.\n    /// Ranges outside the text or off character boundaries are dropped.\n    pub fn set(&mut self, ranges: impl IntoIterator<Item = Range<usize>>, cx: &mut Context<Self>) {\n        let text = self.input.read(cx).value();\n        let mut ranges: Vec<_> = ranges\n            .into_iter()\n            .filter(|range| {\n                range.start < range.end\n                    && text.is_char_boundary(range.start)\n                    && text.is_char_boundary(range.end)\n            })\n            .collect();\n        ranges.sort_by_key(|range| range.start);\n        self.ranges = ranges;\n        self.text = text;\n        cx.notify();\n    }\n\n    /// The current misspelled ranges, in order.\n    pub fn ranges(&self) -> &[Range<usize>] {\n        &self.ranges\n    }\n\n    /// The misspelled range at byte `offset`, its ends included.\n    pub fn range_at(&self, offset: usize) -> Option<Range<usize>> {\n        self.ranges\n            .iter()\n            .find(|range| range.start <= offset && offset <= range.end)\n            .cloned()\n    }\n\n    /// Builds the menu for a right-click inside a misspelled range. Its items\n    /// go above Cut, Copy, Paste and Select All; a right-click elsewhere shows\n    /// only those.\n    pub fn on_menu(\n        &mut self,\n        handler: impl Fn(&mut SpellingMenu, &mut Window, &mut App) + 'static,\n    ) {\n        self.menu = Some(Rc::new(handler));\n    }\n\n    /// Replaces `range` with `text` as one undoable edit and selects nothing,\n    /// leaving the caret after it.\n    pub fn replace(\n        &mut self,\n        range: Range<usize>,\n        text: impl Into<SharedString>,\n        window: &mut Window,\n        cx: &mut Context<Self>,\n    ) {\n        let text = text.into();\n        let value = self.input.read(cx).value();\n        if range.end > value.len()\n            || !value.is_char_boundary(range.start)\n            || !value.is_char_boundary(range.end)\n        {\n            return;\n        }\n        let replacement = text.clone();\n        self.input.update(cx, |input, cx| {\n            input.set_selected_range(range.clone(), cx);\n            input.replace(replacement, window, cx);\n        });\n        cx.emit(MisspellingsEvent::Replaced { range, text });\n    }\n\n    /// Moves the ranges after an edit and drops the ranges it touched.\n    fn follow_edit(&mut self, new: &str) {\n        let old = self.text.as_ref();\n        if old == new || self.ranges.is_empty() {\n            return;\n        }\n        let prefix = old\n            .char_indices()\n            .zip(new.chars())\n            .find(|((_, a), b)| a != b)\n            .map_or(old.len().min(new.len()), |((index, _), _)| index);\n        let suffix = old[prefix..]\n            .chars()\n            .rev()\n            .zip(new[prefix..].chars().rev())\n            .take_while(|(a, b)| a == b)\n            .map(|(a, _)| a.len_utf8())\n            .sum::<usize>();\n        let removed = prefix..old.len() - suffix;\n        let inserted = new.len() - suffix - prefix;\n        self.ranges.retain_mut(|range| {\n            if range.end < removed.start || (range.end == removed.start && inserted == 0) {\n                true\n            } else if range.start > removed.end\n                || (range.start == removed.end && removed.end > removed.start)\n            {\n                range.start = range.start - removed.len() + inserted;\n                range.end = range.end - removed.len() + inserted;\n                true\n            } else {\n                false\n            }\n        });\n    }\n}\n\n/// The items a right-click on a misspelled word adds above Cut, Copy and\n/// Paste: suggestions, then the application's own actions such as\n/// \"Ignore\" or \"Add to dictionary\".\npub struct SpellingMenu {\n    range: Range<usize>,\n    word: SharedString,\n    menu: NativeMenu,\n}\n\nimpl SpellingMenu {\n    /// The misspelled byte range under the pointer.\n    pub fn range(&self) -> Range<usize> {\n        self.range.clone()\n    }\n    /// The misspelled word.\n    pub fn word(&self) -> &SharedString {\n        &self.word\n    }\n    /// Adds a suggestion; choosing it replaces the word in one undoable edit.\n    pub fn suggestion(&mut self, text: impl Into<SharedString>) -> &mut Self {\n        let text = text.into();\n        let action = ReplaceMisspelling {\n            range: self.range.clone(),\n            text: text.clone(),\n        };\n        self.push(|menu| menu.menu(text, Box::new(action)));\n        self\n    }\n    /// Adds an item that dispatches the application's own action.\n    pub fn item(\n        &mut self,\n        label: impl Into<SharedString>,\n        action: Box<dyn gpui_kit::Action>,\n    ) -> &mut Self {\n        let label = label.into();\n        self.push(|menu| menu.menu(label, action));\n        self\n    }\n    /// Adds a separator line.\n    pub fn separator(&mut self) -> &mut Self {\n        self.push(NativeMenu::separator);\n        self\n    }\n    fn push(&mut self, add: impl FnOnce(NativeMenu) -> NativeMenu) {\n        self.menu = add(std::mem::take(&mut self.menu));\n    }\n}\n\n/// Cut, Copy, Paste and Select All, after `menu`'s own items.\nfn edit_menu(menu: NativeMenu, copyable: bool, editable: bool, cx: &App) -> NativeMenu {\n    let menu = if menu.is_empty() {\n        menu\n    } else {\n        menu.separator()\n    };\n    menu.menu_with_disabled(\n        locale::text(cx, UiText::Cut),\n        !(editable && copyable),\n        Box::new(gpui_kit::base::input::Cut),\n    )\n    .menu_with_disabled(\n        locale::text(cx, UiText::Copy),\n        !copyable,\n        Box::new(gpui_kit::base::input::Copy),\n    )\n    .menu_with_disabled(\n        locale::text(cx, UiText::Paste),\n        !editable,\n        Box::new(gpui_kit::base::input::Paste),\n    )\n    .separator()\n    .menu(\n        locale::text(cx, UiText::SelectAll),\n        Box::new(gpui_kit::base::input::SelectAll),\n    )\n}\n\n/// Paints a 1px wavy underline under each misspelled range that is laid out.\nfn misspelling_underlines(\n    input: Entity<TextareaState>,\n    misspellings: Entity<Misspellings>,\n    theme: &UiTheme,\n) -> impl IntoElement {\n    let color = theme.colors.destructive;\n    canvas(\n        |_, _, _| {},\n        move |bounds, _, window, cx| {\n            let input = input.read(cx);\n            let style = UnderlineStyle {\n                thickness: px(1.),\n                color: Some(color.into()),\n                wavy: true,\n            };\n            window.with_content_mask(Some(ContentMask { bounds }), |window| {\n                for range in misspellings.read(cx).ranges() {\n                    let Some(word) = input.range_to_bounds(range) else {\n                        continue;\n                    };\n                    let line = input.line_height().unwrap_or(px(20.));\n                    // A word that wraps onto the next line has no single box.\n                    if word.size.height > line * 1.5 || word.size.width <= px(0.) {\n                        continue;\n                    }\n                    let origin = point(word.left(), word.bottom() - px(3.));\n                    window.paint_underline(origin, word.size.width, &style);\n                }\n            });\n        },\n    )\n    .absolute()\n    .inset_0()\n}\n\nimpl Textarea {\n    /// Creates a Nova textarea using the caller's retained Kit editing state.\n    pub fn new(state: &Entity<TextareaState>) -> Self {\n        Self {\n            state: state.clone(),\n            style: Default::default(),\n            label: None,\n            disabled: false,\n            read_only: false,\n            invalid: false,\n            bordered: true,\n            paste_handler: None,\n            misspellings: None,\n        }\n    }\n    /// Underlines the ranges in `misspellings` with a wavy destructive line\n    /// and adds its spelling items, then Cut, Copy, Paste and Select All, to\n    /// the right-click menu.\n    pub fn misspellings(mut self, misspellings: &Entity<Misspellings>) -> Self {\n        self.misspellings = Some(misspellings.clone());\n        self\n    }\n    /// Sets the accessible name of the control.\n    pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {\n        self.label = Some(label.into());\n        self\n    }\n    /// Disables interaction and applies the disabled appearance.\n    pub fn disabled(mut self, value: bool) -> Self {\n        self.disabled = value;\n        self\n    }\n    /// Prevents user changes while preserving focus and reading.\n    pub fn read_only(mut self, value: bool) -> Self {\n        self.read_only = value;\n        self\n    }\n    /// Applies validation error colors and an invalid accessibility description.\n    pub fn invalid(mut self, value: bool) -> Self {\n        self.invalid = value;\n        self\n    }\n    /// Controls the Nova textarea border and background.\n    pub fn bordered(mut self, value: bool) -> Self {\n        self.bordered = value;\n        self\n    }\n    /// Intercepts native clipboard payloads before the default text insertion.\n    /// Returning `true` consumes the paste; `false` keeps normal text paste.\n    /// Browser image/file paste needs async clipboard permission and is not\n    /// available through this synchronous hook.\n    pub fn on_paste(\n        mut self,\n        handler: impl Fn(&ClipboardItem, &mut Window, &mut App) -> bool + 'static,\n    ) -> Self {\n        self.paste_handler = Some(Rc::new(handler));\n        self\n    }\n    #[doc(hidden)]\n    pub fn is_disabled(&self) -> bool {\n        self.disabled\n    }\n    #[doc(hidden)]\n    pub fn is_read_only(&self) -> bool {\n        self.read_only\n    }\n    #[doc(hidden)]\n    pub fn is_invalid(&self) -> bool {\n        self.invalid\n    }\n    #[doc(hidden)]\n    pub fn field_focus_handle(&self, cx: &App) -> FocusHandle {\n        self.state.read(cx).focus_handle(cx)\n    }\n}\n\nimpl Styled for Textarea {\n    fn style(&mut self) -> &mut gpui_kit::StyleRefinement {\n        &mut self.style\n    }\n}\nimpl Input {\n    /// Creates a Nova input using the caller's retained Kit editing state.\n    pub fn new(state: &Entity<InputState>) -> Self {\n        Self {\n            state: state.clone(),\n            style: Default::default(),\n            label: None,\n            disabled: false,\n            read_only: false,\n            invalid: false,\n            bordered: true,\n            paste_handler: None,\n        }\n    }\n    /// Sets the accessible name of the control.\n    pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {\n        self.label = Some(label.into());\n        self\n    }\n    /// Disables interaction and applies the disabled appearance.\n    pub fn disabled(mut self, value: bool) -> Self {\n        self.disabled = value;\n        self\n    }\n    /// Prevents user changes while preserving focus and reading.\n    pub fn read_only(mut self, value: bool) -> Self {\n        self.read_only = value;\n        self\n    }\n    /// Applies validation error colors and an invalid accessibility description.\n    pub fn invalid(mut self, value: bool) -> Self {\n        self.invalid = value;\n        self\n    }\n    /// Controls the Nova input border and background.\n    pub fn bordered(mut self, value: bool) -> Self {\n        self.bordered = value;\n        self\n    }\n    /// Intercepts native clipboard payloads before the default text insertion.\n    /// Returning `true` consumes the paste; `false` keeps normal text paste.\n    /// Browser image/file paste needs async clipboard permission and is not\n    /// available through this synchronous hook.\n    pub fn on_paste(\n        mut self,\n        handler: impl Fn(&ClipboardItem, &mut Window, &mut App) -> bool + 'static,\n    ) -> Self {\n        self.paste_handler = Some(Rc::new(handler));\n        self\n    }\n    #[doc(hidden)]\n    pub fn is_disabled(&self) -> bool {\n        self.disabled\n    }\n    #[doc(hidden)]\n    pub fn is_read_only(&self) -> bool {\n        self.read_only\n    }\n    #[doc(hidden)]\n    pub fn is_invalid(&self) -> bool {\n        self.invalid\n    }\n    #[doc(hidden)]\n    pub fn field_focus_handle(&self, cx: &App) -> FocusHandle {\n        self.state.read(cx).focus_handle(cx)\n    }\n}\nimpl Styled for Input {\n    fn style(&mut self) -> &mut gpui_kit::StyleRefinement {\n        &mut self.style\n    }\n}\nimpl RenderOnce for Input {\n    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {\n        let theme = UiTheme::read(cx).clone();\n        let core = InputCore {\n            label: self.label,\n            disabled: self.disabled,\n            read_only: self.read_only,\n            invalid: self.invalid,\n            bordered: self.bordered,\n            paste_handler: self.paste_handler,\n        };\n        let root = core\n            .render(\"input\", self.state, &theme, window, cx)\n            .h(theme.space(8.))\n            .items_center();\n        super::theme::apply_style(root, &self.style)\n    }\n}\n\nimpl RenderOnce for Textarea {\n    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {\n        let theme = UiTheme::read(cx).clone();\n        let core = InputCore {\n            label: self.label,\n            disabled: self.disabled,\n            read_only: self.read_only,\n            invalid: self.invalid,\n            bordered: self.bordered,\n            paste_handler: self.paste_handler,\n        };\n        let input = self.state.clone();\n        let root = core\n            .render(\"textarea\", self.state, &theme, window, cx)\n            .min_h(theme.space(16.))\n            .items_start()\n            .py(theme.space(2.));\n        let editable = !self.disabled && !self.read_only;\n        let root = match self.misspellings {\n            Some(misspellings) => {\n                install_spelling_menu(&input, &misspellings, editable, cx);\n                let replacer = misspellings.clone();\n                root.relative()\n                    .when(editable, |root| {\n                        root.on_action(move |action: &ReplaceMisspelling, window, cx| {\n                            replacer.update(cx, |misspellings, cx| {\n                                misspellings.replace(\n                                    action.range.clone(),\n                                    action.text.clone(),\n                                    window,\n                                    cx,\n                                )\n                            });\n                        })\n                    })\n                    .child(misspelling_underlines(input, misspellings, &theme))\n            }\n            None => root,\n        };\n        super::theme::apply_style(root, &self.style)\n    }\n}\n\n/// Shows the spelling items and the edit items on a right-click.\nfn install_spelling_menu(\n    input: &Entity<TextareaState>,\n    misspellings: &Entity<Misspellings>,\n    editable: bool,\n    cx: &mut App,\n) {\n    let misspellings = misspellings.downgrade();\n    let weak_input = input.downgrade();\n    input.update(cx, |state, _| {\n        state.on_context_menu(Rc::new(move |_, capabilities, position, window, cx| {\n            let (Some(input), Some(misspellings)) = (weak_input.upgrade(), misspellings.upgrade())\n            else {\n                return;\n            };\n            // The right-click has already moved the caret to the word.\n            let (cursor, value) = {\n                let input = input.read(cx);\n                (input.cursor(), input.value())\n            };\n            let found = misspellings.read(cx).range_at(cursor);\n            let handler = misspellings.read(cx).menu.clone();\n            let mut menu = NativeMenu::new();\n            if let (Some(range), Some(handler), true) = (found, handler, editable) {\n                let mut spelling = SpellingMenu {\n                    word: value\n                        .get(range.clone())\n                        .unwrap_or_default()\n                        .to_string()\n                        .into(),\n                    range,\n                    menu,\n                };\n                handler(&mut spelling, window, cx);\n                menu = spelling.menu;\n            }\n            edit_menu(\n                menu,\n                capabilities.is_copyable(),\n                editable && !capabilities.is_readonly(),\n                cx,\n            )\n            .show(position, window, cx);\n        }));\n    });\n}\n\n/// The Nova editing frame around any Kit input state. `Input` and `Textarea`\n/// differ only in their size, so both build on this.\n#[doc(hidden)]\npub struct InputCore {\n    pub label: Option<SharedString>,\n    pub disabled: bool,\n    pub read_only: bool,\n    pub invalid: bool,\n    pub bordered: bool,\n    pub paste_handler: Option<PasteHandler>,\n}\n\nimpl InputCore {\n    /// The editor colors every Kit input in a gpuicn app uses.\n    pub fn editor_style(theme: &UiTheme) -> InputEditorStyle {\n        let colors = theme.colors;\n        InputEditorStyle {\n            foreground: colors.foreground.into(),\n            muted_foreground: colors.muted_foreground.into(),\n            background: colors.background.into(),\n            border: colors.input.into(),\n            selection: colors.ring.opacity(0.3).into(),\n            caret: colors.foreground.into(),\n            ..Default::default()\n        }\n    }\n\n    #[doc(hidden)]\n    pub fn render<M: InputModeKind>(\n        self,\n        kind: &'static str,\n        state: Entity<InputBaseState<M>>,\n        theme: &UiTheme,\n        window: &mut Window,\n        cx: &mut App,\n    ) -> InputBase {\n        let editor_style = Self::editor_style(theme);\n        let direction = theme.direction;\n        state.update(cx, |state, cx| {\n            state.set_disabled(self.disabled, cx);\n            state.set_readonly(self.read_only, cx);\n            state.set_editor_style(editor_style);\n            // Single-line inputs start at the reading edge; Kit leaves\n            // multi-line alignment to the text itself.\n            state.set_text_align(direction.start_align(), cx);\n        });\n        let read_only_text = locale::text(cx, UiText::ReadOnly);\n        let invalid_text = locale::text(cx, UiText::InvalidValue);\n        let read = state.read(cx);\n        let focus_handle = read.focus_handle(cx);\n        let focused = focus_handle.is_focused(window) && !self.disabled;\n        let value = read.value();\n        let placeholder = read.presentation().placeholder().clone();\n        let action_state = state.clone();\n        let click_state = state.clone();\n        let a11y_focus = state.clone();\n        let paste_handler = self\n            .paste_handler\n            .filter(|_| !self.disabled && !self.read_only);\n        let root = InputBase::new(ElementId::from((kind, state.entity_id())))\n            .focused(focused)\n            .disabled(self.disabled)\n            .when_some(self.label, |root, label| root.accessibility_label(label))\n            .aria_value(value)\n            .aria_placeholder(placeholder)\n            .when(self.read_only, |root| root.aria_description(read_only_text))\n            .when(self.invalid, |root| root.aria_description(invalid_text))\n            .when(direction.is_rtl(), |root| {\n                root.key_context(locale::RTL_INPUT_CONTEXT)\n            })\n            .when(!self.disabled, |root| {\n                root.on_a11y_action(AccessibleAction::Focus, move |_, window, cx| {\n                    a11y_focus.update(cx, |state, cx| state.focus(window, cx));\n                })\n            })\n            .when(!self.disabled, |root| {\n                root.on_mouse_down(MouseButton::Left, move |_, window, cx| {\n                    click_state.update(cx, |state, cx| state.focus(window, cx));\n                })\n            })\n            .when(!self.disabled && !self.read_only, |root| {\n                root.on_a11y_action(AccessibleAction::SetValue, move |data, window, cx| {\n                    if let Some(gpui_kit::accesskit::ActionData::Value(value)) = data {\n                        action_state.update(cx, |state, cx| {\n                            let end = state.value().encode_utf16().count();\n                            state.replace_text_in_range(Some(0..end), value, window, cx);\n                        });\n                    }\n                })\n            })\n            .flex()\n            .w_full()\n            .min_w_0()\n            .px(theme.space(2.5))\n            .text_color(theme.colors.foreground);\n        let root = if self.bordered {\n            focus::shown_for(\n                control::frame(root, theme, self.invalid),\n                theme,\n                focused,\n                self.invalid,\n            )\n            // The ring is a shadow painted under the whole box; a translucent\n            // fill would show it across a tall textarea.\n            .when_some(\n                focused.then(|| theme.opaque(theme.control().background)),\n                |root, fill| root.bg(fill),\n            )\n        } else {\n            super::theme::primitives::text::sm(root, theme)\n        };\n        root.when(self.disabled, disabled::style)\n            .when_some(paste_handler, |root, handler| {\n                root.capture_action(move |_: &gpui_kit::base::input::Paste, window, cx| {\n                    if let Some(clipboard) = cx.read_from_clipboard()\n                        && handler(&clipboard, window, cx)\n                    {\n                        cx.stop_propagation();\n                    }\n                })\n            })\n            .child(state)\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use gpui_kit::{AppContext as _, Context, Render, TestAppContext, VisualTestContext};\n    use std::{cell::Cell, rc::Rc};\n\n    struct PasteProbe {\n        input: Entity<InputState>,\n        textarea: Entity<TextareaState>,\n        multiline: bool,\n        disabled: bool,\n        read_only: bool,\n        hits: Rc<Cell<usize>>,\n    }\n\n    impl Render for PasteProbe {\n        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {\n            let hits = self.hits.clone();\n            let handler = move |item: &ClipboardItem, _: &mut Window, _: &mut App| {\n                hits.set(hits.get() + 1);\n                item.text().as_deref() == Some(\"asset\")\n            };\n            if self.multiline {\n                Textarea::new(&self.textarea)\n                    .disabled(self.disabled)\n                    .read_only(self.read_only)\n                    .on_paste(handler)\n                    .into_any_element()\n            } else {\n                Input::new(&self.input)\n                    .disabled(self.disabled)\n                    .read_only(self.read_only)\n                    .on_paste(handler)\n                    .into_any_element()\n            }\n        }\n    }\n\n    #[gpui_kit::test]\n    fn paste_hooks_consume_payloads_and_respect_editability(cx: &mut TestAppContext) {\n        cx.update(super::super::theme::init);\n        for multiline in [false, true] {\n            let hits = Rc::new(Cell::new(0));\n            let (probe, visual) = cx.add_window_view({\n                let hits = hits.clone();\n                move |window, cx| PasteProbe {\n                    input: cx.new(|cx| InputState::new(window, cx)),\n                    textarea: cx.new(|cx| TextareaState::new(window, cx)),\n                    multiline,\n                    disabled: false,\n                    read_only: false,\n                    hits,\n                }\n            });\n            let draw = |visual: &mut VisualTestContext| {\n                visual.update(|window, cx| window.draw(cx).clear(cx));\n            };\n            let dispatch = |visual: &mut VisualTestContext, text: &str| {\n                visual.update(|window, cx| {\n                    if multiline {\n                        let textarea = probe.read(cx).textarea.clone();\n                        textarea.update(cx, |state, cx| state.focus(window, cx));\n                    } else {\n                        let input = probe.read(cx).input.clone();\n                        input.update(cx, |state, cx| state.focus(window, cx));\n                    }\n                    cx.write_to_clipboard(ClipboardItem::new_string(text.into()));\n                    window.dispatch_action(Box::new(gpui_kit::base::input::Paste), cx);\n                });\n            };\n            let value = |visual: &mut VisualTestContext| {\n                visual.update(|_, cx| {\n                    let probe = probe.read(cx);\n                    if multiline {\n                        probe.textarea.read(cx).value().to_string()\n                    } else {\n                        probe.input.read(cx).value().to_string()\n                    }\n                })\n            };\n\n            draw(visual);\n            dispatch(visual, \"asset\");\n            assert_eq!(hits.get(), 1);\n            assert_eq!(value(visual), \"\");\n\n            dispatch(visual, \"text\");\n            assert_eq!(hits.get(), 2);\n            assert_eq!(value(visual), \"text\");\n\n            for (disabled, read_only) in [(true, false), (false, true)] {\n                probe.update(visual, |probe, cx| {\n                    probe.disabled = disabled;\n                    probe.read_only = read_only;\n                    cx.notify();\n                });\n                draw(visual);\n                dispatch(visual, \"asset\");\n                assert_eq!(hits.get(), 2);\n                assert_eq!(value(visual), \"text\");\n            }\n        }\n    }\n}\n\n#[cfg(test)]\nmod spelling_tests {\n    use super::*;\n    use gpui_kit::{AppContext as _, Render, TestAppContext, VisualTestContext};\n\n    struct Notes {\n        input: Entity<TextareaState>,\n        misspellings: Entity<Misspellings>,\n    }\n\n    impl Render for Notes {\n        fn render(&mut self, _: &mut Window, _: &mut gpui_kit::Context<Self>) -> impl IntoElement {\n            gpui_kit::div().w(px(400.)).child(\n                Textarea::new(&self.input)\n                    .aria_label(\"Notes\")\n                    .misspellings(&self.misspellings),\n            )\n        }\n    }\n\n    fn notes(text: &'static str, cx: &mut TestAppContext) -> (Entity<Notes>, VisualTestContext) {\n        cx.update(super::super::theme::init);\n        let window = cx.add_window(move |window, cx| {\n            let input = cx.new(|cx| TextareaState::new(window, cx));\n            input.update(cx, |input, cx| input.set_value(text, window, cx));\n            let misspellings = cx.new(|cx| Misspellings::new(&input, cx));\n            Notes {\n                input,\n                misspellings,\n            }\n        });\n        let view = window.root(cx).unwrap();\n        let mut cx = VisualTestContext::from_window(window.into(), cx);\n        cx.update(|window, cx| {\n            window.activate_window();\n            let input = view.read(cx).input.clone();\n            input.update(cx, |input, cx| input.focus(window, cx));\n            window.draw(cx).clear(cx);\n        });\n        (view, cx)\n    }\n\n    #[gpui_kit::test]\n    fn edits_move_later_ranges_and_drop_touched_ones(cx: &mut TestAppContext) {\n        let (view, mut cx) = notes(\"teh cat sat on teh mat\", cx);\n        let (input, misspellings) = cx.update(|_, cx| {\n            let view = view.read(cx);\n            (view.input.clone(), view.misspellings.clone())\n        });\n        cx.update(|_, cx| misspellings.update(cx, |m, cx| m.set([0..3, 15..18, 30..40], cx)));\n        cx.update(|_, cx| {\n            assert_eq!(\n                misspellings.read(cx).ranges(),\n                [0..3, 15..18],\n                \"out of range dropped\"\n            )\n        });\n        // Typing before the second word moves it.\n        cx.update(|window, cx| {\n            input.update(cx, |input, cx| {\n                input.set_selected_range(4..4, cx);\n                input.replace(\"big \", window, cx);\n            })\n        });\n        cx.run_until_parked();\n        cx.update(|_, cx| assert_eq!(misspellings.read(cx).ranges(), [0..3, 19..22]));\n        // Typing inside the first word drops it.\n        cx.update(|window, cx| {\n            input.update(cx, |input, cx| {\n                input.set_selected_range(1..1, cx);\n                input.replace(\"x\", window, cx);\n            })\n        });\n        cx.run_until_parked();\n        cx.update(|_, cx| {\n            let misspellings = misspellings.read(cx);\n            assert_eq!(misspellings.ranges(), vec![20..23]);\n            assert_eq!(misspellings.range_at(21), Some(20..23));\n            assert_eq!(misspellings.range_at(5), None);\n        });\n    }\n\n    #[gpui_kit::test]\n    fn a_suggestion_replaces_the_word_in_one_undoable_edit(cx: &mut TestAppContext) {\n        let (view, mut cx) = notes(\"see teh cat\", cx);\n        let input = cx.update(|_, cx| view.read(cx).input.clone());\n        cx.update(|_, cx| {\n            view.read(cx)\n                .misspellings\n                .clone()\n                .update(cx, |m, cx| m.set(std::iter::once(4..7), cx));\n        });\n        cx.dispatch_action(ReplaceMisspelling {\n            range: 4..7,\n            text: \"the\".into(),\n        });\n        cx.update(|_, cx| assert_eq!(input.read(cx).value(), \"see the cat\"));\n        cx.simulate_keystrokes(\"secondary-z\");\n        cx.update(|_, cx| assert_eq!(input.read(cx).value(), \"see teh cat\"));\n    }\n\n    #[gpui_kit::test]\n    fn the_spelling_menu_puts_suggestions_above_the_edit_items(cx: &mut TestAppContext) {\n        let mut menu = SpellingMenu {\n            range: 0..3,\n            word: \"teh\".into(),\n            menu: NativeMenu::new(),\n        };\n        menu.suggestion(\"the\").suggestion(\"ten\");\n        let menu = cx.update(|cx| edit_menu(menu.menu, false, true, cx));\n        assert!(!menu.is_empty());\n    }\n}\n"
    },
    {
      "path": "registry/kbd/kbd.rs",
      "type": "registry:file",
      "target": "~/src/ui/kbd.rs",
      "content": "//! Nova-styled keyboard shortcut hints.\n\nuse gpui_icons::{LucideIcon, lucide};\nuse gpui_kit::{\n    Action, AnyElement, App, AsKeystroke as _, Div, FontWeight, IntoElement, Keystroke,\n    OperatingSystem, ParentElement, RenderOnce, SharedString, Styled, Window, div,\n};\n\nuse super::theme::{UiTheme, primitives::text};\n\n/// A noninteractive key cap that shows one key or shortcut.\n#[derive(IntoElement)]\npub struct Kbd {\n    style: gpui_kit::StyleRefinement,\n    keys: Keys,\n}\n\nenum Keys {\n    Text(SharedString),\n    Shortcut(SharedString),\n    Keystroke(Keystroke),\n}\n\nimpl Kbd {\n    /// Shows `keys` as written, for example `\"Esc\"` or `\"⌘K\"`.\n    pub fn new(keys: impl Into<SharedString>) -> Self {\n        Self::with(Keys::Text(keys.into()))\n    }\n\n    /// Shows a GPUI keystroke with the platform's modifier names, such as `⌘K` on\n    /// macOS and `Ctrl+K` elsewhere.\n    pub fn keystroke(keystroke: &Keystroke) -> Self {\n        Self::with(Keys::Keystroke(keystroke.clone()))\n    }\n\n    /// Shows a keystroke written like a key binding, such as `\"secondary-k\"`, for\n    /// the platform the app runs on. Text that does not parse is shown as written.\n    pub fn shortcut(source: impl Into<SharedString>) -> Self {\n        Self::with(Keys::Shortcut(source.into()))\n    }\n\n    /// Shows the first keystroke bound to `action` in the window, if any.\n    pub fn for_action(action: &dyn Action, window: &Window) -> Option<Self> {\n        let binding = window.highest_precedence_binding_for_action(action)?;\n        let keystroke = binding.keystrokes().first()?;\n        Some(Self::keystroke(keystroke.as_keystroke()))\n    }\n\n    fn with(keys: Keys) -> Self {\n        Self {\n            style: gpui_kit::StyleRefinement::default(),\n            keys,\n        }\n    }\n}\n\n/// Formats a key-binding string such as `\"secondary-shift-p\"` for `os`, or\n/// returns it unchanged when it does not parse.\npub fn format_shortcut(source: &str, os: OperatingSystem) -> SharedString {\n    match Keystroke::parse_with_os(source, os) {\n        Ok(keystroke) => format_keystroke(&keystroke, os),\n        Err(_) => SharedString::from(source.to_string()),\n    }\n}\n\n/// Formats a keystroke the way `os` shows shortcuts in menus: modifier glyphs\n/// such as `⌃⌥⇧⌘K` on macOS, and `Ctrl+Alt+Shift+K` elsewhere.\npub fn format_keystroke(keystroke: &Keystroke, os: OperatingSystem) -> SharedString {\n    let mac = matches!(os, OperatingSystem::Mac | OperatingSystem::Ios);\n    let modifiers = keystroke.modifiers;\n    let mut parts: Vec<&str> = Vec::new();\n    for (on, glyph, name) in [\n        (modifiers.control, \"⌃\", \"Ctrl\"),\n        (modifiers.alt, \"⌥\", \"Alt\"),\n        (modifiers.shift, \"⇧\", \"Shift\"),\n        (\n            modifiers.platform,\n            \"⌘\",\n            if os == OperatingSystem::Windows {\n                \"Win\"\n            } else {\n                \"Super\"\n            },\n        ),\n    ] {\n        if on {\n            parts.push(if mac { glyph } else { name });\n        }\n    }\n    let key = keystroke.key.as_str();\n    let named = match (key, mac) {\n        (\"enter\", true) => Some(\"↩\"),\n        (\"escape\", true) => Some(\"⎋\"),\n        (\"backspace\" | \"delete\", true) => Some(\"⌫\"),\n        (\"tab\", true) => Some(\"⇥\"),\n        (\"up\", true) => Some(\"↑\"),\n        (\"down\", true) => Some(\"↓\"),\n        (\"left\", true) => Some(\"←\"),\n        (\"right\", true) => Some(\"→\"),\n        (\"escape\", false) => Some(\"Esc\"),\n        (\"pageup\", _) => Some(\"Page Up\"),\n        (\"pagedown\", _) => Some(\"Page Down\"),\n        _ => None,\n    };\n    let key = match named {\n        Some(named) => named.to_string(),\n        None => {\n            let mut chars = key.chars();\n            chars\n                .next()\n                .map(|first| first.to_uppercase().chain(chars).collect())\n                .unwrap_or_default()\n        }\n    };\n    parts.push(&key);\n    parts.join(if mac { \"\" } else { \"+\" }).into()\n}\n\n/// Lays out several key caps in a row, for sequences such as `Ctrl` `B`.\npub fn kbd_group(keys: impl IntoIterator<Item = Kbd>, cx: &App) -> Div {\n    let theme = UiTheme::read(cx);\n    div()\n        .flex()\n        .flex_shrink_0()\n        .items_center()\n        .gap(theme.space(1.))\n        .children(keys)\n}\n\nimpl RenderOnce for Kbd {\n    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {\n        let theme = UiTheme::read(cx);\n        let root = div()\n            .flex()\n            .flex_shrink_0()\n            .items_center()\n            .justify_center()\n            .h(theme.space(5.))\n            .min_w(theme.space(5.))\n            .px(theme.space(1.))\n            .rounded(theme.radius.sm)\n            .bg(theme.colors.muted)\n            .text_color(theme.colors.muted_foreground)\n            .font_family(theme.fonts.body.clone())\n            .font_weight(FontWeight::MEDIUM)\n            .text_size(theme.text(12.))\n            .line_height(text::line_height(theme, theme.text(12.)))\n            .whitespace_nowrap()\n            .gap(theme.space(0.5))\n            .children(key_parts(\n                &match self.keys {\n                    Keys::Text(text) => text,\n                    Keys::Shortcut(source) => format_shortcut(&source, cx.platform_info().os),\n                    Keys::Keystroke(keystroke) => {\n                        format_keystroke(&keystroke, cx.platform_info().os)\n                    }\n                },\n                theme.text(12.),\n                // Icons don't inherit text color, so follow a caller's override.\n                self.style\n                    .text\n                    .color\n                    .unwrap_or(theme.colors.muted_foreground.into()),\n            ));\n        super::theme::apply_style(root, &self.style).into_any_element()\n    }\n}\n\n/// The icon drawn for a key symbol. UI fonts such as Geist have no glyphs for\n/// most of these, and the browser build has no system font to fall back on.\nfn key_icon(symbol: char) -> Option<LucideIcon> {\n    Some(match symbol {\n        '⌘' => LucideIcon::Command,\n        '⌥' => LucideIcon::Option,\n        '⇧' => LucideIcon::ArrowBigUp,\n        '⌃' => LucideIcon::ChevronUp,\n        '↩' => LucideIcon::CornerDownLeft,\n        '⌫' => LucideIcon::Delete,\n        '⇥' => LucideIcon::ArrowRightToLine,\n        '↑' => LucideIcon::ArrowUp,\n        '↓' => LucideIcon::ArrowDown,\n        '←' => LucideIcon::ArrowLeft,\n        '→' => LucideIcon::ArrowRight,\n        _ => return None,\n    })\n}\n\n/// Draws formatted keys such as `\"⇧⌘P\"` inline, with key symbols as icons, for\n/// shortcut hints outside a key cap.\npub fn key_label(keys: &str, size: gpui_kit::Pixels, color: gpui_kit::Hsla) -> Div {\n    div()\n        .flex()\n        .items_center()\n        .gap(size / 6.)\n        .text_color(color)\n        .children(key_parts(keys, size, color))\n}\n\n/// Splits formatted keys into text runs and symbol icons.\nfn key_parts(keys: &str, size: gpui_kit::Pixels, color: gpui_kit::Hsla) -> Vec<AnyElement> {\n    let mut parts = Vec::new();\n    let mut text = String::new();\n    for symbol in keys.chars() {\n        if let Some(icon) = key_icon(symbol) {\n            if !text.is_empty() {\n                parts.push(std::mem::take(&mut text).into_any_element());\n            }\n            parts.push(lucide(icon).size(size).text_color(color).into_any_element());\n        } else if symbol == '⎋' {\n            text.push_str(\"Esc\");\n        } else {\n            text.push(symbol);\n        }\n    }\n    if !text.is_empty() {\n        parts.push(text.into_any_element());\n    }\n    parts\n}\n\nimpl Styled for Kbd {\n    fn style(&mut self) -> &mut gpui_kit::StyleRefinement {\n        &mut self.style\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::{OperatingSystem, format_shortcut};\n\n    #[test]\n    fn shortcuts_follow_platform_conventions() {\n        let mac = OperatingSystem::Mac;\n        let linux = OperatingSystem::Linux;\n        assert_eq!(format_shortcut(\"secondary-k\", mac).as_ref(), \"⌘K\");\n        assert_eq!(format_shortcut(\"secondary-k\", linux).as_ref(), \"Ctrl+K\");\n        assert_eq!(format_shortcut(\"secondary-shift-p\", mac).as_ref(), \"⇧⌘P\");\n        assert_eq!(\n            format_shortcut(\"ctrl-alt-shift-a\", linux).as_ref(),\n            \"Ctrl+Alt+Shift+A\"\n        );\n        assert_eq!(format_shortcut(\"escape\", linux).as_ref(), \"Esc\");\n        assert_eq!(format_shortcut(\"alt-up\", mac).as_ref(), \"⌥↑\");\n        assert_eq!(format_shortcut(\"secondary-,\", linux).as_ref(), \"Ctrl+,\");\n    }\n}\n"
    },
    {
      "path": "registry/menu/menu.rs",
      "type": "registry:file",
      "target": "~/src/ui/menu.rs",
      "content": "//! Nova menus composed from Kit buttons and popup positioning.\nuse super::{\n    button::{ButtonSize, ButtonVariant, style_button},\n    kbd::{format_shortcut, key_label},\n    theme::{\n        UiTheme, apply_style,\n        locale::DirectionalStyled as _,\n        primitives::{disabled, dismiss, surface, text},\n    },\n};\nuse gpui_icons::{LucideIcon, lucide};\nuse gpui_kit::base::TestSupportExt as _;\nuse gpui_kit::base::{Align, Button, ElementExt as _, Placement, Positioner};\nuse gpui_kit::{\n    AnyElement, App, Bounds, ClickEvent, Context, ElementId, Entity, FocusHandle, Focusable,\n    FontWeight, InteractiveElement as _, IntoElement, MouseButton, ParentElement as _, Pixels,\n    Point, Render, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,\n    StyleRefinement, Styled, Window, div, prelude::FluentBuilder as _,\n};\nuse std::{rc::Rc, time::Duration};\n\ntype Handler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;\ntype Slot = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;\n#[derive(Clone)]\n/// An action, check item, radio item, separator or submenu entry.\npub struct MenuItem {\n    id: ElementId,\n    label: SharedString,\n    disabled: bool,\n    checked: Option<bool>,\n    radio: bool,\n    link: bool,\n    handler: Option<Handler>,\n    children: Vec<MenuItem>,\n    separator: bool,\n    icon: Option<LucideIcon>,\n    leading: Option<Slot>,\n    description: Option<SharedString>,\n    trailing: Option<Slot>,\n    shortcut: Option<SharedString>,\n}\nimpl MenuItem {\n    /// Creates an action with a caller-owned ID, unique within this menu tree.\n    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {\n        Self {\n            id: id.into(),\n            label: label.into(),\n            disabled: false,\n            checked: None,\n            radio: false,\n            link: false,\n            handler: None,\n            children: Vec::new(),\n            separator: false,\n            icon: None,\n            leading: None,\n            description: None,\n            trailing: None,\n            shortcut: None,\n        }\n    }\n    /// Shows a 16px Lucide icon in muted color at the row's leading edge.\n    pub fn icon(mut self, icon: LucideIcon) -> Self {\n        self.icon = Some(icon);\n        self\n    }\n    /// Renders a caller-built element at the row's leading edge, such as an\n    /// avatar or a team tile. It replaces [`MenuItem::icon`]. The closure runs\n    /// on every render of the open menu, so items stay cheap to clone.\n    pub fn leading(mut self, slot: impl Fn(&mut Window, &mut App) -> AnyElement + 'static) -> Self {\n        self.leading = Some(Rc::new(slot));\n        self\n    }\n    /// Shows a muted secondary line under the label.\n    pub fn description(mut self, text: impl Into<SharedString>) -> Self {\n        self.description = Some(text.into());\n        self\n    }\n    /// Renders a caller-built element right-aligned before the shortcut, such\n    /// as an unread count or a status dot.\n    pub fn trailing(\n        mut self,\n        slot: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,\n    ) -> Self {\n        self.trailing = Some(Rc::new(slot));\n        self\n    }\n    /// Shows a keyboard shortcut at the far right, written like a key binding\n    /// (`\"secondary-alt-1\"`) and drawn for the running platform (`⌘⌥1` on\n    /// macOS, `Ctrl+Alt+1` elsewhere). Text that does not parse is shown as\n    /// written, so a plain hint such as `\"Settings\"` works too.\n    pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {\n        self.shortcut = Some(shortcut.into());\n        self\n    }\n    fn rich(&self) -> bool {\n        self.icon.is_some() || self.leading.is_some() || self.description.is_some()\n    }\n    /// Disables interaction and applies the disabled appearance.\n    pub fn disabled(mut self, value: bool) -> Self {\n        self.disabled = value;\n        self\n    }\n    /// Makes this a checkbox item with the supplied initial state.\n    pub fn checked(mut self, value: bool) -> Self {\n        self.checked = Some(value);\n        self\n    }\n    /// Makes this a radio item; activating it clears radio siblings at this menu level.\n    pub fn radio(mut self, value: bool) -> Self {\n        self.checked = Some(value);\n        self.radio = true;\n        self\n    }\n    /// Handles activation by pointer, keyboard or an accessibility action.\n    /// It runs after the menu closes and its state update returns, so it may\n    /// call [`MenuState::set_items`].\n    pub fn on_click(\n        mut self,\n        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,\n    ) -> Self {\n        self.handler = Some(Rc::new(handler));\n        self\n    }\n    /// Marks a link; the caller handles navigation through `on_click`.\n    pub fn link(mut self) -> Self {\n        self.link = true;\n        self\n    }\n    /// Creates an item containing another level of menu entries.\n    pub fn submenu(\n        id: impl Into<ElementId>,\n        label: impl Into<SharedString>,\n        items: impl IntoIterator<Item = MenuItem>,\n    ) -> Self {\n        let mut item = Self::new(id, label);\n        item.children = items.into_iter().collect();\n        item\n    }\n    /// Creates a non-interactive separator between menu entries.\n    pub fn separator() -> Self {\n        let mut item = Self::new(\"separator\", \"\");\n        item.separator = true;\n        item\n    }\n    /// Creates a non-interactive menu heading.\n    pub fn label(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {\n        Self::new(id, label).disabled(true)\n    }\n    fn enabled(&self) -> bool {\n        !self.disabled && !self.separator\n    }\n}\n\n/// A committed leaf action, including its new checked state when applicable.\n#[derive(Clone, Debug)]\npub struct MenuEvent {\n    /// Indices from the root menu to the activated leaf.\n    pub path: Vec<usize>,\n    /// The committed checked state, or `None` for a plain action.\n    pub checked: Option<bool>,\n}\nimpl gpui_kit::EventEmitter<MenuEvent> for MenuState {}\n\n/// Retained popup visibility, item state and keyboard navigation. Emits `MenuEvent` on leaf activation.\npub struct MenuState {\n    items: Vec<MenuItem>,\n    open: bool,\n    focus: FocusHandle,\n    trigger: FocusHandle,\n    return_focus: Option<FocusHandle>,\n    anchor: Bounds<Pixels>,\n    pointer: bool,\n    path: Vec<usize>,\n    highlighted: Vec<Option<usize>>,\n    row_bounds: Vec<Vec<Bounds<Pixels>>>,\n    popup_bounds: Vec<Bounds<Pixels>>,\n    query: String,\n    typed_at: Option<web_time::Instant>,\n    submenu_timer: Option<gpui_kit::Task<()>>,\n    width: Option<Pixels>,\n}\n\n/// How long the pointer rests on a submenu row before the submenu opens.\nconst SUBMENU_HOVER_DELAY: Duration = Duration::from_millis(200);\n/// The gap kept between a menu panel and the window edge.\nconst WINDOW_MARGIN: f32 = 8.;\n/// The shortest a menu panel gets before it scrolls in a very short window.\nconst MIN_PANEL_HEIGHT: f32 = 96.;\n\n/// The tallest a menu panel can be before it scrolls: the larger of the room\n/// below and above `anchor` for a menu that drops from its trigger, or the\n/// window height for one beside its anchor (a context menu or a submenu),\n/// which slides up and down instead of flipping.\n#[doc(hidden)]\npub fn menu_max_height(\n    anchor: Bounds<Pixels>,\n    viewport: gpui_kit::Size<Pixels>,\n    beside: bool,\n    offset: Pixels,\n) -> Pixels {\n    let margin = gpui_kit::px(WINDOW_MARGIN);\n    let room = if beside {\n        viewport.height - margin * 2.\n    } else {\n        let below = viewport.height - anchor.bottom() - offset - margin;\n        let above = anchor.top() - offset - margin;\n        below.max(above)\n    };\n    room.max(gpui_kit::px(MIN_PANEL_HEIGHT))\n}\nimpl MenuState {\n    /// Creates a closed menu with the supplied entries and new focus handles.\n    pub fn new(items: impl IntoIterator<Item = MenuItem>, cx: &mut Context<Self>) -> Self {\n        Self {\n            items: items.into_iter().collect(),\n            open: false,\n            focus: cx.focus_handle().tab_stop(false),\n            trigger: cx.focus_handle().tab_stop(true),\n            return_focus: None,\n            anchor: Default::default(),\n            pointer: false,\n            path: Vec::new(),\n            highlighted: Vec::new(),\n            row_bounds: Vec::new(),\n            popup_bounds: Vec::new(),\n            query: String::new(),\n            typed_at: None,\n            submenu_timer: None,\n            width: None,\n        }\n    }\n    /// Gives the root panel a fixed width instead of sizing it to its widest\n    /// row. Submenus keep sizing to their content.\n    pub fn width(mut self, width: Pixels) -> Self {\n        self.width = Some(width);\n        self\n    }\n    /// Returns whether the popup is open.\n    pub fn is_open(&self) -> bool {\n        self.open\n    }\n    /// Replaces the menu entries and resets submenu navigation.\n    pub fn set_items(&mut self, items: impl IntoIterator<Item = MenuItem>, cx: &mut Context<Self>) {\n        self.items = items.into_iter().collect();\n        self.path.clear();\n        self.highlighted = vec![self.items.iter().position(MenuItem::enabled)];\n        cx.notify();\n    }\n    /// Returns the handle used by the menu trigger.\n    pub fn trigger_focus(&self) -> FocusHandle {\n        self.trigger.clone()\n    }\n    /// Opens the menu at its trigger and transfers keyboard focus into it.\n    pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {\n        self.open_at(None, window, cx);\n    }\n    /// Opens at a pointer position, or at the trigger when the position is absent.\n    pub fn open_at(\n        &mut self,\n        point: Option<Point<Pixels>>,\n        window: &mut Window,\n        cx: &mut Context<Self>,\n    ) {\n        self.pointer = point.is_some();\n        self.return_focus = if self.pointer {\n            window.focused(cx)\n        } else {\n            None\n        };\n        if let Some(point) = point {\n            self.anchor = Bounds::new(point, gpui_kit::size(gpui_kit::px(0.), gpui_kit::px(0.)));\n        }\n        self.open = true;\n        self.path.clear();\n        self.query.clear();\n        self.highlighted = vec![self.items.iter().position(MenuItem::enabled)];\n        self.focus.focus(window, cx);\n        cx.notify();\n    }\n    /// Closes and optionally restores the prior context focus or menu trigger.\n    pub fn close(&mut self, restore: bool, window: &mut Window, cx: &mut Context<Self>) {\n        self.open = false;\n        self.path.clear();\n        if restore {\n            self.return_focus\n                .take()\n                .unwrap_or_else(|| self.trigger.clone())\n                .focus(window, cx);\n        }\n        cx.notify();\n    }\n    #[doc(hidden)]\n    pub fn submenu_key(&self, right: bool) -> bool {\n        if !right {\n            return !self.path.is_empty();\n        }\n        self.highlighted\n            .last()\n            .copied()\n            .flatten()\n            .is_some_and(|i| !self.level(self.path.len())[i].children.is_empty())\n    }\n    fn level(&self, depth: usize) -> &[MenuItem] {\n        let mut items = self.items.as_slice();\n        for &index in self.path.iter().take(depth) {\n            items = &items[index].children;\n        }\n        items\n    }\n    fn highlight(&mut self, depth: usize, index: usize, cx: &mut Context<Self>) {\n        if !self.level(depth)[index].enabled() {\n            return;\n        }\n        if self.highlighted.get(depth).copied().flatten() == Some(index) {\n            return;\n        }\n        self.path.truncate(depth);\n        self.highlighted.truncate(depth + 1);\n        self.highlighted[depth] = Some(index);\n        cx.notify();\n    }\n    /// Opens the submenu at `index` after a short rest, unless the pointer\n    /// has moved on to another row by then.\n    fn hover_submenu(\n        &mut self,\n        depth: usize,\n        index: usize,\n        window: &mut Window,\n        cx: &mut Context<Self>,\n    ) {\n        self.submenu_timer = None;\n        if self.level(depth)[index].children.is_empty() || self.path.get(depth) == Some(&index) {\n            return;\n        }\n        self.submenu_timer = Some(cx.spawn_in(window, async move |this, cx| {\n            cx.background_executor().timer(SUBMENU_HOVER_DELAY).await;\n            _ = this.update(cx, |this, cx| {\n                if this.open\n                    && this.path.len() == depth\n                    && this.highlighted.get(depth).copied().flatten() == Some(index)\n                {\n                    this.open_submenu(depth, index, cx);\n                }\n            });\n        }));\n    }\n    fn open_submenu(&mut self, depth: usize, index: usize, cx: &mut Context<Self>) {\n        let first = self.level(depth)[index]\n            .children\n            .iter()\n            .position(MenuItem::enabled);\n        self.path.truncate(depth);\n        self.path.push(index);\n        self.highlighted.truncate(depth + 1);\n        self.highlighted.push(first);\n        cx.notify();\n    }\n    fn activate(\n        &mut self,\n        depth: usize,\n        index: usize,\n        event: &ClickEvent,\n        window: &mut Window,\n        cx: &mut Context<Self>,\n    ) {\n        let item = self.level(depth)[index].clone();\n        if !item.enabled() {\n            return;\n        }\n        if !item.children.is_empty() {\n            self.submenu_timer = None;\n            self.open_submenu(depth, index, cx);\n        } else {\n            let mut path = self.path[..depth].to_vec();\n            path.push(index);\n            let checked = item.checked.map(|value| item.radio || !value);\n            if let Some(checked) = checked {\n                let mut items = &mut self.items;\n                for &parent in &path[..depth] {\n                    items = &mut items[parent].children;\n                }\n                if item.radio {\n                    for sibling in items.iter_mut().filter(|item| item.radio) {\n                        sibling.checked = Some(false);\n                    }\n                }\n                items[index].checked = Some(checked);\n            }\n            self.close(true, window, cx);\n            cx.emit(MenuEvent { path, checked });\n            // The handler runs once this update returns, so it can update the\n            // menu, for example to rebuild its items from a radio choice.\n            if let Some(handler) = item.handler {\n                let event = event.clone();\n                window.defer(cx, move |window, cx| handler(&event, window, cx));\n            }\n        }\n    }\n    fn key(&mut self, event: &gpui_kit::KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {\n        if !self.open {\n            return;\n        }\n        let depth = self.path.len();\n        // Submenus open toward the reading end, so the arrows swap in\n        // right-to-left layouts.\n        let direction = UiTheme::read(cx).direction;\n        let key = direction.logical_key(event.keystroke.key.as_str());\n        if key == \"escape\" {\n            self.close(true, window, cx);\n        } else if key == \"tab\" {\n            self.close(true, window, cx);\n            return;\n        } else if event.keystroke.modifiers.modified() {\n            return;\n        } else if key == \"left\" && depth > 0 {\n            self.path.pop();\n            self.highlighted.pop();\n            cx.notify();\n        } else if matches!(key, \"enter\" | \"space\" | \"right\") {\n            if let Some(index) = self.highlighted[depth]\n                && (key != \"right\" || !self.level(depth)[index].children.is_empty())\n            {\n                self.activate(\n                    depth,\n                    index,\n                    &ClickEvent::Keyboard(Default::default()),\n                    window,\n                    cx,\n                );\n            }\n        } else {\n            let items = self.level(depth);\n            let enabled: Vec<_> = items\n                .iter()\n                .enumerate()\n                .filter_map(|(i, item)| item.enabled().then_some(i))\n                .collect();\n            if enabled.is_empty() {\n                return;\n            }\n            let current = enabled\n                .iter()\n                .position(|i| Some(*i) == self.highlighted[depth])\n                .unwrap_or(0);\n            let next = match key {\n                \"up\" => Some(enabled[(current + enabled.len() - 1) % enabled.len()]),\n                \"down\" => Some(enabled[(current + 1) % enabled.len()]),\n                \"home\" => enabled.first().copied(),\n                \"end\" => enabled.last().copied(),\n                _ if key.chars().count() == 1 => {\n                    let now = web_time::Instant::now();\n                    if self\n                        .typed_at\n                        .is_none_or(|time| now.duration_since(time) > Duration::from_millis(700))\n                    {\n                        self.query.clear();\n                    }\n                    self.typed_at = Some(now);\n                    self.query.push_str(key);\n                    let query = self.query.to_lowercase();\n                    enabled.into_iter().find(|&i| {\n                        self.level(depth)[i]\n                            .label\n                            .to_lowercase()\n                            .starts_with(&query)\n                    })\n                }\n                _ => return,\n            };\n            if let Some(index) = next {\n                self.highlight(depth, index, cx);\n            }\n        }\n        cx.stop_propagation();\n    }\n}\nimpl Focusable for MenuState {\n    fn focus_handle(&self, _: &App) -> FocusHandle {\n        self.focus.clone()\n    }\n}\nimpl Render for MenuState {\n    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {\n        let t = UiTheme::read(cx).clone();\n        let viewport = window.viewport_size();\n        let os = cx.platform_info().os;\n        let escape = cx.entity().downgrade();\n        let mut root = dismiss::on_escape(div(), move |window, cx| {\n            escape\n                .update(cx, |this, cx| {\n                    let open = this.open;\n                    if open {\n                        this.close(true, window, cx);\n                    }\n                    open\n                })\n                .unwrap_or(false)\n        })\n        .id((\"menu\", cx.entity_id()))\n        .track_focus(&self.focus)\n        .capture_key_down(cx.listener(Self::key));\n        if !self.open {\n            return root;\n        }\n        self.row_bounds.resize_with(self.path.len() + 1, Vec::new);\n        self.popup_bounds\n            .resize(self.path.len() + 1, Default::default());\n        for depth in 0..=self.path.len() {\n            let items = self.level(depth).to_vec();\n            self.row_bounds[depth].resize(items.len(), Default::default());\n            let entity = cx.entity();\n            let popup_id = if depth == 0 {\n                ElementId::from((\"menu-popup\", cx.entity_id()))\n            } else {\n                (\n                    self.level(depth - 1)[self.path[depth - 1]].id.clone(),\n                    \"popup\",\n                )\n                    .into()\n            };\n            let anchor = if depth == 0 {\n                self.anchor\n            } else {\n                self.row_bounds[depth - 1][self.path[depth - 1]]\n            };\n            let beside = depth > 0 || self.pointer;\n            let mut popup = div()\n                .id(popup_id)\n                .relative()\n                .role(Role::Menu)\n                .min_w(t.space(40.))\n                .when_some(self.width.filter(|_| depth == 0), |popup, width| {\n                    popup.w(width)\n                })\n                .max_h(menu_max_height(anchor, viewport, beside, t.space(1.)))\n                .debug_selector(move || format!(\"menu-popup-{depth}\"))\n                .overflow_y_scroll()\n                .map(|popup| surface::menu(popup, &t))\n                .on_prepaint(move |bounds, _, cx| {\n                    entity.update(cx, |this, _| this.popup_bounds[depth] = bounds)\n                })\n                .on_mouse_down_out(cx.listener(\n                    |this, event: &gpui_kit::MouseDownEvent, window, cx| {\n                        if !this.anchor.contains(&event.position)\n                            && !this\n                                .popup_bounds\n                                .iter()\n                                .any(|b| b.contains(&event.position))\n                        {\n                            this.close(false, window, cx);\n                        }\n                    },\n                ));\n            for (index, item) in items.into_iter().enumerate() {\n                if item.separator {\n                    popup = popup.child(\n                        div()\n                            .h(gpui_kit::px(1.))\n                            .my(t.space(1.5))\n                            .bg(t.colors.border),\n                    );\n                    continue;\n                }\n                let entity = cx.entity();\n                let selected = self.highlighted[depth] == Some(index);\n                let submenu = !item.children.is_empty();\n                let role = if submenu {\n                    Role::MenuItem\n                } else if item.link {\n                    Role::Link\n                } else if item.radio {\n                    Role::MenuItemRadio\n                } else if item.checked.is_some() {\n                    Role::MenuItemCheckBox\n                } else {\n                    Role::MenuItem\n                };\n                let row = Button::new(item.id.clone())\n                    .role(role)\n                    .focusable(false)\n                    .disabled(item.disabled)\n                    .accessibility_label(item.label.clone())\n                    .relative()\n                    .w_full()\n                    .min_h(t.space(if item.rich() { 9. } else { 8. }))\n                    .mirror_row(t.direction)\n                    .justify_start()\n                    .gap(t.space(if item.leading.is_some() { 2.5 } else { 2. }))\n                    .px(t.space(1.5))\n                    // GPUI Kit's Button shrinks the line box to the font size,\n                    // which truncate() would clip the descenders to.\n                    .line_height(text::line_height(&t, t.text(14.)))\n                    // A name over a description gets room to breathe: the\n                    // button's fixed height would press the two lines together.\n                    .when(item.description.is_some(), |b| b.h_auto().py(t.space(0.75)))\n                    .rounded(t.radius.sm)\n                    .when(selected, |b| b.bg(t.colors.accent).aria_active_descendant())\n                    .map(|b| disabled::dim(b, item.disabled))\n                    .when_some(item.checked, |b, checked| {\n                        b.aria_toggled(if checked {\n                            gpui_kit::Toggled::True\n                        } else {\n                            gpui_kit::Toggled::False\n                        })\n                    })\n                    .when(submenu, |b| {\n                        b.aria_expanded(self.path.get(depth) == Some(&index))\n                    })\n                    .on_prepaint(move |bounds, window, cx| {\n                        entity.update(cx, |this, _| {\n                            if this.row_bounds[depth][index] != bounds {\n                                this.row_bounds[depth][index] = bounds;\n                                window.request_animation_frame();\n                            }\n                        })\n                    })\n                    .on_hover(cx.listener(move |this, hovered, window, cx| {\n                        if *hovered {\n                            this.highlight(depth, index, cx);\n                            this.hover_submenu(depth, index, window, cx);\n                        }\n                    }))\n                    .on_click(cx.listener(move |this, event, window, cx| {\n                        this.activate(depth, index, event, window, cx)\n                    }))\n                    .map(|b| match (&item.leading, item.icon) {\n                        (Some(slot), _) => b.child(\n                            div()\n                                .flex_shrink_0()\n                                .flex()\n                                .items_center()\n                                .child(slot(window, cx)),\n                        ),\n                        (None, Some(icon)) => b.child(\n                            lucide(icon)\n                                .flex_shrink_0()\n                                .size(t.space(4.))\n                                .text_color(t.colors.muted_foreground),\n                        ),\n                        (None, None) => b,\n                    })\n                    .child(\n                        div()\n                            .flex_1()\n                            .min_w_0()\n                            .flex()\n                            .flex_col()\n                            .child(\n                                div()\n                                    .debug_selector(|| \"menu-label\".into())\n                                    .truncate()\n                                    .child(item.label.clone()),\n                            )\n                            .when_some(item.description.clone(), |col, description| {\n                                col.child(\n                                    text::control(div(), &t, t.text(12.))\n                                        .debug_selector(|| \"menu-description\".into())\n                                        .truncate()\n                                        .font_weight(FontWeight::NORMAL)\n                                        .text_color(t.colors.muted_foreground)\n                                        .child(description),\n                                )\n                            }),\n                    )\n                    .when_some(item.trailing.clone(), |b, slot| {\n                        b.child(\n                            div()\n                                .flex_shrink_0()\n                                .flex()\n                                .items_center()\n                                .child(slot(window, cx)),\n                        )\n                    })\n                    .when(item.checked == Some(true), |b| {\n                        b.child(\n                            lucide(LucideIcon::Check)\n                                .size(t.space(4.))\n                                .text_color(t.colors.popover_foreground),\n                        )\n                    })\n                    .when_some(item.shortcut.clone(), |b, shortcut| {\n                        b.child(\n                            key_label(\n                                &format_shortcut(&shortcut, os),\n                                t.text(12.),\n                                t.colors.muted_foreground.into(),\n                            )\n                            .debug_selector(|| \"menu-shortcut\".into())\n                            .flex_shrink_0()\n                            .text_size(t.text(12.)),\n                        )\n                    })\n                    .when(submenu, |b| {\n                        b.child(\n                            lucide(t.direction.icon(\n                                true,\n                                LucideIcon::ChevronLeft,\n                                LucideIcon::ChevronRight,\n                            ))\n                            .size(t.space(4.))\n                            .text_color(t.colors.popover_foreground),\n                        )\n                    });\n                popup = popup.child(row);\n            }\n            root = root.child(\n                gpui_kit::deferred(\n                    Positioner::side(anchor)\n                        .align(t.direction.align(Align::Start))\n                        .margin(gpui_kit::px(WINDOW_MARGIN))\n                        .placement(t.direction.placement(if beside {\n                            Placement::Right\n                        } else {\n                            Placement::Bottom\n                        }))\n                        .offset(t.space(1.))\n                        .occlude()\n                        .child(popup),\n                )\n                .with_priority(gpui_kit::base::POPUP_PRIORITY + depth),\n            );\n        }\n        root\n    }\n}\n\n#[derive(IntoElement)]\n/// A named menu trigger or context area backed by retained menu state.\npub struct Menu {\n    state: Entity<MenuState>,\n    label: SharedString,\n    disabled: bool,\n    context: Option<AnyElement>,\n    trigger: Option<AnyElement>,\n    trigger_style: Option<Box<dyn FnOnce(Button) -> Button>>,\n    style: StyleRefinement,\n}\nimpl Menu {\n    /// Creates a named trigger for the caller's retained menu state.\n    pub fn new(state: &Entity<MenuState>, label: impl Into<SharedString>) -> Self {\n        Self {\n            state: state.clone(),\n            label: label.into(),\n            disabled: false,\n            context: None,\n            trigger: None,\n            trigger_style: None,\n            style: Default::default(),\n        }\n    }\n    /// Supplies custom content for the named trigger button.\n    pub fn trigger(mut self, child: impl IntoElement) -> Self {\n        self.trigger = Some(child.into_any_element());\n        self\n    }\n    /// Replaces trigger styling while retaining menu behavior. Include a visible keyboard focus treatment.\n    pub fn trigger_style_with(mut self, style: impl FnOnce(Button) -> Button + 'static) -> Self {\n        self.trigger_style = Some(Box::new(style));\n        self\n    }\n    /// Disables interaction and applies the disabled appearance.\n    pub fn disabled(mut self, value: bool) -> Self {\n        self.disabled = value;\n        self\n    }\n    /// Replaces the button trigger with content that opens a menu on secondary click or Shift+F10.\n    pub fn context_area(mut self, child: impl IntoElement) -> Self {\n        self.context = Some(child.into_any_element());\n        self\n    }\n}\nimpl Styled for Menu {\n    fn style(&mut self) -> &mut StyleRefinement {\n        &mut self.style\n    }\n}\nimpl RenderOnce for Menu {\n    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {\n        let state = self.state.clone();\n        let keyboard = state.clone();\n        let measured = state.clone();\n        let context = self.context.is_some();\n        let disabled = self.disabled;\n        let focus = state.read(cx).trigger.clone();\n        let open = state.read(cx).open;\n        let mut base = div()\n            .id((\"menu-trigger\", state.entity_id()))\n            .test_support()\n            .relative()\n            .on_prepaint(move |bounds, _, cx| {\n                measured.update(cx, |this, _| {\n                    if !this.pointer || !this.open {\n                        this.anchor = bounds;\n                    }\n                })\n            })\n            .capture_key_down(move |event, window, cx| {\n                let key = event.keystroke.key.as_str();\n                if !disabled\n                    && keyboard.read(cx).trigger.is_focused(window)\n                    && ((!context && (key == \"down\" || key == \"up\"))\n                        || (context && key == \"f10\" && event.keystroke.modifiers.shift))\n                {\n                    keyboard.update(cx, |this, cx| this.open(window, cx));\n                    cx.stop_propagation();\n                }\n            });\n        if let Some(area) = self.context {\n            base = base\n                .track_focus(&focus.tab_stop(!disabled))\n                .aria_label(self.label)\n                // Keep the content's focus for selection and context-menu restoration.\n                .capture_any_mouse_down(|event, window, _| {\n                    if matches!(event.button, MouseButton::Left | MouseButton::Right) {\n                        window.prevent_default();\n                    }\n                })\n                .on_mouse_down(MouseButton::Right, move |event, window, cx| {\n                    if !disabled {\n                        state.update(cx, |this, cx| {\n                            this.open_at(Some(event.position), window, cx)\n                        });\n                        cx.stop_propagation();\n                    }\n                })\n                .child(area);\n        } else {\n            base = base.child(\n                Button::new((\"menu-button\", state.entity_id()))\n                    .track_focus(&focus)\n                    .tab_stop(focus.tab_stop)\n                    .disabled(disabled)\n                    .accessibility_label(self.label.clone())\n                    .aria_expanded(open)\n                    .map(|button| match self.trigger_style {\n                        Some(style) => style(button),\n                        None => style_button(\n                            button,\n                            disabled,\n                            ButtonVariant::Outline,\n                            ButtonSize::Default,\n                            UiTheme::read(cx),\n                        ),\n                    })\n                    .on_click(move |_, window, cx| {\n                        state.update(cx, |this, cx| {\n                            if this.open {\n                                this.close(true, window, cx);\n                            } else {\n                                this.open(window, cx);\n                            }\n                        })\n                    })\n                    .child(\n                        self.trigger\n                            .unwrap_or_else(|| self.label.into_any_element()),\n                    ),\n            );\n        }\n        apply_style(base.child(self.state), &self.style)\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use gpui_kit::{AppContext as _, point, px, size};\n\n    #[test]\n    fn a_menu_uses_the_room_in_the_window() {\n        let viewport = size(px(1000.), px(800.));\n        let offset = px(4.);\n        // A trigger near the top drops a panel almost to the bottom edge.\n        let top = Bounds::new(point(px(10.), px(20.)), size(px(80.), px(32.)));\n        assert_eq!(\n            menu_max_height(top, viewport, false, offset),\n            px(800. - 52. - 4. - 8.)\n        );\n        // A trigger near the bottom has more room above, where it flips.\n        let bottom = Bounds::new(point(px(10.), px(700.)), size(px(80.), px(32.)));\n        assert_eq!(\n            menu_max_height(bottom, viewport, false, offset),\n            px(700. - 4. - 8.)\n        );\n        // A context menu or submenu slides along the window's full height.\n        assert_eq!(\n            menu_max_height(bottom, viewport, true, offset),\n            px(800. - 16.)\n        );\n        // A very short window still shows a few rows and scrolls.\n        let tiny = size(px(300.), px(60.));\n        assert_eq!(menu_max_height(top, tiny, false, offset), px(96.));\n    }\n\n    struct LongMenu {\n        state: Entity<MenuState>,\n    }\n    impl Render for LongMenu {\n        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {\n            div()\n                .p(px(16.))\n                .child(Menu::new(&self.state, \"Message actions\"))\n        }\n    }\n\n    #[gpui_kit::test]\n    fn a_long_menu_does_not_scroll_in_a_tall_window(cx: &mut gpui_kit::TestAppContext) {\n        cx.update(super::super::theme::init);\n        let (view, cx) = cx.add_window_view(|_, cx| LongMenu {\n            state: cx.new(|cx| {\n                MenuState::new(\n                    (0..12).map(|i| MenuItem::new((\"item\", i as u64), format!(\"Action {i}\"))),\n                    cx,\n                )\n            }),\n        });\n        cx.simulate_resize(size(px(800.), px(800.)));\n        cx.update(|window, cx| window.draw(cx).clear(cx));\n        cx.update(|window, cx| {\n            let state = view.read(cx).state.clone();\n            state.update(cx, |menu, cx| menu.open(window, cx));\n        });\n        cx.update(|window, cx| window.draw(cx).clear(cx));\n        cx.update(|window, cx| window.draw(cx).clear(cx));\n        let popup = cx.debug_bounds(\"menu-popup-0\").expect(\"the menu is open\");\n        // Twelve 32px rows plus padding: taller than the old 288px cap.\n        assert!(popup.size.height > px(12. * 32.), \"{popup:?}\");\n    }\n\n    #[gpui_kit::test]\n    fn rich_items_draw_their_shortcut_and_grow_to_36px(cx: &mut gpui_kit::TestAppContext) {\n        cx.update(super::super::theme::init);\n        let (view, cx) = cx.add_window_view(|_, cx| LongMenu {\n            state: cx.new(|cx| {\n                MenuState::new(\n                    [\n                        MenuItem::new(\"tech\", \"Tech\")\n                            .icon(LucideIcon::Users)\n                            .description(\"karya.team\")\n                            .trailing(|_, _| div().child(\"3\").into_any_element())\n                            .shortcut(\"secondary-alt-1\")\n                            .radio(true),\n                        MenuItem::new(\"join\", \"Join another team…\").icon(LucideIcon::Plus),\n                    ],\n                    cx,\n                )\n                .width(px(300.))\n            }),\n        });\n        cx.simulate_resize(size(px(800.), px(800.)));\n        cx.update(|window, cx| window.draw(cx).clear(cx));\n        cx.update(|window, cx| {\n            let state = view.read(cx).state.clone();\n            state.update(cx, |menu, cx| menu.open(window, cx));\n        });\n        cx.update(|window, cx| window.draw(cx).clear(cx));\n        cx.update(|window, cx| window.draw(cx).clear(cx));\n        let popup = cx.debug_bounds(\"menu-popup-0\").expect(\"the menu is open\");\n        assert_eq!(popup.size.width, px(300.));\n        assert!(popup.size.height >= px(2. * 36.), \"{popup:?}\");\n        let shortcut = cx\n            .debug_bounds(\"menu-shortcut\")\n            .expect(\"the shortcut is drawn\");\n        assert!(shortcut.size.width > px(0.));\n        // The shortcut sits at the trailing edge of the panel.\n        assert!(\n            shortcut.right() > popup.right() - px(24.),\n            \"{shortcut:?} {popup:?}\"\n        );\n    }\n\n    #[gpui_kit::test]\n    fn resting_on_a_submenu_row_opens_it_and_a_sibling_closes_it(\n        cx: &mut gpui_kit::TestAppContext,\n    ) {\n        cx.update(super::super::theme::init);\n        let window = cx.add_window(|_, cx| {\n            MenuState::new(\n                [\n                    MenuItem::new(\"reply\", \"Reply\"),\n                    MenuItem::submenu(\n                        \"remind\",\n                        \"Remind me\",\n                        [\n                            MenuItem::new(\"hour\", \"In 1 hour\"),\n                            MenuItem::new(\"tomorrow\", \"Tomorrow\"),\n                        ],\n                    ),\n                    MenuItem::new(\"copy\", \"Copy link\"),\n                ],\n                cx,\n            )\n        });\n        window\n            .update(cx, |menu, window, cx| {\n                menu.open(window, cx);\n                menu.highlight(0, 1, cx);\n                menu.hover_submenu(0, 1, window, cx);\n            })\n            .unwrap();\n        cx.executor().advance_clock(SUBMENU_HOVER_DELAY / 2);\n        cx.run_until_parked();\n        window\n            .update(cx, |menu, _, _| {\n                assert!(menu.path.is_empty(), \"not before the delay\")\n            })\n            .unwrap();\n        cx.executor().advance_clock(SUBMENU_HOVER_DELAY);\n        cx.run_until_parked();\n        window\n            .update(cx, |menu, window, cx| {\n                assert_eq!(menu.path, [1], \"the submenu opened\");\n                menu.highlight(0, 2, cx);\n                menu.hover_submenu(0, 2, window, cx);\n                assert!(menu.path.is_empty(), \"a sibling row closes it\");\n                // Passing over the submenu row on the way elsewhere opens nothing.\n                menu.highlight(0, 1, cx);\n                menu.hover_submenu(0, 1, window, cx);\n                menu.highlight(0, 0, cx);\n                menu.hover_submenu(0, 0, window, cx);\n            })\n            .unwrap();\n        cx.executor().advance_clock(SUBMENU_HOVER_DELAY * 2);\n        cx.run_until_parked();\n        window\n            .update(cx, |menu, _, _| assert!(menu.path.is_empty()))\n            .unwrap();\n    }\n    #[gpui_kit::test]\n    fn check_actions_toggle_and_radio_actions_select_one(cx: &mut gpui_kit::TestAppContext) {\n        cx.update(super::super::theme::init);\n        let window = cx.add_window(|_, cx| {\n            MenuState::new(\n                [\n                    MenuItem::new(\"notifications\", \"Notifications\").checked(true),\n                    MenuItem::new(\"compact\", \"Compact\").radio(true),\n                    MenuItem::new(\"comfortable\", \"Comfortable\").radio(false),\n                    MenuItem::new(\"locked\", \"Locked\")\n                        .checked(true)\n                        .disabled(true),\n                ],\n                cx,\n            )\n        });\n        window\n            .update(cx, |menu, window, cx| {\n                menu.activate(0, 0, &ClickEvent::default(), window, cx);\n                assert_eq!(menu.items[0].checked, Some(false));\n                menu.activate(0, 2, &ClickEvent::default(), window, cx);\n                assert_eq!(menu.items[1].checked, Some(false));\n                assert_eq!(menu.items[2].checked, Some(true));\n                menu.activate(0, 3, &ClickEvent::default(), window, cx);\n                assert_eq!(menu.items[3].checked, Some(true));\n            })\n            .unwrap();\n    }\n}\n"
    },
    {
      "path": "registry/sidebar/sidebar.rs",
      "type": "registry:file",
      "target": "~/src/ui/sidebar.rs",
      "content": "//! Sidebar navigation composed from GPUI Kit buttons, Scroll Area and Tooltip.\n//! Applications own navigation and collapsed state; this component owns no router.\n\nuse super::tooltip::AnchoredTooltip as _;\nuse super::{\n    scroll_area::*,\n    theme::{\n        Direction, UiText, UiTheme,\n        locale::{self, DirectionalStyled as _},\n        primitives::{disabled, text},\n    },\n    tooltip::text_tooltip,\n};\nuse gpui_kit::base::Button as BaseButton;\nuse gpui_kit::{\n    AnyElement, App, Bounds, ClickEvent, Div, Element, ElementId, FocusHandle, FontWeight,\n    GlobalElementId, InspectorElementId, InteractiveElement as _, IntoElement, KeyDownEvent,\n    LayoutId, ParentElement, Pixels, RenderOnce, Role, SharedString,\n    StatefulInteractiveElement as _, Styled, Text, Window, div, prelude::FluentBuilder as _, px,\n};\nuse std::{cell::RefCell, rc::Rc, sync::Arc};\n\ntype SuffixTooltip = Rc<dyn Fn(&mut Window, &mut App) -> gpui_kit::AnyView>;\n\ntype ActivateHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;\nfn part(id: &ElementId, name: &'static str) -> ElementId {\n    ElementId::NamedChild(Arc::new(id.clone()), name.into())\n}\n\n/// A labelled sidebar with fixed header/footer and scrollable navigation content.\n/// Width and collapse state belong to its parent layout.\n#[derive(IntoElement)]\npub struct Sidebar {\n    style: gpui_kit::StyleRefinement,\n    id: ElementId,\n    label: SharedString,\n    header: Option<AnyElement>,\n    header_padding: Option<gpui_kit::Pixels>,\n    content_padding: Option<gpui_kit::Pixels>,\n    footer: Option<AnyElement>,\n    footer_padding: Option<gpui_kit::Pixels>,\n    overlay: Option<AnyElement>,\n    scroll: Option<gpui_kit::ScrollHandle>,\n    roving_focus: bool,\n    surface: bool,\n    children: Vec<AnyElement>,\n}\nimpl Sidebar {\n    /// Creates a navigation region with a caller-owned ID and accessible name.\n    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {\n        Self {\n            style: gpui_kit::StyleRefinement::default(),\n            id: id.into(),\n            label: label.into(),\n            header: None,\n            header_padding: None,\n            content_padding: None,\n            footer: None,\n            footer_padding: None,\n            overlay: None,\n            scroll: None,\n            roving_focus: false,\n            surface: false,\n            children: vec![],\n        }\n    }\n    /// Makes the navigation rows one tab stop, as the APG tree and Slack's\n    /// channel list do. Tab lands on the focused or selected row and the next\n    /// Tab leaves the navigation; Up and Down move between rows, wrapping at\n    /// the ends; Home and End jump to the first and last row; Enter or Space\n    /// activates. Applies to every `SidebarItem` in the scrollable content;\n    /// header, footer and other controls keep their own tab stops. Off by default.\n    pub fn roving_focus(mut self, roving: bool) -> Self {\n        self.roving_focus = roving;\n        self\n    }\n    /// Draws the navigation on the page's muted surface (`muted` background,\n    /// `foreground` text) instead of the sidebar colors, for a section list\n    /// beside a page, such as a settings window, that should not read as a\n    /// second app sidebar. Give its rows [`SidebarItem::surface`] too.\n    pub fn surface(mut self, surface: bool) -> Self {\n        self.surface = surface;\n        self\n    }\n    /// Override the content inset, for example zero for full-width mail rows.\n    /// Header and footer retain their standard inset.\n    pub fn content_padding(mut self, padding: gpui_kit::Pixels) -> Self {\n        self.content_padding = Some(padding.max(px(0.)));\n        self\n    }\n    /// Sets content that remains above the scrollable navigation.\n    pub fn header(mut self, child: impl IntoElement) -> Self {\n        self.header = Some(child.into_any_element());\n        self\n    }\n    /// Sets content that remains below the scrollable navigation.\n    pub fn footer(mut self, child: impl IntoElement) -> Self {\n        self.footer = Some(child.into_any_element());\n        self\n    }\n    /// Overrides the header's inset (8px by default), for example zero for a\n    /// header that draws its own height and padding.\n    pub fn header_padding(mut self, padding: gpui_kit::Pixels) -> Self {\n        self.header_padding = Some(padding.max(px(0.)));\n        self\n    }\n    /// Overrides the footer's inset (8px by default), for example zero for a\n    /// full-width footer with a hairline on top.\n    pub fn footer_padding(mut self, padding: gpui_kit::Pixels) -> Self {\n        self.footer_padding = Some(padding.max(px(0.)));\n        self\n    }\n    /// Floats `child` over the scrolling navigation without scrolling with\n    /// it, such as a \"2 unread below\" pill. Position it with `absolute()`;\n    /// the area it is placed in is the navigation's visible part.\n    pub fn overlay(mut self, child: impl IntoElement) -> Self {\n        self.overlay = Some(child.into_any_element());\n        self\n    }\n    /// Shares the navigation's scroll position with the caller, to read\n    /// what is in view or scroll a row into it. Without it the sidebar keeps\n    /// its own.\n    pub fn track_scroll(mut self, handle: &gpui_kit::ScrollHandle) -> Self {\n        self.scroll = Some(handle.clone());\n        self\n    }\n}\nimpl ParentElement for Sidebar {\n    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {\n        self.children.extend(elements);\n    }\n}\nimpl RenderOnce for Sidebar {\n    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {\n        let roving = self.roving_focus.then(|| {\n            let model = window\n                .use_keyed_state(part(&self.id, \"roving\"), cx, |_, _| RovingModel::default())\n                .read(cx)\n                .clone();\n            model.start_frame(window);\n            model\n        });\n        if let (Some(model), Some(handle)) = (roving.as_ref(), self.scroll.as_ref()) {\n            model.0.borrow_mut().scroll = handle.clone();\n        }\n        let theme = UiTheme::read(cx).clone();\n        let spacing = theme.spacing.unit;\n        let (color, foreground) = if self.surface {\n            (theme.colors.muted, theme.colors.foreground)\n        } else {\n            (theme.colors.sidebar, theme.colors.sidebar_foreground)\n        };\n        let padding = self.content_padding.unwrap_or(spacing * 2_f32);\n        let scroll = self\n            .scroll\n            .clone()\n            .or_else(|| roving.as_ref().map(|model| model.0.borrow().scroll.clone()));\n        let content = ScrollArea::new(part(&self.id, \"scroll\"))\n            .when_some(scroll.as_ref(), |area, handle| area.track_scroll(handle))\n            .size_full()\n            .aria_label(self.label.clone())\n            .child(\n                div()\n                    .w_full()\n                    .min_w_0()\n                    .flex()\n                    .flex_col()\n                    .p(padding)\n                    .children(self.children),\n            );\n        div()\n            .id(self.id)\n            .role(Role::Navigation)\n            .aria_label(self.label)\n            .size_full()\n            .flex()\n            .flex_col()\n            .min_w_0()\n            .min_h_0()\n            .bg(color)\n            .text_color(foreground)\n            .map(|el| text::sm(el, &theme))\n            .when_some(self.header, |el, header| {\n                el.child(\n                    div()\n                        .flex_shrink_0()\n                        .p(self.header_padding.unwrap_or(spacing * 2_f32))\n                        .child(header),\n                )\n            })\n            .child(\n                div()\n                    .relative()\n                    .flex_1()\n                    .min_h_0()\n                    .min_w_0()\n                    .overflow_hidden()\n                    .map(|el| match roving {\n                        Some(model) => {\n                            let keys = model.clone();\n                            // Capture: the scroll area under it scrolls on the arrows.\n                            el.capture_key_down(move |event, window, cx| {\n                                if keys.handle_key(event, window, cx) {\n                                    cx.stop_propagation();\n                                }\n                            })\n                            .child(RovingScope {\n                                model,\n                                child: content.into_any_element(),\n                            })\n                        }\n                        None => el.child(content),\n                    })\n                    .children(self.overlay),\n            )\n            .when_some(self.footer, |el, footer| {\n                el.child(\n                    div()\n                        .flex_shrink_0()\n                        .p(self.footer_padding.unwrap_or(spacing * 2_f32))\n                        .child(footer),\n                )\n            })\n            .map(|base| super::theme::apply_style(base, &self.style))\n    }\n}\n\n/// One navigation row registered with a roving sidebar this frame.\nstruct RovingRow {\n    id: ElementId,\n    focus: FocusHandle,\n    /// Where the row was painted, for scrolling it into view.\n    bounds: Rc<std::cell::Cell<Bounds<Pixels>>>,\n    selected: bool,\n    disabled: bool,\n}\n\n/// The rows of a `Sidebar::roving_focus` sidebar, in visual order, and the\n/// one row that is its tab stop.\n#[derive(Default)]\nstruct Roving {\n    rows: Vec<RovingRow>,\n    target: Option<ElementId>,\n    scroll: gpui_kit::ScrollHandle,\n}\n\nimpl Roving {\n    /// Picks this frame's tab stop from last frame's rows: the focused row,\n    /// else the last one focused, else the selected one, else the first.\n    fn start_frame(&mut self, window: &Window) {\n        let rows = std::mem::take(&mut self.rows);\n        let enabled = |row: &&RovingRow| !row.disabled;\n        let target = rows\n            .iter()\n            .find(|row| row.focus.is_focused(window))\n            .or_else(|| {\n                rows.iter()\n                    .filter(enabled)\n                    .find(|row| Some(&row.id) == self.target.as_ref())\n            })\n            .or_else(|| rows.iter().filter(enabled).find(|row| row.selected))\n            .or_else(|| rows.iter().find(enabled))\n            .map(|row| row.id.clone());\n        self.target = target;\n    }\n\n    /// Records a row and returns whether it is the tab stop.\n    fn register(&mut self, row: RovingRow) -> bool {\n        let tab_stop = match &self.target {\n            Some(target) => *target == row.id,\n            // The first frame has no history: the selected row and the first\n            // enabled row take the stop until the next frame settles on one.\n            None => !row.disabled && (row.selected || self.rows.iter().all(|row| row.disabled)),\n        };\n        self.rows.push(row);\n        tab_stop\n    }\n\n    /// The row to focus for an arrow, Home or End key, if any.\n    fn next(&self, key: &str, window: &Window) -> Option<&RovingRow> {\n        let enabled: Vec<&RovingRow> = self.rows.iter().filter(|row| !row.disabled).collect();\n        let last = enabled.len().checked_sub(1)?;\n        let current = enabled.iter().position(|row| row.focus.is_focused(window));\n        let index = match (key, current) {\n            (\"home\", _) => 0,\n            (\"end\", _) => last,\n            (\"down\", Some(index)) => {\n                if index == last {\n                    0\n                } else {\n                    index + 1\n                }\n            }\n            (\"up\", Some(index)) => {\n                if index == 0 {\n                    last\n                } else {\n                    index - 1\n                }\n            }\n            _ => return None,\n        };\n        Some(enabled[index])\n    }\n\n    /// Scrolls the navigation so `row` and its focus ring are fully visible.\n    fn reveal(&self, row: &RovingRow) {\n        let viewport = self.scroll.bounds();\n        let bounds = row.bounds.get();\n        if viewport.size.height <= px(0.) || bounds.size.height <= px(0.) {\n            return;\n        }\n        // Leave room for the row's border and the 3px outer focus ring.\n        let bounds = bounds.dilate(px(4.));\n        let mut offset = self.scroll.offset();\n        if bounds.top() < viewport.top() {\n            offset.y += viewport.top() - bounds.top();\n        } else if bounds.bottom() > viewport.bottom() {\n            offset.y -= bounds.bottom() - viewport.bottom();\n        } else {\n            return;\n        }\n        let max = self.scroll.max_offset().y.max(px(0.));\n        offset.y = offset.y.clamp(-max, px(0.));\n        self.scroll.set_offset(offset);\n    }\n}\n\n#[derive(Clone, Default)]\nstruct RovingModel(Rc<RefCell<Roving>>);\n\nimpl RovingModel {\n    fn start_frame(&self, window: &Window) {\n        self.0.borrow_mut().start_frame(window);\n    }\n\n    fn handle_key(&self, event: &KeyDownEvent, window: &mut Window, cx: &mut App) -> bool {\n        let modifiers = event.keystroke.modifiers;\n        if modifiers.control || modifiers.alt || modifiers.platform || modifiers.shift {\n            return false;\n        }\n        let roving = self.0.borrow();\n        let Some(row) = roving.next(&event.keystroke.key, window) else {\n            return false;\n        };\n        let focus = row.focus.clone();\n        roving.reveal(row);\n        drop(roving);\n        focus.focus(window, cx);\n        window.refresh();\n        true\n    }\n}\n\nthread_local! {\n    /// The roving sidebars whose content is laying out, innermost last.\n    static ROVING: RefCell<Vec<RovingModel>> = const { RefCell::new(Vec::new()) };\n}\n\n/// Lets the `SidebarItem`s rendered inside a roving sidebar find it: rows\n/// render while their ancestors request layout, so the scope is open exactly\n/// while its content renders.\nstruct RovingScope {\n    model: RovingModel,\n    child: AnyElement,\n}\n\nimpl IntoElement for RovingScope {\n    type Element = Self;\n    fn into_element(self) -> Self {\n        self\n    }\n}\n\nimpl Element for RovingScope {\n    type RequestLayoutState = ();\n    type PrepaintState = ();\n\n    fn id(&self) -> Option<ElementId> {\n        None\n    }\n\n    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {\n        None\n    }\n\n    fn request_layout(\n        &mut self,\n        _: Option<&GlobalElementId>,\n        _: Option<&InspectorElementId>,\n        window: &mut Window,\n        cx: &mut App,\n    ) -> (LayoutId, ()) {\n        ROVING.with(|scopes| scopes.borrow_mut().push(self.model.clone()));\n        let layout = self.child.request_layout(window, cx);\n        ROVING.with(|scopes| scopes.borrow_mut().pop());\n        (layout, ())\n    }\n\n    fn prepaint(\n        &mut self,\n        _: Option<&GlobalElementId>,\n        _: Option<&InspectorElementId>,\n        _: Bounds<Pixels>,\n        _: &mut (),\n        window: &mut Window,\n        cx: &mut App,\n    ) {\n        self.child.prepaint(window, cx);\n    }\n\n    fn paint(\n        &mut self,\n        _: Option<&GlobalElementId>,\n        _: Option<&InspectorElementId>,\n        _: Bounds<Pixels>,\n        _: &mut (),\n        _: &mut (),\n        window: &mut Window,\n        cx: &mut App,\n    ) {\n        self.child.paint(window, cx);\n    }\n}\n\n/// A sidebar section label. Omit it in an icon rail; keep item accessible names.\npub fn sidebar_group_label(label: impl Into<SharedString>, cx: &App) -> Div {\n    let theme = UiTheme::read(cx).clone();\n    let spacing = theme.spacing.unit;\n    div()\n        .flex_row_in(theme.direction)\n        .items_center()\n        .h(spacing * 8_f32)\n        .px(spacing * 2_f32)\n        .map(|el| text::xs(el, &theme))\n        .font_weight(FontWeight::MEDIUM)\n        .text_color(theme.colors.sidebar_muted_foreground())\n        .child(label.into())\n}\n\n/// A navigation action with selected/disabled styling and an optional icon/badge.\n/// Collapsed items keep their accessible name and expose a tooltip. Keep item IDs\n/// stable across rail/expanded layouts so focus survives the change.\n#[derive(IntoElement)]\npub struct SidebarItem {\n    style: gpui_kit::StyleRefinement,\n    id: ElementId,\n    label: SharedString,\n    selected: bool,\n    disabled: bool,\n    collapsed: bool,\n    icon: Option<AnyElement>,\n    label_suffix: Option<AnyElement>,\n    label_suffix_tooltip: Option<SharedString>,\n    label_suffix_tooltip_view: Option<SuffixTooltip>,\n    trailing: Option<AnyElement>,\n    size: SidebarItemSize,\n    outline: bool,\n    surface: bool,\n    expanded: Option<bool>,\n    on_activate: Option<ActivateHandler>,\n}\nimpl SidebarItem {\n    /// Creates a navigation action. Its label is also used for accessibility and tooltips.\n    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {\n        Self {\n            style: gpui_kit::StyleRefinement::default(),\n            id: id.into(),\n            label: label.into(),\n            selected: false,\n            disabled: false,\n            collapsed: false,\n            icon: None,\n            label_suffix: None,\n            label_suffix_tooltip: None,\n            label_suffix_tooltip_view: None,\n            trailing: None,\n            size: SidebarItemSize::Default,\n            outline: false,\n            surface: false,\n            expanded: None,\n            on_activate: None,\n        }\n    }\n    /// Uses the page's colors (`foreground`, `accent` on hover and when\n    /// selected, `ring`) for a row in a [`Sidebar::surface`] navigation.\n    pub fn surface(mut self, surface: bool) -> Self {\n        self.surface = surface;\n        self\n    }\n    /// Marks the current destination with shadcn's active background and medium weight.\n    pub fn selected(mut self, value: bool) -> Self {\n        self.selected = value;\n        self\n    }\n    /// Prevents activation using the shared GPUI Kit button guard.\n    pub fn disabled(mut self, value: bool) -> Self {\n        self.disabled = value;\n        self\n    }\n    /// Shows only the icon (or first character if absent), retaining a full-label tooltip.\n    pub fn collapsed(mut self, value: bool) -> Self {\n        self.collapsed = value;\n        self\n    }\n    /// Sets a caller-rendered leading icon.\n    pub fn icon(mut self, icon: impl IntoElement) -> Self {\n        self.icon = Some(icon.into_any_element());\n        self\n    }\n    /// Adds content right after the label, such as a person's status emoji.\n    /// Unlike `trailing`, it follows the text, so a hover-revealed action at\n    /// the row's end never covers it; a long label truncates before it.\n    pub fn label_suffix(mut self, child: impl IntoElement) -> Self {\n        self.label_suffix = Some(child.into_any_element());\n        self\n    }\n    /// Shows `text` in a tooltip while the pointer is over the label suffix,\n    /// such as the status text behind a status emoji. It is also read after\n    /// the label by assistive technology.\n    pub fn label_suffix_tooltip(mut self, text: impl Into<SharedString>) -> Self {\n        self.label_suffix_tooltip = Some(text.into());\n        self\n    }\n    /// Shows `build`'s view as the suffix's tooltip instead of a plain text\n    /// one, such as `message::emoji_tooltip` for a status emoji. Set\n    /// [`SidebarItem::label_suffix_tooltip`] too: its text is still what\n    /// assistive technology reads.\n    pub fn label_suffix_tooltip_view(\n        mut self,\n        build: impl Fn(&mut Window, &mut App) -> gpui_kit::AnyView + 'static,\n    ) -> Self {\n        self.label_suffix_tooltip_view = Some(Rc::new(build));\n        self\n    }\n    /// Adds noninteractive trailing content, such as a count. Separate actions belong beside the item.\n    pub fn trailing(mut self, child: impl IntoElement) -> Self {\n        self.trailing = Some(child.into_any_element());\n        self\n    }\n    /// Set the menu row size.\n    pub fn size(mut self, size: SidebarItemSize) -> Self {\n        self.size = size;\n        self\n    }\n    /// Use a background surface with a sidebar-colored outline.\n    pub fn outline(mut self, outline: bool) -> Self {\n        self.outline = outline;\n        self\n    }\n    /// Announces disclosure state when this item controls a nested menu.\n    pub fn expanded(mut self, expanded: bool) -> Self {\n        self.expanded = Some(expanded);\n        self\n    }\n    /// Emits activation without owning routing or selection state.\n    pub fn on_activate(\n        mut self,\n        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,\n    ) -> Self {\n        self.on_activate = Some(Rc::new(handler));\n        self\n    }\n}\nimpl RenderOnce for SidebarItem {\n    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {\n        // Inside a roving sidebar, the row uses a handle the sidebar can move\n        // focus to, and only one row is a tab stop.\n        let roving = ROVING\n            .with(|scopes| scopes.borrow().last().cloned())\n            .map(|model| {\n                let focus = window\n                    .use_keyed_state(part(&self.id, \"focus\"), cx, |_, cx| cx.focus_handle())\n                    .read(cx)\n                    .clone();\n                let bounds = Rc::new(std::cell::Cell::new(Bounds::default()));\n                let tab_stop = model.0.borrow_mut().register(RovingRow {\n                    id: self.id.clone(),\n                    focus: focus.clone(),\n                    bounds: bounds.clone(),\n                    selected: self.selected,\n                    disabled: self.disabled,\n                });\n                (focus, tab_stop, bounds)\n            });\n        let theme = UiTheme::read(cx).clone();\n        let spacing = theme.spacing.unit;\n        let selected = self.selected;\n        let size = self.size;\n        let outline = self.outline;\n        let c = &theme.colors;\n        // (rest, foreground, active, active foreground, border, ring)\n        let (rest, fg, active, active_fg, border, ring) = if self.surface {\n            (\n                c.muted,\n                c.foreground,\n                c.accent,\n                c.accent_foreground,\n                c.border,\n                c.ring,\n            )\n        } else {\n            (\n                c.sidebar,\n                c.sidebar_foreground,\n                c.sidebar_accent,\n                c.sidebar_accent_foreground,\n                c.sidebar_border,\n                c.sidebar_ring,\n            )\n        };\n        let collapsed = self.collapsed;\n        let mut accessible = self.label.to_string();\n        if let Some(text) = self\n            .label_suffix\n            .as_ref()\n            .and(self.label_suffix_tooltip.as_ref())\n        {\n            accessible.push_str(\", \");\n            accessible.push_str(text);\n        }\n        let mut append = |text: UiText| {\n            accessible.push_str(\", \");\n            accessible.push_str(&locale::text(cx, text));\n        };\n        if selected {\n            append(UiText::CurrentDestination);\n        }\n        if self.disabled {\n            append(UiText::Unavailable);\n        }\n        if let Some(expanded) = self.expanded {\n            append(if expanded {\n                UiText::Expanded\n            } else {\n                UiText::Collapsed\n            });\n        }\n        let icon = self.icon.or_else(|| {\n            collapsed.then(|| {\n                Text::new_inaccessible(self.label.chars().next().unwrap_or(' ').to_string().into())\n                    .into_any_element()\n            })\n        });\n        let tooltip_label = self.label.clone();\n        BaseButton::new(part(&self.id, \"button\"))\n            .accessibility_label(accessible)\n            .disabled(self.disabled)\n            .when_some(roving, |base, (focus, tab_stop, bounds)| {\n                base.track_focus(&focus).tab_stop(tab_stop).child(\n                    gpui_kit::canvas(move |row, _, _| bounds.set(row), |_, _, _, _| {})\n                        .absolute()\n                        .size_full(),\n                )\n            })\n            .map(|base| {\n                let base = {\n                    let mut base = base;\n                    let label = tooltip_label.clone();\n                    if collapsed {\n                        base = base.anchored_tooltip(move |_, cx| text_tooltip(label.clone(), cx));\n                    }\n                    base.relative()\n                        .flex_row_in(theme.direction)\n                        .w_full()\n                        .h(spacing\n                            * if collapsed {\n                                8_f32\n                            } else {\n                                match size {\n                                    SidebarItemSize::Small => 7.,\n                                    SidebarItemSize::Default => 8.,\n                                    SidebarItemSize::Large => 12.,\n                                }\n                            })\n                        .text_size(\n                            px(if size == SidebarItemSize::Small {\n                                12.\n                            } else {\n                                14.\n                            }) * theme.text_scale,\n                        )\n                        .line_height(\n                            px(if size == SidebarItemSize::Small {\n                                16.\n                            } else {\n                                20.\n                            }) * theme.text_scale,\n                        )\n                        .font_family(theme.fonts.body.clone())\n                        .font_weight(FontWeight::NORMAL)\n                        .border_1()\n                        .border_color(if outline { border } else { rest.opacity(0.) })\n                        .min_w_0()\n                        .flex_shrink_0()\n                        .items_center()\n                        .gap(spacing * 2_f32)\n                        .px(spacing * 2_f32)\n                        .rounded(theme.radius.md)\n                        .text_color(if selected { active_fg } else { fg })\n                        .bg(if selected {\n                            active\n                        } else if outline {\n                            theme.colors.background\n                        } else {\n                            rest\n                        })\n                        .when(selected, |el| el.font_weight(FontWeight::MEDIUM))\n                        .when(collapsed, |el| el.w(spacing * 8_f32).justify_center())\n                        .when(self.disabled, disabled::style)\n                        // The selected item is already in its active\n                        // colors; hovering it changes nothing, so an app's\n                        // own selected colors stay put too.\n                        .when(!self.disabled, |el| el.cursor_pointer())\n                        .when(!self.disabled && !selected, |el| {\n                            el.hover(|style| style.bg(active).text_color(active_fg))\n                        })\n                        .focus_visible(|style| style.border_color(ring))\n                };\n                super::theme::apply_style(base, &self.style)\n            })\n            .on_click(move |event, window, cx| {\n                if let Some(handler) = &self.on_activate {\n                    handler(event, window, cx);\n                }\n            })\n            .when_some(icon, |el, icon| el.child(div().flex_shrink_0().child(icon)))\n            .when(!collapsed, |el| {\n                let label = div()\n                    .min_w_0()\n                    .truncate()\n                    .child(Text::new_inaccessible(self.label.clone()));\n                match self.label_suffix {\n                    None => el.child(label.flex_1()),\n                    Some(suffix) => {\n                        let tooltip = self.label_suffix_tooltip.clone();\n                        let tooltip_view = self.label_suffix_tooltip_view.clone();\n                        el.child(\n                            div()\n                                .flex_1()\n                                .min_w_0()\n                                .flex_row_in(theme.direction)\n                                .items_center()\n                                .gap(spacing * 1.5_f32)\n                                .child(label.flex_shrink(1.))\n                                .child(\n                                    div()\n                                        .id(part(&self.id, \"suffix\"))\n                                        .flex_none()\n                                        .flex()\n                                        .items_center()\n                                        .map(|suffix| match (tooltip_view, tooltip) {\n                                            (Some(build), _) => {\n                                                suffix.anchored_tooltip(move |window, cx| {\n                                                    build(window, cx)\n                                                })\n                                            }\n                                            (None, Some(text)) => {\n                                                suffix.anchored_tooltip(move |_, cx| {\n                                                    text_tooltip(text.clone(), cx)\n                                                })\n                                            }\n                                            (None, None) => suffix,\n                                        })\n                                        .child(suffix),\n                                ),\n                        )\n                    }\n                }\n            })\n            .when(!collapsed, |el| {\n                el.when_some(self.trailing, |el, content| {\n                    el.child(div().flex_shrink_0().child(content))\n                })\n            })\n    }\n}\n\nimpl gpui_kit::Styled for Sidebar {\n    fn style(&mut self) -> &mut gpui_kit::StyleRefinement {\n        &mut self.style\n    }\n}\n\nimpl gpui_kit::Styled for SidebarItem {\n    fn style(&mut self) -> &mut gpui_kit::StyleRefinement {\n        &mut self.style\n    }\n}\n\n/// Which edge contains the navigation.\n#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]\npub enum SidebarSide {\n    #[default]\n    /// Navigation before the content: on the left, or the right in\n    /// right-to-left layouts.\n    Left,\n    /// Navigation after the content: on the right, or the left in\n    /// right-to-left layouts.\n    Right,\n}\n\nimpl SidebarSide {\n    /// The edge on screen for this layout direction.\n    pub fn physical(self, direction: Direction) -> Self {\n        match (direction, self) {\n            (Direction::Rtl, Self::Left) => Self::Right,\n            (Direction::Rtl, Self::Right) => Self::Left,\n            _ => self,\n        }\n    }\n}\n/// The three shadcn application layouts.\n#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]\npub enum SidebarVariant {\n    #[default]\n    /// Full-height navigation with an edge border.\n    Sidebar,\n    /// A rounded, bordered navigation surface.\n    Floating,\n    /// Content inset into the sidebar-colored shell.\n    Inset,\n}\n/// Desktop collapse behavior. Mobile uses a modal sheet except for `None`.\n#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]\npub enum SidebarCollapsible {\n    #[default]\n    /// Completely hide desktop navigation when closed.\n    Offcanvas,\n    /// Keep a compact icon rail when closed.\n    Icon,\n    /// Always display full navigation, including on narrow windows.\n    None,\n}\n/// Caller-owned state. Desktop preference survives opening and closing mobile navigation.\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub struct SidebarState {\n    /// Desktop expanded preference.\n    pub open: bool,\n    /// Whether the mobile sheet is open.\n    pub mobile_open: bool,\n}\nimpl Default for SidebarState {\n    fn default() -> Self {\n        Self {\n            open: true,\n            mobile_open: false,\n        }\n    }\n}\nimpl SidebarState {\n    /// Toggle the state for the active viewport.\n    pub fn toggle(&mut self, mobile: bool) {\n        if mobile {\n            self.mobile_open = !self.mobile_open;\n        } else {\n            self.open = !self.open;\n        }\n    }\n    /// Whether navigation should render icons without labels.\n    pub fn icon_collapsed(self, mobile: bool, mode: SidebarCollapsible) -> bool {\n        !mobile && !self.open && mode == SidebarCollapsible::Icon\n    }\n}\n\n/// Uses the available GPUI window width, including an embedded preview's viewport,\n/// against `theme.breakpoints.mobile`. Pass the same result to the layout and\n/// menu composition. Applications with a narrower nested pane can instead\n/// supply their own breakpoint decision.\npub fn sidebar_is_mobile(window: &Window, cx: &App) -> bool {\n    window.viewport_size().width < UiTheme::read(cx).breakpoints.mobile\n}\n\nstruct SidebarFocus {\n    mobile_open: bool,\n    return_to: Option<gpui_kit::FocusHandle>,\n    navigation: gpui_kit::FocusHandle,\n    content: gpui_kit::FocusHandle,\n    sheet: gpui_kit::FocusHandle,\n}\n\ntype StateHandler = Rc<dyn Fn(&SidebarState, &mut Window, &mut App)>;\n\n/// A controlled application shell. Supplies side, variant, animated desktop width,\n/// keyboard toggle and a focus-trapped mobile sheet. Render menu labels using\n/// `state.icon_collapsed(mobile, mode)`; the mobile sheet always gets full labels.\n#[derive(IntoElement)]\npub struct SidebarLayout {\n    id: ElementId,\n    state: SidebarState,\n    mobile: bool,\n    side: SidebarSide,\n    variant: SidebarVariant,\n    collapsible: SidebarCollapsible,\n    width: Option<gpui_kit::Pixels>,\n    icon_width: Option<gpui_kit::Pixels>,\n    mobile_width: Option<gpui_kit::Pixels>,\n    rail: bool,\n    sidebar: AnyElement,\n    content: AnyElement,\n    on_change: StateHandler,\n    style: gpui_kit::StyleRefinement,\n}\nimpl SidebarLayout {\n    /// Compose navigation and application content with controlled state.\n    /// Store the state passed to [`SidebarLayout::on_change`] and pass it back here.\n    pub fn new(id: impl Into<ElementId>, state: SidebarState) -> Self {\n        Self {\n            id: id.into(),\n            state,\n            mobile: false,\n            side: SidebarSide::Left,\n            variant: SidebarVariant::Sidebar,\n            collapsible: SidebarCollapsible::Offcanvas,\n            width: None,\n            icon_width: None,\n            mobile_width: None,\n            rail: false,\n            sidebar: gpui_kit::Empty.into_any_element(),\n            content: gpui_kit::Empty.into_any_element(),\n            on_change: Rc::new(|_, _, _| {}),\n            style: Default::default(),\n        }\n    }\n    /// Use the narrow-viewport sheet; pass `sidebar_is_mobile(window, cx)` or your own\n    /// breakpoint, and use the same value for triggers and `state.icon_collapsed`.\n    pub fn mobile(mut self, mobile: bool) -> Self {\n        self.mobile = mobile;\n        self\n    }\n    /// Sets the navigation, usually a [`Sidebar`].\n    pub fn sidebar(mut self, sidebar: impl IntoElement) -> Self {\n        self.sidebar = sidebar.into_any_element();\n        self\n    }\n    /// Sets the application content beside the navigation.\n    pub fn content(mut self, content: impl IntoElement) -> Self {\n        self.content = content.into_any_element();\n        self\n    }\n    /// Receives the next state after the trigger, rail, shortcut or sheet changes it.\n    pub fn on_change(\n        mut self,\n        on_change: impl Fn(&SidebarState, &mut Window, &mut App) + 'static,\n    ) -> Self {\n        self.on_change = Rc::new(on_change);\n        self\n    }\n    /// Add a pointer rail along the navigation edge. Keep a visible keyboard trigger.\n    pub fn rail(mut self, rail: bool) -> Self {\n        self.rail = rail;\n        self\n    }\n    /// Set the navigation edge.\n    pub fn side(mut self, side: SidebarSide) -> Self {\n        self.side = side;\n        self\n    }\n    /// Set the application layout.\n    pub fn variant(mut self, variant: SidebarVariant) -> Self {\n        self.variant = variant;\n        self\n    }\n    /// Set desktop collapse behavior.\n    pub fn collapsible(mut self, mode: SidebarCollapsible) -> Self {\n        self.collapsible = mode;\n        self\n    }\n    /// Icon rail width before floating/inset gutters; defaults to a themed 48px.\n    pub fn icon_width(mut self, width: gpui_kit::Pixels) -> Self {\n        self.icon_width = Some(width);\n        self\n    }\n    /// Mobile sheet width; defaults to a themed 288px and cannot exceed its viewport.\n    pub fn mobile_width(mut self, width: gpui_kit::Pixels) -> Self {\n        self.mobile_width = Some(width);\n        self\n    }\n    /// Expanded width. Invalid values fall back to the themed 256px default.\n    pub fn width(mut self, width: gpui_kit::Pixels) -> Self {\n        self.width = Some(width);\n        self\n    }\n}\nimpl Styled for SidebarLayout {\n    fn style(&mut self) -> &mut gpui_kit::StyleRefinement {\n        &mut self.style\n    }\n}\nimpl RenderOnce for SidebarLayout {\n    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {\n        use super::dialog::*;\n        use super::theme::transition_value;\n        let theme = UiTheme::read(cx).clone();\n        let s = theme.spacing.unit;\n        let side = self.side.physical(theme.direction);\n        let mobile = self.mobile && self.collapsible != SidebarCollapsible::None;\n        let inset = self.variant == SidebarVariant::Inset && !mobile;\n        let floating = self.variant == SidebarVariant::Floating && !mobile;\n        let padded = inset || floating;\n        let valid_width = |width: Option<gpui_kit::Pixels>, default| {\n            width\n                .filter(|w| f32::from(*w).is_finite() && *w > px(0.))\n                .unwrap_or(default)\n        };\n        let expanded = valid_width(self.width, s * 64_f32);\n        let icon_width = valid_width(self.icon_width, s * 12_f32).max(s * 12_f32);\n        let mobile_width = valid_width(self.mobile_width, s * 72_f32);\n        let collapsed = !self.state.open && self.collapsible != SidebarCollapsible::None;\n        let hidden = mobile || (collapsed && self.collapsible == SidebarCollapsible::Offcanvas);\n        let target = if hidden {\n            px(0.)\n        } else if collapsed {\n            icon_width + if padded { s * 4_f32 } else { px(0.) }\n        } else {\n            expanded + if padded { s * 4_f32 } else { px(0.) }\n        };\n        let width = px(transition_value(\n            part(&self.id, \"width\"),\n            target.into(),\n            theme.motion.normal,\n            window,\n            cx,\n        ));\n        let focus = window.use_keyed_state(part(&self.id, \"focus\"), cx, |_, cx| SidebarFocus {\n            mobile_open: false,\n            return_to: None,\n            navigation: cx.focus_handle(),\n            content: cx.focus_handle(),\n            sheet: cx.focus_handle(),\n        });\n        let (navigation_focus, content_focus, sheet_focus) = focus.update(cx, |focus, cx| {\n            let sheet_open = mobile && self.state.mobile_open;\n            if sheet_open && !focus.mobile_open {\n                focus.return_to = window.focused(cx);\n                // Base's controlled open reconciliation does not request focus.\n                // Focus a descendant that participates in the popup's key context.\n                focus.sheet.focus(window, cx);\n            } else if !sheet_open && focus.mobile_open {\n                if let Some(handle) = focus.return_to.take() {\n                    handle.focus(window, cx);\n                }\n            } else if hidden && focus.navigation.contains_focused(window, cx) {\n                focus.content.focus(window, cx);\n            }\n            focus.mobile_open = sheet_open;\n            (\n                focus.navigation.clone(),\n                focus.content.clone(),\n                focus.sheet.clone(),\n            )\n        });\n        let state = self.state;\n        let change = self.on_change.clone();\n        let main = div()\n            .track_focus(&content_focus)\n            .text_start(theme.direction)\n            .flex_1()\n            .min_w_0()\n            .min_h_0()\n            .overflow_hidden()\n            .bg(theme.colors.background)\n            .when(inset, |el| {\n                el.m(s * 2_f32)\n                    .when(!collapsed && side == SidebarSide::Left, |el| el.ml(px(0.)))\n                    .when(!collapsed && side == SidebarSide::Right, |el| el.mr(px(0.)))\n                    .rounded(theme.radius.xl)\n                    .shadow(theme.shadows.sm.to_vec())\n            })\n            .child(self.content);\n        let mut shell = div()\n            .id(self.id.clone())\n            .size_full()\n            .min_w_0()\n            .min_h_0()\n            .flex()\n            .bg(theme.colors.sidebar)\n            .map(|el| text::sm(el, &theme))\n            .when(side == SidebarSide::Right, |el| el.flex_row_reverse())\n            .on_key_down(move |event, window, cx| {\n                if event.keystroke.key == \"b\"\n                    && (event.keystroke.modifiers.platform || event.keystroke.modifiers.control)\n                    && self.collapsible != SidebarCollapsible::None\n                {\n                    let mut next = state;\n                    next.toggle(mobile);\n                    change(&next, window, cx);\n                    window.prevent_default();\n                    cx.stop_propagation();\n                }\n            });\n        if mobile {\n            let id = part(&self.id, \"sheet\");\n            let popup_focus = modal_focus::prepare(id.clone(), self.state.mobile_open, window, cx);\n            let focus = modal_focus::ModalFocus::new(id.clone());\n            let popup = focus\n                .trap(div(), true)\n                .id(id)\n                .track_focus(&popup_focus)\n                .text_start(theme.direction)\n                .aria_label(locale::text(cx, UiText::Navigation))\n                .occlude()\n                .h_full()\n                .w(mobile_width)\n                .max_w_full()\n                .flex()\n                .flex_col()\n                .bg(theme.colors.sidebar)\n                .text_color(theme.colors.sidebar_foreground)\n                .child(focus.boundary(false))\n                .child(focus.boundary(true))\n                .child(\n                    div()\n                        .size_full()\n                        .track_focus(&sheet_focus)\n                        .child(self.sidebar),\n                );\n            let change = self.on_change;\n            let root = Dialog::new(cx)\n                .open(self.state.mobile_open)\n                .on_ok(|_, _, _| false)\n                .on_open_change(move |open, _, window, cx| {\n                    change(\n                        &SidebarState {\n                            mobile_open: open,\n                            ..state\n                        },\n                        window,\n                        cx,\n                    );\n                })\n                .backdrop(dismiss_backdrop(cx))\n                .popup(\n                    div()\n                        .absolute()\n                        .inset_0()\n                        .flex()\n                        .when(side == SidebarSide::Right, |el| el.justify_end())\n                        .child(popup),\n                );\n            shell = shell.child(main).child(root);\n        } else {\n            let navigation = div()\n                .track_focus(&navigation_focus)\n                .text_start(theme.direction)\n                .w(width)\n                .h_full()\n                .flex_shrink_0()\n                .overflow_hidden()\n                .when(padded, |el| el.p(s * 2_f32))\n                .when(!padded, |el| {\n                    el.border_color(theme.colors.sidebar_border)\n                        .when(side == SidebarSide::Left, |el| el.border_r_1())\n                        .when(side == SidebarSide::Right, |el| el.border_l_1())\n                })\n                // Fully hidden navigation is removed immediately from focus traversal.\n                .when(!hidden, |el| {\n                    el.child(\n                        div()\n                            .size_full()\n                            .overflow_hidden()\n                            .when(floating, |el| {\n                                el.rounded(theme.radius.lg)\n                                    .border_1()\n                                    .border_color(theme.colors.sidebar_border)\n                                    .shadow(theme.shadows.sm.to_vec())\n                            })\n                            .child(self.sidebar),\n                    )\n                });\n            shell = shell.child(navigation).child(main);\n            if self.rail && self.collapsible != SidebarCollapsible::None {\n                let change = self.on_change;\n                shell = shell.relative().child(\n                    sidebar_rail(\n                        part(&self.id, \"rail\"),\n                        move |_, window, cx| {\n                            let mut state = state;\n                            state.toggle(false);\n                            change(&state, window, cx);\n                        },\n                        cx,\n                    )\n                    .absolute()\n                    .top_0()\n                    .when(side == SidebarSide::Left, |el| {\n                        el.left((width - s).max(px(0.)))\n                    })\n                    .when(side == SidebarSide::Right, |el| {\n                        el.right((width - s).max(px(0.)))\n                    }),\n                );\n            }\n        }\n        super::theme::apply_style(shell, &self.style)\n    }\n}\n\n/// A keyboard-accessible toggle. Share the same callback with the layout and rail.\npub fn sidebar_trigger(\n    id: impl Into<ElementId>,\n    on_toggle: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,\n    cx: &App,\n) -> super::button::Button {\n    super::button::Button::new(id)\n        .variant(super::button::ButtonVariant::Ghost)\n        .size(super::button::ButtonSize::IconSm)\n        .aria_label(locale::text(cx, UiText::ToggleSidebar))\n        .child(\n            gpui_icons::lucide(UiTheme::read(cx).direction.icon(\n                false,\n                gpui_icons::LucideIcon::PanelLeft,\n                gpui_icons::LucideIcon::PanelRight,\n            ))\n            .size(UiTheme::read(cx).spacing.unit * 4_f32)\n            .text_color(UiTheme::read(cx).colors.sidebar_foreground),\n        )\n        .on_click(on_toggle)\n}\n\n/// Group container. Header, menu and group action can be composed freely.\npub fn sidebar_group() -> Div {\n    div().relative().w_full().min_w_0().flex().flex_col()\n}\n/// A vertical menu with Nova's contiguous rows.\npub fn sidebar_menu() -> Div {\n    div().w_full().min_w_0().flex().flex_col()\n}\n/// Nested navigation. Omit it when its parent is closed or the sidebar is an icon rail.\npub fn sidebar_menu_sub(cx: &App) -> Div {\n    let t = UiTheme::read(cx);\n    let s = t.spacing.unit;\n    div()\n        .min_w_0()\n        .flex()\n        .flex_col()\n        .gap(s)\n        .mx(s * 3.5_f32)\n        .px(s * 2.5_f32)\n        .py(s * 0.5_f32)\n        .border_start_1(t.direction)\n        .border_color(t.colors.sidebar_border)\n}\n/// Noninteractive count that inherits sidebar colors.\npub fn sidebar_badge(label: impl Into<SharedString>, cx: &App) -> Div {\n    let t = UiTheme::read(cx);\n    let s = t.spacing.unit;\n    div()\n        .h(s * 5_f32)\n        .min_w(s * 5_f32)\n        .px(s)\n        .flex()\n        .items_center()\n        .justify_center()\n        .rounded(t.radius.md)\n        .map(|el| text::xs(el, t))\n        .font_weight(FontWeight::MEDIUM)\n        .child(label.into())\n}\n/// A mention count on the `sidebar_badge` fill, for unread mentions of the\n/// reader; `sidebar_badge` is the plain count.\npub fn sidebar_mention_badge(label: impl Into<SharedString>, cx: &App) -> Div {\n    let t = UiTheme::read(cx);\n    sidebar_badge(label, cx)\n        .rounded_full()\n        .px(t.spacing.unit * 1.5_f32)\n        .bg(t.colors.sidebar_badge())\n        .text_color(t.colors.sidebar_badge_foreground())\n}\n/// Separator between navigation groups.\npub fn sidebar_separator(cx: &App) -> Div {\n    let t = UiTheme::read(cx);\n    div()\n        .h(px(1.))\n        .my(t.spacing.unit * 2_f32)\n        .flex_shrink_0()\n        .bg(t.colors.sidebar_border)\n}\n/// Sidebar-sized text field; input editing and accessibility remain in the existing Input.\npub fn sidebar_input(\n    state: &gpui_kit::Entity<super::input::InputState>,\n    cx: &App,\n) -> super::input::Input {\n    let t = UiTheme::read(cx);\n    super::input::Input::new(state)\n        .h(t.spacing.unit * 8_f32)\n        .w_full()\n        .bg(t.colors.background)\n}\n/// A stable loading placeholder, with optional icon. No random widths or idle animation.\npub fn sidebar_menu_skeleton(show_icon: bool, cx: &App) -> Div {\n    let t = UiTheme::read(cx);\n    let s = t.spacing.unit;\n    div()\n        .h(s * 8_f32)\n        .px(s * 2_f32)\n        .flex_row_in(t.direction)\n        .items_center()\n        .gap(s * 2_f32)\n        .when(show_icon, |el| {\n            el.child(\n                div()\n                    .size(s * 4_f32)\n                    .rounded(t.radius.md)\n                    .bg(t.colors.muted),\n            )\n        })\n        .child(\n            div()\n                .h(s * 4_f32)\n                .w(s * 28_f32)\n                .rounded(t.radius.md)\n                .bg(t.colors.muted),\n        )\n}\n\n/// Nova menu row sizes. Collapsed rows always use the icon size.\n#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]\npub enum SidebarItemSize {\n    /// 28px high, 12px text at the default theme scale.\n    Small,\n    /// 32px high, 14px text.\n    #[default]\n    Default,\n    /// 48px high, suitable for workspace and account controls.\n    Large,\n}\n/// A named secondary action. Place beside the menu button, never inside it.\npub fn sidebar_menu_action(\n    id: impl Into<ElementId>,\n    label: impl Into<SharedString>,\n    cx: &App,\n) -> super::button::Button {\n    let t = UiTheme::read(cx);\n    super::button::Button::new(id)\n        .aria_label(label)\n        .variant(super::button::ButtonVariant::Sidebar)\n        .size(super::button::ButtonSize::IconXs)\n        .text_color(t.colors.sidebar_foreground)\n}\n/// A narrow pointer target along the navigation edge. Keep a visible trigger for keyboard users.\npub fn sidebar_rail(\n    id: impl Into<ElementId>,\n    on_toggle: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,\n    cx: &App,\n) -> gpui_kit::Stateful<Div> {\n    let border = UiTheme::read(cx).colors.sidebar_border;\n    div()\n        .id(id)\n        .w(px(8.))\n        .h_full()\n        .flex_shrink_0()\n        .cursor_col_resize()\n        .hover(move |el| el.bg(border))\n        .on_click(on_toggle)\n}\n\n/// A sidebar menu with caller-owned state and a readable trigger label.\n/// Collapsed triggers fit the icon rail; expanded triggers leave room for two-line labels.\npub fn sidebar_dropdown(\n    state: &gpui_kit::Entity<super::menu::MenuState>,\n    label: impl Into<SharedString>,\n    collapsed: bool,\n    cx: &App,\n) -> super::menu::Menu {\n    let theme = UiTheme::read(cx).clone();\n    super::menu::Menu::new(state, label)\n        .w_full()\n        .trigger_style_with(move |button| {\n            button\n                .w_full()\n                .h_auto()\n                .min_h(theme.space(if collapsed { 8. } else { 12. }))\n                .p(if collapsed {\n                    px(0.)\n                } else {\n                    theme.space(2.) - px(1.)\n                })\n                .when(collapsed, |button| button.h(theme.space(8.)))\n                .rounded(theme.radius.lg)\n                .border_1()\n                .border_color(theme.colors.sidebar.opacity(0.))\n                .cursor_pointer()\n                .font_family(theme.fonts.body.clone())\n                .text_size(theme.text(14.))\n                .line_height(theme.text(20.))\n                .focus_visible(move |style| style.border_color(theme.colors.sidebar_ring))\n                .bg(theme.colors.sidebar)\n                .text_color(theme.colors.sidebar_foreground)\n                .hover(move |style| {\n                    style\n                        .bg(theme.colors.sidebar_accent)\n                        .text_color(theme.colors.sidebar_accent_foreground)\n                })\n        })\n}\n\n#[cfg(test)]\nmod sidebar_tests {\n    use super::*;\n    #[gpui_kit::test]\n    fn dropdown_trigger_fits_expanded_labels_and_collapsed_icons(\n        cx: &mut gpui_kit::TestAppContext,\n    ) {\n        use super::super::menu::MenuState;\n        use gpui_kit::{AppContext as _, Context, Entity, Render};\n        struct Probe {\n            state: Entity<MenuState>,\n            collapsed: bool,\n        }\n        impl Render for Probe {\n            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {\n                div().flex().flex_col().items_start().child(\n                    div()\n                        .w(px(if self.collapsed { 32. } else { 240. }))\n                        .debug_selector(|| \"header\".into())\n                        .child(\n                            sidebar_dropdown(&self.state, \"Workspace\", self.collapsed, cx).trigger(\n                                div()\n                                    .w_full()\n                                    .h(px(if self.collapsed { 32. } else { 34. }))\n                                    .debug_selector(|| \"team-content\".into()),\n                            ),\n                        ),\n                )\n            }\n        }\n        cx.update(super::super::theme::init);\n        for collapsed in [false, true] {\n            let (_, visual) = cx.add_window_view(move |_, cx| Probe {\n                state: cx.new(|cx| MenuState::new(vec![], cx)),\n                collapsed,\n            });\n            visual.update(|window, cx| window.draw(cx).clear(cx));\n            let header = visual.debug_bounds(\"header\").unwrap();\n            let content = visual.debug_bounds(\"team-content\").unwrap();\n            let padding = px(if collapsed { 1. } else { 8. });\n            assert_eq!(content.left() - header.left(), padding);\n            assert_eq!(header.right() - content.right(), padding);\n            let vertical_padding = if collapsed { px(0.) } else { padding };\n            assert!(content.top() - header.top() >= vertical_padding);\n            assert!(header.bottom() - content.bottom() >= vertical_padding);\n            if collapsed {\n                assert_eq!(header.size.height, px(32.));\n            }\n        }\n    }\n\n    #[gpui_kit::test]\n    fn the_label_suffix_follows_the_label_and_stays_visible(cx: &mut gpui_kit::TestAppContext) {\n        use gpui_kit::{Context, Render, test::TestQueryExt as _};\n        struct Probe(&'static str);\n        impl Render for Probe {\n            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {\n                div().w(px(200.)).child(\n                    SidebarItem::new(\"dm\", self.0)\n                        .label_suffix(div().size(px(16.)).debug_selector(|| \"suffix\".into()))\n                        .label_suffix_tooltip(\"In a meeting\")\n                        .trailing(div().size(px(16.)).debug_selector(|| \"trailing\".into())),\n                )\n            }\n        }\n        cx.update(super::super::theme::init);\n        let (_, short) = cx.add_window_view(|_, _| Probe(\"Ana\"));\n        short.update(|window, cx| window.draw(cx).clear(cx));\n        let (suffix, trailing) = (\n            short.debug_bounds(\"suffix\").unwrap(),\n            short.debug_bounds(\"trailing\").unwrap(),\n        );\n        // Right after a short name, not at the row's end.\n        assert!(suffix.right() < trailing.left() - px(80.));\n        short.update(|window, _| {\n            assert!(window.find_by_label(\"Ana, In a meeting\").role().is_some());\n        });\n        let (_, long) = cx.add_window_view(|_, _| {\n            Probe(\"A very long display name that cannot fit in the sidebar row\")\n        });\n        long.update(|window, cx| window.draw(cx).clear(cx));\n        let (suffix, trailing) = (\n            long.debug_bounds(\"suffix\").unwrap(),\n            long.debug_bounds(\"trailing\").unwrap(),\n        );\n        // The name truncates; the suffix keeps its size before the trailing slot.\n        assert_eq!(suffix.size.width, px(16.));\n        assert!(suffix.right() <= trailing.left());\n    }\n\n    #[test]\n    fn mobile_and_desktop_state_are_independent() {\n        let mut state = SidebarState::default();\n        state.toggle(false);\n        assert!(state.icon_collapsed(false, SidebarCollapsible::Icon));\n        state.toggle(true);\n        assert!(!state.open && state.mobile_open);\n        assert!(!state.icon_collapsed(true, SidebarCollapsible::Icon));\n        assert!(!state.icon_collapsed(false, SidebarCollapsible::None));\n        state.toggle(true);\n        assert!(!state.open && !state.mobile_open);\n    }\n    #[test]\n    fn controlled_sheet_takes_focus_wraps_tabs_and_restores_the_opener() {\n        use gpui_kit::{\n            AppContext as _, Context, FocusHandle, Render, TestAppContext, VisualTestContext,\n        };\n        struct View {\n            state: SidebarState,\n            opener: FocusHandle,\n            first: FocusHandle,\n            last: FocusHandle,\n        }\n        impl Render for View {\n            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {\n                let navigation = Sidebar::new(\"test.nav\", \"Navigation\")\n                    .child(\n                        div()\n                            .id(\"test.first\")\n                            .track_focus(&self.first.clone().tab_stop(true))\n                            .child(\"First\"),\n                    )\n                    .child(\n                        div()\n                            .id(\"test.last\")\n                            .track_focus(&self.last.clone().tab_stop(true))\n                            .child(\"Last\"),\n                    );\n                let main = div()\n                    .id(\"test.opener\")\n                    .track_focus(&self.opener.clone().tab_stop(true))\n                    .child(\"Open\");\n                SidebarLayout::new(\"test.layout\", self.state)\n                    .mobile(true)\n                    .sidebar(navigation)\n                    .content(main)\n                    .on_change(cx.listener(|this, state: &SidebarState, _, cx| {\n                        this.state = *state;\n                        cx.notify();\n                    }))\n            }\n        }\n        // Declared first so it is dropped after `cx`: GPUI Kit 0.8 deadlocks when\n        // an app is dropped after its test scheduler.\n        let dispatcher = gpui_kit::TestDispatcher::new(0);\n        let mut cx = TestAppContext::build(dispatcher.clone(), None);\n        cx.update(|cx| {\n            super::super::theme::init(cx);\n            UiTheme::set(cx, UiTheme::neutral_light());\n        });\n        let window = cx.add_window(|_, cx| View {\n            state: SidebarState::default(),\n            opener: cx.focus_handle(),\n            first: cx.focus_handle(),\n            last: cx.focus_handle(),\n        });\n        let mut visual = VisualTestContext::from_window(window.into(), &cx);\n        cx.update_window(window.into(), |view, window, cx| {\n            let view = view.downcast::<View>().unwrap();\n            window.draw(cx).clear(cx);\n            view.update(cx, |view, cx| {\n                view.opener.focus(window, cx);\n                view.state.mobile_open = true;\n                cx.notify();\n            });\n            window.draw(cx).clear(cx);\n        })\n        .unwrap();\n        for (key, first) in [\n            (\"tab\", true),\n            (\"tab\", false),\n            (\"tab\", true),\n            (\"shift-tab\", false),\n        ] {\n            visual.simulate_keystrokes(key);\n            cx.update_window(window.into(), |view, window, cx| {\n                window.draw(cx).clear(cx);\n                let view = view.downcast::<View>().unwrap();\n                let view = view.read(cx);\n                let expected = if first { &view.first } else { &view.last };\n                assert!(\n                    expected.is_focused(window),\n                    \"{key}: expected {expected:?}, got {:?}\",\n                    window.focused(cx)\n                );\n            })\n            .unwrap();\n        }\n        visual.simulate_keystrokes(\"escape\");\n        cx.update_window(window.into(), |view, window, cx| {\n            window.draw(cx).clear(cx);\n            let view = view.downcast::<View>().unwrap();\n            let view = view.read(cx);\n            assert!(!view.state.mobile_open);\n            assert!(view.state.open);\n            assert!(view.opener.is_focused(window));\n        })\n        .unwrap();\n    }\n\n    /// A roving sidebar is one tab stop that lands on the selected (later the\n    /// last focused) row, and the arrows, Home and End move between rows,\n    /// skipping disabled ones (karyalabs/gpuicn#100).\n    #[test]\n    fn roving_rows_are_one_tab_stop_moved_with_the_arrows() {\n        use gpui_kit::{\n            AppContext as _, Context, FocusHandle, Render, TestAppContext, VisualTestContext,\n        };\n        struct View {\n            before: FocusHandle,\n            after: FocusHandle,\n            activated: Rc<RefCell<Vec<&'static str>>>,\n        }\n        impl Render for View {\n            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {\n                let rows = [\"a\", \"b\", \"c\", \"d\"].map(|label| {\n                    let activated = self.activated.clone();\n                    div().debug_selector(move || format!(\"row-{label}\")).child(\n                        SidebarItem::new(label, label)\n                            .selected(label == \"b\")\n                            .disabled(label == \"c\")\n                            .on_activate(move |_, _, _| activated.borrow_mut().push(label)),\n                    )\n                });\n                div()\n                    .size_full()\n                    .flex()\n                    .child(\n                        div()\n                            .id(\"before\")\n                            .track_focus(&self.before.clone().tab_stop(true))\n                            .child(\"Before\"),\n                    )\n                    .child(\n                        Sidebar::new(\"nav\", \"Channels\")\n                            .roving_focus(true)\n                            .w(px(200.))\n                            .h(px(80.))\n                            .child(sidebar_menu().children(rows)),\n                    )\n                    .child(\n                        div()\n                            .id(\"after\")\n                            .track_focus(&self.after.clone().tab_stop(true))\n                            .child(\"After\"),\n                    )\n            }\n        }\n        let dispatcher = gpui_kit::TestDispatcher::new(0);\n        let mut cx = TestAppContext::build(dispatcher.clone(), None);\n        cx.update(|cx| {\n            super::super::theme::init(cx);\n            UiTheme::set(cx, UiTheme::neutral_light());\n        });\n        let activated = Rc::new(RefCell::new(Vec::new()));\n        let log = activated.clone();\n        let window = cx.add_window(move |window, cx| {\n            window.activate_window();\n            View {\n                before: cx.focus_handle(),\n                after: cx.focus_handle(),\n                activated: log,\n            }\n        });\n        let mut visual = VisualTestContext::from_window(window.into(), &cx);\n        let draw = |cx: &mut TestAppContext| {\n            cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))\n                .unwrap();\n        };\n        draw(&mut cx);\n        cx.update_window(window.into(), |view, window, cx| {\n            let view = view.downcast::<View>().unwrap();\n            view.read(cx).before.clone().focus(window, cx);\n        })\n        .unwrap();\n        draw(&mut cx);\n        let focused_is = |cx: &mut TestAppContext, which: &str| {\n            cx.update_window(window.into(), |view, window, cx| {\n                let view = view.downcast::<View>().unwrap();\n                let view = view.read(cx);\n                match which {\n                    \"before\" => view.before.is_focused(window),\n                    _ => view.after.is_focused(window),\n                }\n            })\n            .unwrap()\n        };\n        // Enter activates the focused row, which names it.\n        let row = |visual: &mut VisualTestContext, cx: &mut TestAppContext| {\n            let keystroke = gpui_kit::Keystroke::parse(\"enter\").unwrap();\n            visual.simulate_event(gpui_kit::KeyDownEvent {\n                keystroke: keystroke.clone(),\n                is_held: false,\n                prefer_character_input: false,\n            });\n            visual.simulate_event(gpui_kit::KeyUpEvent { keystroke });\n            draw(cx);\n            activated.borrow_mut().pop()\n        };\n        for (key, expected) in [\n            // In from the page, onto the selected row, then out in one step.\n            (\"tab\", Some(\"b\")),\n            (\"tab\", None),\n            (\"shift-tab\", Some(\"b\")),\n            // The disabled row is skipped and the arrows wrap.\n            (\"down\", Some(\"d\")),\n            (\"down\", Some(\"a\")),\n            (\"up\", Some(\"d\")),\n            (\"home\", Some(\"a\")),\n            (\"end\", Some(\"d\")),\n            // Leaving and coming back returns to the last focused row.\n            (\"shift-tab\", None),\n            (\"tab\", Some(\"d\")),\n        ] {\n            visual.simulate_keystrokes(key);\n            draw(&mut cx);\n            match expected {\n                Some(label) => {\n                    // The focused row is scrolled into the 80px sidebar.\n                    let bounds = visual\n                        .debug_bounds(Box::leak(format!(\"row-{label}\").into_boxed_str()))\n                        .expect(\"row drew\");\n                    assert!(\n                        bounds.top() >= px(-0.5) && bounds.bottom() <= px(80.5),\n                        \"{key}: {label} at {bounds:?}\"\n                    );\n                    assert_eq!(row(&mut visual, &mut cx), Some(label), \"after {key}\")\n                }\n                None => assert!(\n                    focused_is(&mut cx, \"after\") || focused_is(&mut cx, \"before\"),\n                    \"{key} should leave the rows\"\n                ),\n            }\n        }\n    }\n}\n"
    }
  ],
  "meta": {
    "since": "0.5.0",
    "category": "navigation"
  }
}
