From 8f96a2cc16f4f64def04f8d5758b4ded4b2a64d9 Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Tue, 17 Nov 2026 09:49:10 +0700 Subject: [PATCH] Re-vendor the native UI kit at 278430d - Upstream merged core, data, editor, and utils into a single `components` crate: `ui::button`, `ui::tabs`, `ui::code`, `ui::tree`, `ui::sidebar` are flat, and `h_flex`/`v_flex`/`StyledExt` live in `ui::common` and `ui::layout`. - Adopts the new wrapper-less component module tree, the merged theme/icon updates, and the relocated editor grammars. - Titlebar repo tabs use the new `TabsVariant::Titlebar` capsule sizing. - Doc examples now import from `ui::`, so all 44 doctests compile; the clipboard sample no longer names the kit crate. - docs/ui-gaps.md records that `ui` has no dock/view-registry API instead of the deleted `DockState`. --- crates/signed_app/src/pull_requests/detail.rs | 2 +- crates/signed_app/src/pull_requests/new.rs | 2 +- crates/signed_app/src/repo/commit_diff.rs | 2 +- crates/signed_app/src/repo/files.rs | 6 +- crates/signed_app/src/repo/helpers.rs | 4 +- crates/signed_app/src/repo/mod.rs | 2 +- crates/signed_app/src/titlebar/mod.rs | 4 +- crates/signed_app/src/workspace.rs | 2 +- crates/ui/src/components/alert.rs | 43 +- crates/ui/src/components/avatar.rs | 77 +-- crates/ui/src/components/badge.rs | 20 +- crates/ui/src/components/button.rs | 64 +- crates/ui/src/components/checkbox.rs | 23 +- crates/ui/src/components/clipboard.rs | 22 +- crates/ui/src/{editor => components}/code.rs | 64 +- crates/ui/src/components/combobox.rs | 65 +- crates/ui/src/components/command_palette.rs | 50 +- crates/ui/src/components/common.rs | 183 +++++- crates/ui/src/components/context_menu.rs | 18 + crates/ui/src/components/dialog.rs | 27 +- crates/ui/src/{editor => components}/diff.rs | 54 +- crates/ui/src/components/dropdown_menu.rs | 25 +- crates/ui/src/components/empty_state.rs | 17 +- crates/ui/src/components/field.rs | 24 +- crates/ui/src/components/grain.rs | 21 +- .../src/{editor => components}/highlight.rs | 32 +- crates/ui/src/components/input.rs | 74 ++- crates/ui/src/components/link.rs | 26 +- crates/ui/src/{data => components}/list.rs | 34 +- .../ui/src/{editor => components}/markdown.rs | 88 ++- crates/ui/src/components/menu.rs | 42 +- crates/ui/src/components/mod.rs | 10 + crates/ui/src/components/popover.rs | 27 +- crates/ui/src/components/progress.rs | 15 +- crates/ui/src/components/radio.rs | 26 +- crates/ui/src/components/scroll_area.rs | 14 +- crates/ui/src/components/scrollbar.rs | 26 +- crates/ui/src/components/segmented.rs | 31 +- crates/ui/src/components/select.rs | 26 +- crates/ui/src/components/separator.rs | 19 +- crates/ui/src/{data => components}/sidebar.rs | 37 +- crates/ui/src/components/slider.rs | 22 +- crates/ui/src/components/speech.rs | 44 +- crates/ui/src/components/spinner.rs | 58 +- crates/ui/src/components/status_dot.rs | 21 +- crates/ui/src/components/switch.rs | 25 +- crates/ui/src/{data => components}/tabs.rs | 221 ++++++- crates/ui/src/components/toast.rs | 24 +- crates/ui/src/components/toggle.rs | 23 +- crates/ui/src/components/tooltip.rs | 34 +- crates/ui/src/{data => components}/tree.rs | 70 +-- crates/ui/src/{editor => components}/utils.rs | 16 +- crates/ui/src/data/mod.rs | 6 - crates/ui/src/editor/mod.rs | 8 - crates/ui/src/icons/freedesktop.rs | 153 ----- crates/ui/src/icons/mod.rs | 28 - crates/ui/src/icons/segoe.rs | 15 - crates/ui/src/layout/mod.rs | 47 ++ crates/ui/src/layout/panel.rs | 4 +- crates/ui/src/layout/resizable.rs | 4 +- crates/ui/src/layout/resize_handle.rs | 9 +- crates/ui/src/layout/shell.rs | 10 +- crates/ui/src/layout/titlebar.rs | 8 +- crates/ui/src/layout/window_controls.rs | 22 +- crates/ui/src/layout/window_frame.rs | 3 +- crates/ui/src/lib.rs | 12 +- crates/ui/src/theme/definition.rs | 48 -- crates/ui/src/theme/mod.rs | 38 +- crates/ui/src/theme/presets.rs | 13 - crates/ui/src/theme/ramps.rs | 95 --- crates/ui/src/theme/resolve.rs | 564 +----------------- crates/ui/src/theme/source/kde.rs | 128 ---- crates/ui/src/theme/source/linux.rs | 50 +- crates/ui/src/theme/source/macos.rs | 4 +- crates/ui/src/theme/source/omarchy.rs | 84 --- crates/ui/src/theme/source/portal.rs | 56 +- crates/ui/src/theme/typography.rs | 63 -- crates/ui/src/utils.rs | 173 ------ crates/ui/tests/tabs.rs | 2 +- docs/ui-gaps.md | 8 +- 80 files changed, 1524 insertions(+), 2037 deletions(-) rename crates/ui/src/{editor => components}/code.rs (90%) rename crates/ui/src/{editor => components}/diff.rs (94%) rename crates/ui/src/{editor => components}/highlight.rs (89%) rename crates/ui/src/{data => components}/list.rs (89%) rename crates/ui/src/{editor => components}/markdown.rs (97%) rename crates/ui/src/{data => components}/sidebar.rs (94%) rename crates/ui/src/{data => components}/tabs.rs (85%) rename crates/ui/src/{data => components}/tree.rs (91%) rename crates/ui/src/{editor => components}/utils.rs (90%) delete mode 100644 crates/ui/src/data/mod.rs delete mode 100644 crates/ui/src/editor/mod.rs delete mode 100644 crates/ui/src/utils.rs diff --git a/crates/signed_app/src/pull_requests/detail.rs b/crates/signed_app/src/pull_requests/detail.rs index a5c8ed9..71ae672 100644 --- a/crates/signed_app/src/pull_requests/detail.rs +++ b/crates/signed_app/src/pull_requests/detail.rs @@ -15,13 +15,13 @@ use ui::avatar::Avatar; use ui::button::Button; use ui::clipboard::ClipboardButton; use ui::common::{Sizable as _, h_flex, v_flex}; -use ui::data::tabs::{Tab, Tabs}; use ui::icons::{Icon, IconRole}; use ui::input::InputState; use ui::layout::panel::Panel; use ui::scroll_area::ScrollArea; use ui::scrollbar::Scrollbar; use ui::spinner::Spinner; +use ui::tabs::{Tab, Tabs}; use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use utils::relative_time; diff --git a/crates/signed_app/src/pull_requests/new.rs b/crates/signed_app/src/pull_requests/new.rs index 5c12f5c..05c2149 100644 --- a/crates/signed_app/src/pull_requests/new.rs +++ b/crates/signed_app/src/pull_requests/new.rs @@ -10,13 +10,13 @@ use signed_state::{CheckoutsStore, RepoStore}; use ui::button::Button; use ui::combobox::{Combobox, ComboboxState}; use ui::common::{h_flex, v_flex}; -use ui::data::tabs::{Tab, Tabs}; use ui::icons::{Icon, IconRole}; use ui::input::{Input, InputState}; use ui::layout::panel::Panel; use ui::menu::Menu; use ui::scrollbar::Scrollbar; use ui::spinner::Spinner; +use ui::tabs::{Tab, Tabs}; use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use super::helpers::{ForkCompare, fork_display_name, truncate_label}; diff --git a/crates/signed_app/src/repo/commit_diff.rs b/crates/signed_app/src/repo/commit_diff.rs index 36b8544..a1ddb78 100644 --- a/crates/signed_app/src/repo/commit_diff.rs +++ b/crates/signed_app/src/repo/commit_diff.rs @@ -11,13 +11,13 @@ use signed_git::{CommitDiff, DiffStatus, FileCommit, FileDiff, Repo}; use ui::badge::{Badge, BadgeVariant}; use ui::clipboard::ClipboardButton; use ui::common::{h_flex, v_flex}; -use ui::data::tree::{Tree, TreeItem}; use ui::icons::{Icon, IconRole}; use ui::layout::panel::Panel; use ui::layout::resizable::{Resizable, ResizableState}; use ui::scrollbar::Scrollbar; use ui::spinner::Spinner; use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; +use ui::tree::{Tree, TreeItem}; use utils::relative_time_secs; use super::helpers::{DiffRow, diff_rows, render_diff_row}; diff --git a/crates/signed_app/src/repo/files.rs b/crates/signed_app/src/repo/files.rs index eaa1573..1c53a71 100644 --- a/crates/signed_app/src/repo/files.rs +++ b/crates/signed_app/src/repo/files.rs @@ -8,12 +8,12 @@ use gpui::{ ParentElement as _, SharedString, Styled as _, Task, WeakEntity, Window, div, px, }; use signed_git::{FileCommit, Repo, WorktreeSnapshot}; +use ui::code::CodeViewState; use ui::common::{h_flex, v_flex}; -use ui::data::tree::{Tree, TreeItem}; -use ui::editor::code::CodeViewState; -use ui::editor::markdown::MarkdownViewState; use ui::icons::{Icon, IconRole}; +use ui::markdown::MarkdownViewState; use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; +use ui::tree::{Tree, TreeItem}; use super::helpers::{code_language, is_markdown_path, preview_spinner, source_hash}; use crate::shared::tree::{TreeItemSeed, TreeRow, collect_expanded, flatten}; diff --git a/crates/signed_app/src/repo/helpers.rs b/crates/signed_app/src/repo/helpers.rs index c8fac6c..f930c23 100644 --- a/crates/signed_app/src/repo/helpers.rs +++ b/crates/signed_app/src/repo/helpers.rs @@ -234,8 +234,8 @@ pub(super) fn preview_spinner() -> AnyElement { } /// The kit grammar for a path; only four languages are supported. -pub(super) fn code_language(path: &str) -> ui::editor::highlight::Language { - use ui::editor::highlight::Language; +pub(super) fn code_language(path: &str) -> ui::highlight::Language { + use ui::highlight::Language; match Path::new(path) .extension() .and_then(|ext| ext.to_str()) diff --git a/crates/signed_app/src/repo/mod.rs b/crates/signed_app/src/repo/mod.rs index ffd90b2..d7e0588 100644 --- a/crates/signed_app/src/repo/mod.rs +++ b/crates/signed_app/src/repo/mod.rs @@ -17,9 +17,9 @@ use signed_state::{ }; use ui::alert::{Alert, AlertSeverity}; use ui::common::{h_flex, v_flex}; -use ui::data::sidebar::{Sidebar, SidebarEntry}; use ui::icons::{Icon, IconRole}; use ui::layout::panel::Panel; +use ui::sidebar::{Sidebar, SidebarEntry}; use ui::spinner::Spinner; use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; diff --git a/crates/signed_app/src/titlebar/mod.rs b/crates/signed_app/src/titlebar/mod.rs index 98c3906..25038ea 100644 --- a/crates/signed_app/src/titlebar/mod.rs +++ b/crates/signed_app/src/titlebar/mod.rs @@ -13,9 +13,9 @@ use ui::avatar::Avatar; use ui::button::{Button, ButtonVariant}; use ui::command_palette::{Command, CommandPalette, CommandPaletteState}; use ui::common::{Sizable as _, h_flex}; -use ui::data::tabs::{Tab, Tabs, TabsVariant}; use ui::icons::{Icon, IconRole}; use ui::menu::{Menu, MenuItem}; +use ui::tabs::{Tab, Tabs, TabsVariant}; use ui::theme::ActiveTheme as _; use ui::tooltip::Tooltip; @@ -227,7 +227,7 @@ impl TitlebarView { Some( Tabs::new("signed-repo-tabs") - .variant(TabsVariant::Pill) + .variant(TabsVariant::Titlebar) .overflow_scroll(true) .selected(selected) .tabs(move |_, cx| { diff --git a/crates/signed_app/src/workspace.rs b/crates/signed_app/src/workspace.rs index 155d84a..abc097e 100644 --- a/crates/signed_app/src/workspace.rs +++ b/crates/signed_app/src/workspace.rs @@ -5,8 +5,8 @@ use gpui::{ Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div, }; use ui::common::v_flex; -use ui::data::tabs::{Tab, Tabs, TabsVariant}; use ui::layout::panel::{Panel, PanelView}; +use ui::tabs::{Tab, Tabs, TabsVariant}; use crate::shared::log_dropped; diff --git a/crates/ui/src/components/alert.rs b/crates/ui/src/components/alert.rs index b6ab0f8..f098184 100644 --- a/crates/ui/src/components/alert.rs +++ b/crates/ui/src/components/alert.rs @@ -1,5 +1,32 @@ +//! Renders alert banners and the floating stack they push onto. +//! +//! An [`Alert`] is a value that renders as an [`AlertStyle::Overlay`] banner or +//! an [`AlertStyle::Inline`] callout. An [`Alerts`] entity holds the pushed +//! alerts, and an [`AlertsView`] renders the stack; mount the view at the +//! window root. +//! +//! # Examples +//! +//! ```no_run +//! use ui::alert::Alert; +//! +//! let alert = Alert::new("disk-warning") +//! .title("Storage almost full") +//! .message("Delete unused projects to free up space.") +//! .on_dismiss(|_cx| println!("dismissed")); +//! ``` + use std::rc::Rc; +use crate::components::button::{Button, ButtonVariant}; +use crate::components::common::{ + DismissHandler, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, v_flex, +}; +use crate::icons::{Icon, IconRole}; +use crate::theme::{ + ALERT_EDGE_WIDTH, ALERT_STACK_WIDTH, ActiveTheme as _, ENTER_SLIDE_DISTANCE, Size, TextRole, + Typeset as _, +}; use gpui::prelude::FluentBuilder as _; use gpui::{ Animation, AnimationExt as _, App, Context, ElementId, Entity, InteractiveElement as _, @@ -8,17 +35,6 @@ use gpui::{ ease_out_quint, }; -use crate::components::button::{Button, ButtonVariant}; -use crate::components::common::{ - DismissHandler, Sizable as _, StyledExt as _, TOAST_LAYER, v_flex, -}; -use crate::icons::{Icon, IconRole}; -use crate::theme::{ - ALERT_EDGE_WIDTH, ALERT_STACK_WIDTH, ActiveTheme as _, ENTER_SLIDE_DISTANCE, Size, TextRole, - Typeset as _, -}; -use crate::utils::ResultLogErr as _; - /// How alarming an [`Alert`] is; picks the accent color. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum AlertSeverity { @@ -58,6 +74,7 @@ pub struct Alert { } impl Alert { + /// Creates an alert. pub fn new(id: I) -> Self where I: Into, @@ -267,7 +284,9 @@ impl RenderOnce for Alert { /// One pushed alert, with its identity in the stack. #[derive(Clone)] pub struct AlertEntry { + /// The id [`Alerts::push`] returned. pub id: usize, + /// The alert as pushed. pub alert: Alert, on_dismiss: Option, } @@ -280,7 +299,7 @@ pub struct Alerts { } impl Alerts { - /// Pushes an alert onto the stack. + /// Pushes an alert onto the stack and returns its id. pub fn push(&mut self, mut alert: Alert, cx: &mut Context) -> usize { let id = self.next_id; self.next_id += 1; diff --git a/crates/ui/src/components/avatar.rs b/crates/ui/src/components/avatar.rs index 0a78bb4..3a15777 100644 --- a/crates/ui/src/components/avatar.rs +++ b/crates/ui/src/components/avatar.rs @@ -1,15 +1,28 @@ +//! Renders a user avatar that shows a picture when set and a deterministic +//! pixel fallback derived from the id otherwise. +//! +//! # Examples +//! +//! ```no_run +//! use ui::avatar::Avatar; +//! +//! let avatar = Avatar::new("user-42") +//! .name("Ada Lovelace") +//! .picture(Some("https://example.com/ada.png")); +//! ``` + use std::fmt::Display; +use crate::theme::{ + ActiveTheme as _, Oklch, PIXEL_AVATAR_DARK_FACTOR, PIXEL_AVATAR_DARK_FLOOR, + PIXEL_AVATAR_LIGHT_CAP, PIXEL_AVATAR_LIGHT_LIFT, PIXEL_AVATAR_TINT_ALPHA, Size, ThemeVariant, +}; use gpui::{ App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, div, }; use crate::components::common::{Sizable, StyledExt, h_flex}; -use crate::theme::{ - ActiveTheme as _, Oklch, PIXEL_AVATAR_DARK_FACTOR, PIXEL_AVATAR_DARK_FLOOR, - PIXEL_AVATAR_LIGHT_CAP, PIXEL_AVATAR_LIGHT_LIFT, PIXEL_AVATAR_TINT_ALPHA, Size, ThemeVariant, -}; /// Number of rows and columns in the pixel grid. const GRID_SIZE: usize = 8; @@ -35,7 +48,7 @@ pub struct Avatar { } impl Avatar { - /// Create an avatar for `id`, a public key or any other stable string. + /// Creates an avatar for `id`, a public key or any other stable string. /// /// The id seeds the pixel fallback shown when no picture is set. pub fn new(id: T) -> Self @@ -52,7 +65,7 @@ impl Avatar { } } - /// The display name of the avatar's subject, if known. + /// Sets the display name used as the image's accessibility label. pub fn name(mut self, name: N) -> Self where N: Into, @@ -61,7 +74,7 @@ impl Avatar { self } - /// The user's picture URL. + /// Sets the picture URL; `None` shows the pixel fallback. pub fn picture

(mut self, picture: Option

) -> Self where P: Into, @@ -70,7 +83,7 @@ impl Avatar { self } - /// Renders the avatar circular instead of the control radius. + /// Renders the avatar circular instead of the theme's small radius. pub fn fully_rounded(mut self, fully_rounded: bool) -> Self { self.fully_rounded = fully_rounded; self @@ -281,51 +294,3 @@ impl PixelRng { self.next() as f32 / (u64::MAX as f32) < probability } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_pattern_is_mirror_symmetric() { - for seed in [0u64, 1, 42, u64::MAX] { - let pattern = pattern(seed); - for row in 0..GRID_SIZE { - for col in 0..GRID_SIZE / 2 { - assert_eq!( - pattern[row * GRID_SIZE + col], - pattern[row * GRID_SIZE + (GRID_SIZE - 1 - col)], - "seed {seed} row {row} col {col}" - ); - } - } - } - } - - #[test] - fn the_pattern_keeps_the_outer_ring_empty() { - for seed in [0u64, 1, 42, u64::MAX] { - let pattern = pattern(seed); - for col in 0..GRID_SIZE { - assert_eq!(pattern[col], 0, "top row, seed {seed}"); - assert_eq!(pattern[(GRID_SIZE - 1) * GRID_SIZE + col], 0, "bottom row"); - } - for row in 0..GRID_SIZE { - assert_eq!(pattern[row * GRID_SIZE], 0, "left column, seed {seed}"); - assert_eq!(pattern[row * GRID_SIZE + GRID_SIZE - 1], 0, "right column"); - } - } - } - - #[test] - fn the_pattern_is_deterministic_and_fills_the_minimum() { - for seed in [0u64, 7, 42, u64::MAX] { - let first = pattern(seed); - assert_eq!(first, pattern(seed), "seed {seed} must be stable"); - - // Mirrored cells count twice, so both halves carry the minimum. - let filled = first.iter().filter(|cell| **cell != 0).count(); - assert!(filled >= MIN_FILLED * 2, "seed {seed} filled {filled}"); - } - } -} diff --git a/crates/ui/src/components/badge.rs b/crates/ui/src/components/badge.rs index 13e56aa..e12e99b 100644 --- a/crates/ui/src/components/badge.rs +++ b/crates/ui/src/components/badge.rs @@ -1,5 +1,17 @@ +//! Renders a small pill that labels a count or a state. +//! +//! # Examples +//! +//! ```no_run +//! use ui::badge::{Badge, BadgeVariant}; +//! +//! let unread = Badge::new("unread", "12").variant(BadgeVariant::Accent); +//! ``` + use std::rc::Rc; +use crate::icons::Icon; +use crate::theme::{ActiveTheme as _, Size, Theme}; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyView, App, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, @@ -8,13 +20,11 @@ use gpui::{ }; use crate::components::common::{StyledExt, h_flex}; -use crate::icons::Icon; -use crate::theme::{ActiveTheme as _, Size, Theme}; /// The tooltip view builder gpui's `.tooltip(...)` expects. type TooltipBuilder = Rc AnyView>; -/// How loud a badge is. +/// The visual treatment of a [`Badge`]. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum BadgeVariant { /// The default; quiet muted fill for counts. @@ -82,7 +92,7 @@ pub struct Badge { } impl Badge { - /// Creates a badge showing `label` — a count or state word the caller formats. + /// Creates a badge with `label`, a count or state word the caller formats. pub fn new(id: I, label: L) -> Self where I: Into, @@ -98,7 +108,7 @@ impl Badge { } } - /// Sets how loud the badge is. + /// Sets the badge's [`BadgeVariant`]. pub fn variant(mut self, variant: BadgeVariant) -> Self { self.variant = variant; self diff --git a/crates/ui/src/components/button.rs b/crates/ui/src/components/button.rs index 8a26d12..f43c31a 100644 --- a/crates/ui/src/components/button.rs +++ b/crates/ui/src/components/button.rs @@ -1,19 +1,30 @@ -//! The push button: the API template for every control that follows. - -use std::rc::Rc; +//! Renders a push button that fires its handler on click, Enter, and Space. +//! +//! # Examples +//! +//! ```no_run +//! use ui::button::{Button, ButtonVariant}; +//! +//! let save = Button::new("save") +//! .label("Save") +//! .variant(ButtonVariant::Primary) +//! .on_click(|_event, _window, _cx| println!("saved")); +//! ``` +use crate::icons::Icon; +use crate::theme::{ActiveTheme as _, ControlMetrics, DISABLED_OPACITY, Size}; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, AnyView, App, ClickEvent, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas, relative, transparent_black, }; +use std::rc::Rc; -use crate::components::common::{Sizable, StyledExt as _, h_flex}; +use crate::components::common::{ + Sizable, StyledExt as _, focus_ring, h_flex, record_anchor_bounds, +}; use crate::components::spinner::Spinner; -use crate::icons::Icon; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; -use crate::utils::{focus_ring, record_anchor_bounds}; /// The single activation handler, shared by pointer, Enter, and Space. type ClickHandler = Box; @@ -46,7 +57,8 @@ pub enum ButtonSide { Right, } -/// A push button: pointer, Enter, and Space all fire the single `on_click`. +/// A push button that renders a label, an icon, or both, and fires +/// [`Button::on_click`] on click, Enter, or Space. #[derive(IntoElement)] #[must_use] pub struct Button { @@ -56,9 +68,11 @@ pub struct Button { children: Vec, variant: ButtonVariant, size: Size, + custom_metrics: Option, disabled: bool, loading: bool, padded: bool, + fully_rounded: bool, side: ButtonSide, tab_stop: bool, debug_selector: Option String>>, @@ -81,9 +95,11 @@ impl Button { children: Vec::new(), variant: ButtonVariant::default(), size: Size::default(), + custom_metrics: None, disabled: false, loading: false, padded: true, + fully_rounded: false, side: ButtonSide::default(), tab_stop: true, debug_selector: None, @@ -127,7 +143,14 @@ impl Button { self } - /// Whether the button is a keyboard tab stop, dense toolbars turn it off. + /// Overrides the theme metrics, allowing sizes beyond the built-in classes. + pub fn custom_size(mut self, metrics: ControlMetrics) -> Self { + self.custom_metrics = Some(metrics); + self + } + + /// Sets whether the button is a keyboard tab stop. Dense toolbars typically + /// turn this off. pub fn tab_stop(mut self, tab_stop: bool) -> Self { self.tab_stop = tab_stop; self @@ -154,12 +177,18 @@ impl Button { self } - /// Whether the button pads its content. false removes all padding. + /// Sets whether the button pads its content. `false` removes all padding. pub fn padded(mut self, padded: bool) -> Self { self.padded = padded; self } + /// Renders the button as a pill instead of the control radius. + pub fn fully_rounded(mut self, fully_rounded: bool) -> Self { + self.fully_rounded = fully_rounded; + self + } + /// Sets the edge the content aligns to, `Right` renders the icon after the label. pub fn side(mut self, side: ButtonSide) -> Self { self.side = side; @@ -175,7 +204,7 @@ impl Button { self } - /// The single activation handler, fired by pointer, Enter, and Space. + /// Sets the single activation handler, fired by pointer, Enter, and Space. pub fn on_click(mut self, handler: F) -> Self where F: Fn(&ClickEvent, &mut Window, &mut App) + 'static, @@ -208,7 +237,16 @@ impl RenderOnce for Button { let theme = cx.theme(); let colors = theme.colors; let ramps = theme.ramps; - let metrics = theme.sizes.resolve(self.size); + + let metrics = self + .custom_metrics + .unwrap_or_else(|| theme.sizes.resolve(self.size)); + + let radius = if self.fully_rounded { + theme.radius.full + } else { + theme.radius.control + }; let on_click = self.on_click; let a11y_label = self.a11y_label.or_else(|| self.label.clone()); @@ -278,7 +316,7 @@ impl RenderOnce for Button { button.px(metrics.padding_x) }) .line_height(relative(1.0)) - .rounded(theme.radius.control) + .rounded(radius) .text_size(metrics.text_size) .border_1() .border_color(border) diff --git a/crates/ui/src/components/checkbox.rs b/crates/ui/src/components/checkbox.rs index c0461c1..c3aad54 100644 --- a/crates/ui/src/components/checkbox.rs +++ b/crates/ui/src/components/checkbox.rs @@ -1,18 +1,27 @@ -//! The checkbox: a controlled on/off value with an optional label. +//! Renders a controlled checkbox that reports the next value on click, Enter, and Space. +//! +//! # Examples +//! +//! ```no_run +//! use ui::checkbox::Checkbox; +//! +//! let consent = Checkbox::new("consent") +//! .label("Send release notes") +//! .checked(false) +//! .on_change(|next, _window, _cx| println!("checked: {next}")); +//! ``` use std::rc::Rc; +use crate::components::common::{Sizable, StyledExt as _, focus_ring, h_flex}; +use crate::icons::{IconRole, icon}; +use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; use gpui::prelude::FluentBuilder as _; use gpui::{ App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window, }; -use crate::components::common::{Sizable, StyledExt as _, h_flex}; -use crate::icons::{IconRole, icon}; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; -use crate::utils::focus_ring; - /// The change reporter, fired with the next value by pointer, Enter, and Space. type ChangeHandler = Box; @@ -89,7 +98,7 @@ impl Checkbox { self } - /// The change handler, fired with the next value by pointer, Enter, and Space. + /// Sets the change handler, fired with the next value by pointer, Enter, and Space. pub fn on_change(mut self, handler: F) -> Self where F: Fn(bool, &mut Window, &mut App) + 'static, diff --git a/crates/ui/src/components/clipboard.rs b/crates/ui/src/components/clipboard.rs index 37337aa..4830298 100644 --- a/crates/ui/src/components/clipboard.rs +++ b/crates/ui/src/components/clipboard.rs @@ -1,20 +1,28 @@ -//! The clipboard button: copies a value and confirms with a brief check mark. +//! Renders a button that copies a value to the system clipboard and confirms with a +//! brief check mark. +//! +//! # Examples +//! +//! ```no_run +//! use ui::clipboard::ClipboardButton; +//! +//! let copy = ClipboardButton::new("copy-build", "cargo build --release") +//! .on_copied(|_cx| println!("copied")); +//! ``` use std::rc::Rc; use std::time::Duration; +use crate::components::button::{Button, ButtonVariant}; +use crate::components::common::{ResultLogErr as _, Sizable, StyledExt as _}; +use crate::icons::IconRole; +use crate::theme::Size; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyView, App, ClipboardItem, ElementId, Entity, IntoElement, RenderOnce, SharedString, StyleRefinement, Task, Window, }; -use crate::components::button::{Button, ButtonVariant}; -use crate::components::common::{Sizable, StyledExt as _}; -use crate::icons::IconRole; -use crate::theme::Size; -use crate::utils::ResultLogErr as _; - /// How long the check mark shows before reverting to the copy icon. pub const COPIED_DURATION: Duration = Duration::from_secs(1); diff --git a/crates/ui/src/editor/code.rs b/crates/ui/src/components/code.rs similarity index 90% rename from crates/ui/src/editor/code.rs rename to crates/ui/src/components/code.rs index f9ed671..134b461 100644 --- a/crates/ui/src/editor/code.rs +++ b/crates/ui/src/components/code.rs @@ -1,7 +1,33 @@ -//! The code view: a virtualized, read-only rendering of highlighted source. -//! Rows render only when visible, the line-number gutter is part of each -//! row, and the overlay scrollbar is the core one. +//! Renders a read-only, virtualized view of highlighted source with a +//! line-number gutter, an active-line wash on hover, and drag selection +//! with copy. Rows render only when visible, and the overlay scrollbar is +//! the core one. +//! +//! The view is the state: build a [`CodeViewState`] in a [`gpui::Entity`] +//! and render the entity, then mutate the state to update the view. +//! [`bind_code_view_keys`] installs the selection copy chord once at +//! startup. +//! +//! # Examples +//! +//! ```no_run +//! use gpui::{App, AppContext as _}; +//! use ui::code::{CodeViewState, bind_code_view_keys}; +//! use ui::highlight::Language; +//! +//! fn source_pane(cx: &mut App) -> gpui::Entity { +//! bind_code_view_keys(cx); +//! let view = cx.new(|cx| CodeViewState::new("source", "fn main() {}\n", Language::Rust, cx)); +//! view.update(cx, |state, cx| state.set_source("fn hello() {}\n", Language::Rust, cx)); +//! view +//! } +//! ``` +use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility}; +use crate::theme::{ + ActiveTheme as _, CODE_GUTTER_WIDTH, CODE_LINE_HEIGHT, ColorTokens, MONO_ADVANCE_RATIO, Ramps, + WASH_ALPHA_SOFT, +}; use gpui::prelude::FluentBuilder as _; use gpui::{ App, Bounds, ClipboardItem, Context, ElementId, HighlightStyle, Hsla, InteractiveElement as _, @@ -11,13 +37,8 @@ use gpui::{ actions, canvas, div, uniform_list, }; -use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility}; -use crate::editor::highlight::{HighlightedCode, Language, Role, highlight}; -use crate::editor::utils::gutter_cell; -use crate::theme::{ - ActiveTheme as _, CODE_GUTTER_WIDTH, CODE_LINE_HEIGHT, ColorTokens, MONO_ADVANCE_RATIO, Ramps, - WASH_ALPHA_SOFT, -}; +use crate::components::highlight::{HighlightedCode, Language, Role, highlight}; +use crate::components::utils::gutter_cell; actions!(code_view, [Copy]); @@ -39,7 +60,9 @@ pub fn bind_code_view_keys(cx: &mut App) { /// A point in the source, in lines and characters (not bytes). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct SelectionPoint { + /// The zero-based line index. pub row: usize, + /// The zero-based character offset within the line. pub col: usize, } @@ -51,6 +74,9 @@ impl SelectionPoint { } /// Retained state for a code view. +/// +/// Build one in a [`gpui::Entity`], render the entity, and call its setters +/// to update the rendered view. pub struct CodeViewState { id: ElementId, source: SharedString, @@ -91,7 +117,8 @@ impl CodeViewState { } } - /// Replaces the source and re-highlights it. + /// Replaces the source and re-highlights it, clearing the selection and + /// scrolling back to the top. pub fn set_source(&mut self, source: S, language: Language, cx: &mut Context) where S: Into, @@ -107,7 +134,13 @@ impl CodeViewState { cx.notify(); } - /// Replaces one line's text and re-highlights the file. + /// Replaces one line's text and re-highlights the file. `line_ix` past + /// the end clamps to the last line, and the replacement may span + /// multiple lines. + /// + /// # Panics + /// + /// Panics if the source is empty, which leaves no line to replace. pub fn update_line(&mut self, line_ix: usize, text: T, cx: &mut Context) where T: AsRef, @@ -130,7 +163,7 @@ impl CodeViewState { cx.notify(); } - /// The highlighted source text. + /// The source text the view renders. pub fn source(&self) -> &str { &self.source } @@ -140,7 +173,8 @@ impl CodeViewState { &self.code } - /// Scrolls `line` to the top of the view. + /// Scrolls `line` to the top of the view; past-the-end lines clamp to + /// the last line. pub fn scroll_to_line(&self, line: usize) { self.handle.scroll_to_item( line.min(self.code.lines.len().saturating_sub(1)), @@ -207,7 +241,7 @@ impl CodeViewState { (!selected.is_empty()).then(|| selected.join("\n")) } - // Overrides the accessibility label of the view. + /// Overrides the accessibility label of the view. pub fn accessibility_label(mut self, label: L) -> Self where L: Into, diff --git a/crates/ui/src/components/combobox.rs b/crates/ui/src/components/combobox.rs index a558aaa..17a540f 100644 --- a/crates/ui/src/components/combobox.rs +++ b/crates/ui/src/components/combobox.rs @@ -1,13 +1,41 @@ -//! The combobox: an editable field that filters its options while typing. +//! Renders an editable field that filters its options while typing. //! -//! The state is the view: it owns the query field and the options, and the -//! owner renders the entity itself. Typing filters, the arrow keys move a -//! highlight, Enter commits, and what happens to unmatched text when the -//! field loses focus is [`UnmatchedText`] — revert by default. +//! The state is the view: [`ComboboxState`] owns the query field and the +//! options, and the owner renders the entity itself. Typing filters, the +//! arrow keys move a highlight, Enter commits, and what happens to unmatched +//! text when the field loses focus is decided by [`UnmatchedText`], which +//! reverts by default. +//! +//! # Examples +//! +//! ```no_run +//! use gpui::prelude::*; +//! use gpui::{App, Entity, Window}; +//! use ui::combobox::{Combobox, ComboboxState}; +//! +//! # fn build(window: &mut Window, cx: &mut App) -> Entity> { +//! let picker = Combobox::new( +//! "theme", +//! "Theme", +//! vec![("dark", "Dark".into()), ("light", "Light".into())], +//! ) +//! .on_change(|value, _window, _cx| println!("{value:?}")); +//! let state = cx.new(|cx| ComboboxState::new(picker, window, cx)); +//! # state +//! # } +//! ``` use std::cell::RefCell; use std::rc::Rc; +use crate::components::common::{ + OVERLAY_LAYER, ResultLogErr as _, Sizable, StyledExt as _, h_flex, v_flex, +}; +use crate::components::input::{Input, InputState, InputStateEvent}; +use crate::components::scroll_area::ScrollArea; +use crate::icons::{IconRole, icon}; +use crate::theme::ActiveTheme as _; +use crate::theme::{COMBOBOX_MIN_WIDTH, COMBOBOX_WIDTH, POPUP_MAX_HEIGHT, Size}; use gpui::prelude::FluentBuilder; use gpui::{ App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding, @@ -16,13 +44,6 @@ use gpui::{ Window, actions, anchored, canvas, deferred, div, point, px, }; -use crate::components::common::{OVERLAY_LAYER, Sizable, StyledExt as _, h_flex, v_flex}; -use crate::components::input::{Input, InputState, InputStateEvent}; -use crate::components::scroll_area::ScrollArea; -use crate::icons::{IconRole, icon}; -use crate::theme::{ActiveTheme as _, COMBOBOX_MIN_WIDTH, COMBOBOX_WIDTH, POPUP_MAX_HEIGHT, Size}; -use crate::utils::ResultLogErr as _; - actions!( combobox, [HighlightNext, HighlightPrevious, Choose, Dismiss] @@ -60,14 +81,14 @@ pub enum UnmatchedText { /// An option for a [`Combobox`]: a value and the label the filter matches on. pub type ComboboxOption = (T, SharedString); -/// Reports the value whenever it changes; +/// Reports the value whenever it changes. pub type ComboboxHandler = Rc, &mut Window, &mut App)>; /// Receives unmatched text when the field loses focus in create mode. pub type ComboboxCreateHandler = Rc; /// Decides which options survive a query: the query, the value, the label. pub type ComboboxFilter = Rc bool>; -/// Builder for a combobox. Pass it to [`ComboboxState::new`]. +/// Builder for a combobox, consumed by [`ComboboxState::new`]. #[must_use] pub struct Combobox where @@ -186,6 +207,22 @@ where impl FluentBuilder for Combobox where T: Clone + PartialEq + 'static {} /// The stateful combobox. +/// +/// # Examples +/// +/// ```no_run +/// # use gpui::prelude::*; +/// # use gpui::{App, Entity, Window}; +/// # use ui::combobox::{Combobox, ComboboxState}; +/// # +/// # fn build(window: &mut Window, cx: &mut App) -> Entity> { +/// # let picker = Combobox::new("theme", "Theme", vec![("dark", "Dark".into())]); +/// # let state = cx.new(|cx| ComboboxState::new(picker, window, cx)); +/// state.update(cx, |state, cx| state.set_selected(Some("dark"), window, cx)); +/// assert_eq!(state.read(cx).selected(), Some(&"dark")); +/// # state +/// # } +/// ``` pub struct ComboboxState where T: Clone + PartialEq + 'static, diff --git a/crates/ui/src/components/command_palette.rs b/crates/ui/src/components/command_palette.rs index be9a6a5..b41c8bf 100644 --- a/crates/ui/src/components/command_palette.rs +++ b/crates/ui/src/components/command_palette.rs @@ -1,7 +1,33 @@ -//! The command palette: a modal query field over the application's actions. +//! Renders a modal query field over the application's actions. +//! +//! The state is the view: [`CommandPaletteState`] owns the query field and +//! the matches, and the owner renders the entity itself. Opening resets the +//! query, typing asks the caller's matcher for fresh matches, the arrow keys +//! move a highlight, and Enter runs the highlighted command through +//! [`CommandPalette::on_execute`]. +//! +//! # Examples +//! +//! ```no_run +//! use gpui::prelude::*; +//! use gpui::{App, Entity, Window}; +//! use ui::command_palette::{Command, CommandPalette, CommandPaletteState}; +//! +//! # fn build(window: &mut Window, cx: &mut App) -> Entity { +//! # let commands = vec![Command::new("save", "Save file").hint("Cmd+S")]; +//! let palette = CommandPalette::new("palette", commands, |query, all| { +//! all.iter().filter(|command| command.label.contains(query)).cloned().collect() +//! }) +//! .on_execute(|command, _window, _cx| println!("run {}", command.id)); +//! let state = cx.new(|cx| CommandPaletteState::new(palette, window, cx)); +//! # state +//! # } +//! ``` use std::rc::Rc; +use crate::icons::Icon; +use crate::theme::{ActiveTheme as _, POPUP_MAX_HEIGHT, Size}; use gpui::prelude::FluentBuilder; use gpui::{ AnyElement, App, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding, @@ -13,8 +39,6 @@ use gpui::{ use crate::components::common::{DIALOG_LAYER, StyledExt as _, h_flex, v_flex}; use crate::components::input::{Input, InputState, InputStateEvent}; use crate::components::scroll_area::{ScrollArea, ScrollAxes}; -use crate::icons::Icon; -use crate::theme::{ActiveTheme as _, POPUP_MAX_HEIGHT, Size}; actions!( command_palette, @@ -95,7 +119,7 @@ pub type CommandMatcher = Rc Vec>; /// Runs the chosen command. pub type CommandHandler = Rc; -/// Builder for a command palette. Pass it to [`CommandPaletteState::new`]. +/// Builder for a command palette, consumed by [`CommandPaletteState::new`]. #[must_use] pub struct CommandPalette { id: ElementId, @@ -108,7 +132,7 @@ pub struct CommandPalette { } impl CommandPalette { - /// Creates the builder, the caller-owned matcher decides what matches. + /// Creates the builder with a caller-owned matcher that decides what matches. pub fn new(id: I, commands: Vec, matcher: M) -> Self where I: Into, @@ -157,6 +181,22 @@ impl CommandPalette { impl FluentBuilder for CommandPalette {} /// The stateful palette. +/// +/// # Examples +/// +/// ```no_run +/// # use gpui::prelude::*; +/// # use gpui::{App, Entity, Window}; +/// # use ui::command_palette::{Command, CommandPalette, CommandPaletteState}; +/// # +/// # fn build(window: &mut Window, cx: &mut App) -> Entity { +/// # let palette = CommandPalette::new("palette", Vec::new(), |_, all| all.to_vec()); +/// # let state = cx.new(|cx| CommandPaletteState::new(palette, window, cx)); +/// state.update(cx, |state, cx| state.toggle(window, cx)); +/// assert!(state.read(cx).is_open()); +/// # state +/// # } +/// ``` pub struct CommandPaletteState { id: ElementId, name: SharedString, diff --git a/crates/ui/src/components/common.rs b/crates/ui/src/components/common.rs index 43d8263..e38b6d5 100644 --- a/crates/ui/src/components/common.rs +++ b/crates/ui/src/components/common.rs @@ -1,7 +1,188 @@ //! Shared element constructors and small style helpers. +//! +//! # Examples +//! +//! ```no_run +//! use gpui::{ParentElement as _, Styled as _, div}; +//! use ui::common::{h_flex, v_flex}; +//! +//! let row = h_flex().gap_2().child(div()).child(div()); +//! let column = v_flex().gap_2().child(row); +//! ``` + +use crate::theme::{ActiveTheme as _, FOCUS_RING_ALPHA, FOCUS_RING_SPREAD}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, Bounds, BoxShadow, Div, ElementId, FocusHandle, Global, Hsla, IntoElement, Pixels, + Refineable as _, StatefulInteractiveElement, StyleRefinement, Styled, Window, WindowId, div, + px, +}; +use std::collections::HashMap; pub use crate::theme::Size; -pub use crate::utils::{StyledExt, h_flex, v_flex}; + +/// A row whose children center on the cross axis. +#[must_use] +pub fn h_flex() -> Div { + div().flex().flex_row().items_center() +} + +/// A column whose children stack on the main axis. +#[must_use] +pub fn v_flex() -> Div { + div().flex().flex_col() +} + +/// Logs the error and yields the success value, if any. +pub trait ResultLogErr { + /// Logs the error and yields the success value, if any. + fn log_err(self) -> Option; +} + +impl ResultLogErr for Result { + fn log_err(self) -> Option { + match self { + Ok(value) => Some(value), + Err(error) => { + log::warn!("{error}"); + None + } + } + } +} + +/// Extensions over [`Styled`], shared by the components. +pub trait StyledExt: Styled + Sized { + #[must_use] + fn refine_style(mut self, style: &StyleRefinement) -> Self { + self.style().refine(style); + self + } +} + +impl StyledExt for E {} + +/// Returns a focus handle for the given element ID. +pub fn focus_handle(id: &ElementId, window: &mut Window, cx: &mut App) -> FocusHandle { + window + .with_element_namespace(id.clone(), |window| { + window.use_keyed_state("focus-handle", cx, |_, cx| cx.focus_handle()) + }) + .read(cx) + .clone() +} + +/// The painted bounds of elements that tooltips anchor to, per window and element id. +/// Entries are never evicted: bounds are bounded by live windows, though long-lived processes minting dynamic per-item ids could accumulate. +#[derive(Default)] +struct AnchorBoundsRegistry(HashMap<(WindowId, ElementId), Bounds>); + +impl Global for AnchorBoundsRegistry {} + +impl AnchorBoundsRegistry { + fn record(&mut self, window: WindowId, id: ElementId, bounds: Bounds) { + self.0.insert((window, id), bounds); + } + + fn get(&self, window: WindowId, id: &ElementId) -> Option> { + self.0.get(&(window, id.clone())).copied() + } +} + +/// The last bounds an element painted at, in the given window. +pub fn anchor_bounds(window: WindowId, id: &ElementId, cx: &App) -> Option> { + cx.try_global::() + .and_then(|registry| registry.get(window, id)) +} + +/// A canvas prepaint closure recording the element's painted bounds. +pub fn record_anchor_bounds( + id: ElementId, +) -> impl Fn(Bounds, &mut Window, &mut App) + 'static { + move |bounds, window, cx| { + let window_id = window.window_handle().window_id(); + cx.default_global::() + .record(window_id, id.clone(), bounds); + } +} + +/// Returns a focus ring shadow with the given color at half ink. +pub fn focus_ring(color: Hsla) -> Vec { + vec![ + BoxShadow::new(px(0.), px(0.), color.alpha(FOCUS_RING_ALPHA)) + .spread_radius(FOCUS_RING_SPREAD), + ] +} + +/// The next selectable row in the direction, or `None` at the ends. +pub fn adjacent_selectable( + selectable: &[usize], + selected: Option, + forward: bool, +) -> Option { + if forward { + selectable + .iter() + .copied() + .find(|index| Some(*index) > selected) + } else { + selectable + .iter() + .copied() + .rev() + .find(|index| Some(*index) < selected) + } +} + +/// Whether the given key is a vertical navigation key. +pub fn nav_key(selectable: &[usize], selected: Option, key: &str, select: S) -> bool +where + S: FnOnce(Option), +{ + let target = match key { + "down" => adjacent_selectable(selectable, selected, true), + "up" => adjacent_selectable(selectable, selected, false), + "home" => selectable.first().copied(), + "end" => selectable.last().copied(), + _ => return false, + }; + if let Some(next) = target + && Some(next) != selected + { + select(Some(next)); + } + true +} + +/// A selectable row's label and icon color. +pub fn selectable_label_color(cx: &App, selected: bool, disabled: bool) -> Hsla { + let theme = cx.theme(); + if disabled { + theme.colors.muted_foreground + } else if selected { + theme.colors.primary_foreground + } else { + theme.colors.foreground + } +} + +/// A selectable row's background. +#[must_use] +pub fn paint_selectable_row(cx: &App, row: R, selected: bool, disabled: bool) -> R +where + R: IntoElement + Styled + StatefulInteractiveElement, +{ + let theme = cx.theme(); + row.map(|row| { + if disabled { + row + } else if selected { + row.bg(theme.ramps.primary.base) + } else { + row.hover(|row| row.bg(theme.colors.muted)) + } + }) +} /// A handler told to clean up after a dismissed surface. pub type DismissHandler = std::rc::Rc; diff --git a/crates/ui/src/components/context_menu.rs b/crates/ui/src/components/context_menu.rs index 0723676..a41d89e 100644 --- a/crates/ui/src/components/context_menu.rs +++ b/crates/ui/src/components/context_menu.rs @@ -1,3 +1,21 @@ +//! Renders a menu at the pointer when its target element is right-clicked. +//! +//! # Examples +//! +//! ```no_run +//! use gpui::{IntoElement as _, ParentElement as _, SharedString, div}; +//! use ui::context_menu::ContextMenu; +//! use ui::menu::MenuItem; +//! +//! let context = ContextMenu::new("project-context") +//! .target(|_window, _cx| { +//! div() +//! .child(SharedString::from("project.el")) +//! .into_any_element() +//! }) +//! .items(|_window, _cx| vec![MenuItem::new("Delete").handler(|_window, _cx| {})]); +//! ``` + use gpui::prelude::FluentBuilder as _; use gpui::{ App, ElementId, InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent, diff --git a/crates/ui/src/components/dialog.rs b/crates/ui/src/components/dialog.rs index 3f597dc..45d0d36 100644 --- a/crates/ui/src/components/dialog.rs +++ b/crates/ui/src/components/dialog.rs @@ -1,6 +1,27 @@ -use std::rc::Rc; +//! Renders a centred panel over a dim scrim: the platform's modal. +//! +//! # Examples +//! +//! ```no_run +//! use gpui::{IntoElement, ParentElement as _, SharedString, div}; +//! use ui::dialog::Dialog; +//! +//! let confirm = Dialog::new("delete-project") +//! .title("Delete project") +//! .content(|_window, _cx| { +//! div() +//! .child(SharedString::from("This cannot be undone.")) +//! .into_any_element() +//! }) +//! .open(true) +//! .on_change(|open, _window, _cx| println!("dialog open: {open}")); +//! ``` use gpui::prelude::FluentBuilder as _; +use std::rc::Rc; + +use crate::icons::IconRole; +use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH, TextRole, Typeset as _}; use gpui::{ Animation, AnimationExt as _, AnyElement, App, DefiniteLength, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, ParentElement as _, @@ -12,8 +33,6 @@ use crate::components::button::{Button, ButtonVariant}; use crate::components::common::{DIALOG_LAYER, Sizable, StyledExt as _, v_flex}; use crate::components::grain::grain; use crate::components::scroll_area::ScrollArea; -use crate::icons::IconRole; -use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH, TextRole, Typeset as _}; /// Requests the dialog's close: `false` closes. pub type ChangeHandler = Rc; @@ -186,7 +205,7 @@ impl RenderOnce for Dialog { let show_close = !alert && on_change.is_some(); // Keyboard focus rides the panel across frames. - let focus = crate::utils::focus_handle(&self.id, window, cx); + let focus = crate::components::common::focus_handle(&self.id, window, cx); let content = self.content.map(|build| build(window, cx)); let actions = self.actions.map(|build| build(window, cx)); diff --git a/crates/ui/src/editor/diff.rs b/crates/ui/src/components/diff.rs similarity index 94% rename from crates/ui/src/editor/diff.rs rename to crates/ui/src/components/diff.rs index 306cb37..8db853b 100644 --- a/crates/ui/src/editor/diff.rs +++ b/crates/ui/src/components/diff.rs @@ -1,12 +1,33 @@ -//! The diff view: a unified, syntax-highlighted rendering of two versions of -//! a file, in the style of the Pierre diff engine used by tangled.org: change -//! bars instead of markers, tinted number gutters, word-level intra-line -//! highlights and hunk separators. Rows reuse the code view's highlighting; -//! consumers that already hold a git diff can build [`DiffRow`]s themselves -//! instead of calling [`DiffViewState::diff_rows`]. - -use std::ops::Range; +//! Renders a unified, syntax-highlighted diff of two versions of a file: +//! change bars or `+`/`-` markers, tinted number gutters, word-level +//! intra-line highlights, and collapsed hunk separators. +//! +//! Rows reuse the code view's highlighting. Consumers that already hold a +//! git diff can build [`DiffRow`]s themselves instead of calling +//! [`DiffViewState::diff_rows`]. +//! +//! # Examples +//! +//! ```no_run +//! use gpui::{App, AppContext as _}; +//! use ui::diff::{DiffIndicators, DiffViewState}; +//! use ui::highlight::Language; +//! +//! fn patch(cx: &mut App) -> gpui::Entity { +//! let state = DiffViewState::new( +//! "patch", +//! "# gpui\nA UI kit for gpui.", +//! "# gpui\nA UI toolkit for gpui.", +//! Language::Rust, +//! ) +//! .indicators(DiffIndicators::Bars); +//! +//! cx.new(|_| state) +//! } +//! ``` +use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility}; +use crate::theme::{ActiveTheme as _, BORDER_WIDTH, CODE_GUTTER_WIDTH, MONO_ADVANCE_RATIO}; use gpui::prelude::FluentBuilder as _; use gpui::{ App, Context, ElementId, HighlightStyle, InteractiveElement as _, IntoElement, @@ -16,10 +37,10 @@ use gpui::{ }; use similar::{Change, ChangeTag, TextDiff}; -use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility}; -use crate::editor::highlight::{HighlightedCode, Language, Line, Role, highlight}; -use crate::editor::utils::{gutter_cell, wash, wash_gutter, wash_strong}; -use crate::theme::{ActiveTheme as _, BORDER_WIDTH, CODE_GUTTER_WIDTH, MONO_ADVANCE_RATIO}; +use std::ops::Range; + +use crate::components::highlight::{HighlightedCode, Language, Line, Role, highlight}; +use crate::components::utils::{gutter_cell, wash, wash_gutter, wash_strong}; /// What a diff row did to the file. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -79,7 +100,9 @@ pub enum HunkSeparator { /// Presentation options for the diff view. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct DiffViewOptions { + /// How changed rows are marked. pub indicators: DiffIndicators, + /// How collapsed regions between hunks render. pub separator: HunkSeparator, /// Whether the line-number gutter renders. pub line_numbers: bool, @@ -167,6 +190,9 @@ impl DiffRow { } /// Retained state for a diff view. +/// +/// Build one in a [`gpui::Entity`], render the entity, and call its setters +/// to update the rendered view. pub struct DiffViewState { id: ElementId, rows: Vec, @@ -243,7 +269,9 @@ impl DiffViewState { .map(|(widest, _)| widest); } - /// Computes unified rows between two texts, highlighting every line with `language`. + /// Computes unified rows between two texts, highlighting every line with + /// `language`. Rows include [`DiffRowKind::Hunk`] separators between + /// hunks. pub fn diff_rows(old: &str, new: &str, language: Language) -> Vec { let old_code = highlight(old, language); let new_code = highlight(new, language); diff --git a/crates/ui/src/components/dropdown_menu.rs b/crates/ui/src/components/dropdown_menu.rs index df058e7..04188d4 100644 --- a/crates/ui/src/components/dropdown_menu.rs +++ b/crates/ui/src/components/dropdown_menu.rs @@ -1,8 +1,22 @@ -//! The dropdown menu: a push button with an attached menu of actions. +//! Renders a push button with an attached menu of actions. +//! +//! # Examples +//! +//! ```no_run +//! use ui::dropdown_menu::DropdownMenu; +//! use ui::menu::MenuItem; +//! +//! let export = DropdownMenu::new("export") +//! .label("Export") +//! .on_open_change(|open, _window, _cx| println!("menu open: {open}")) +//! .items(|_window, _cx| vec![MenuItem::new("PDF"), MenuItem::new("HTML")]); +//! ``` use std::cell::RefCell; use std::rc::Rc; +use crate::icons::{Icon, IconRole, icon}; +use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; use gpui::prelude::FluentBuilder as _; use gpui::{ App, ClickEvent, DefiniteLength, DispatchPhase, ElementId, InteractiveElement as _, @@ -12,14 +26,11 @@ use gpui::{ }; use crate::components::button::ButtonVariant; -use crate::components::common::{Sizable, StyledExt as _, h_flex}; +use crate::components::common::{Sizable, StyledExt as _, focus_handle, focus_ring, h_flex}; use crate::components::menu::{ ChangeHandler, MenuChrome, MenuItem, MenuPanelSpec, TriggerBoundsCell, anchored_menu_panel, }; use crate::components::spinner::Spinner; -use crate::icons::{Icon, IconRole, icon}; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; -use crate::utils::{focus_handle, focus_ring}; /// The main zone's activation handler, shared by pointer, Enter, and Space. type ClickHandler = Box; @@ -95,7 +106,7 @@ impl DropdownMenu { self } - /// Whether the trigger is a keyboard tab stop, dense toolbars turn it off. + /// Sets whether the trigger is a keyboard tab stop. Dense toolbars turn it off. pub fn tab_stop(mut self, tab_stop: bool) -> Self { self.tab_stop = tab_stop; self @@ -128,7 +139,7 @@ impl DropdownMenu { self } - /// The main zone's action. Without one, activating the button opens the menu. + /// Sets the main zone's action. Without one, activating the button opens the menu. pub fn on_click(mut self, handler: F) -> Self where F: Fn(&ClickEvent, &mut Window, &mut App) + 'static, diff --git a/crates/ui/src/components/empty_state.rs b/crates/ui/src/components/empty_state.rs index c96bbb0..a877c4b 100644 --- a/crates/ui/src/components/empty_state.rs +++ b/crates/ui/src/components/empty_state.rs @@ -1,3 +1,16 @@ +//! Renders a centered panel for lists, tables, and searches with nothing to show. +//! +//! # Examples +//! +//! ```no_run +//! use ui::empty_state::EmptyState; +//! +//! let state = EmptyState::new("No projects yet") +//! .hint("Create a project to get started"); +//! ``` + +use crate::icons::Icon; +use crate::theme::{ActiveTheme as _, Size, TextRole, Typeset as _}; use gpui::prelude::FluentBuilder as _; use gpui::{ App, IntoElement, ParentElement as _, RenderOnce, SharedString, StyleRefinement, Styled as _, @@ -5,8 +18,6 @@ use gpui::{ }; use crate::components::common::{StyledExt, v_flex}; -use crate::icons::Icon; -use crate::theme::{ActiveTheme as _, Size, TextRole, Typeset as _}; /// The centered "nothing here yet" panel for lists, tables, and searches. #[derive(IntoElement)] @@ -52,7 +63,7 @@ impl EmptyState { self } - /// Sets an action element — usually a button — under the hint. + /// Sets an action element, usually a [`crate::components::button::Button`], under the hint. pub fn action(mut self, action: E) -> Self where E: IntoElement, diff --git a/crates/ui/src/components/field.rs b/crates/ui/src/components/field.rs index 8c50ef2..b6aaef5 100644 --- a/crates/ui/src/components/field.rs +++ b/crates/ui/src/components/field.rs @@ -1,5 +1,18 @@ -//! The field: a label, description, and error wrapped around a control. +//! Wraps a control with a label, description, and error text. +//! +//! # Examples +//! +//! ```no_run +//! use gpui::{div, ParentElement}; +//! use ui::field::{Field, FieldVariant}; +//! +//! let sync = Field::new("sync", "Sync settings") +//! .description("Keep your work synced across devices") +//! .variant(FieldVariant::Row) +//! .child(div()); +//! ``` +use crate::theme::{ActiveTheme as _, TextRole, Typeset as _}; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce, @@ -7,7 +20,6 @@ use gpui::{ }; use crate::components::common::{StyledExt, h_flex, v_flex}; -use crate::theme::{ActiveTheme as _, TextRole, Typeset as _}; /// The arrangement of a [`Field`]'s label and control. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -15,11 +27,11 @@ pub enum FieldVariant { /// The label block sits above the control, full width. #[default] Block, - /// The label block leads and the control trails — the settings row. + /// The label block leads and the control trails, as in a settings row. Row, } -/// A labeled control: the label, description, and error around any element. +/// A control presented with a label, an optional description, and an error. #[derive(IntoElement)] #[must_use] pub struct Field { @@ -50,7 +62,7 @@ impl Field { } } - /// The helper text under the label. + /// Sets the helper text under the label. pub fn description(mut self, description: D) -> Self where D: Into, @@ -59,7 +71,7 @@ impl Field { self } - /// The error under the control; `None` clears it. + /// Sets the error under the control; `None` clears it. pub fn error(mut self, error: Option) -> Self where E: Into, diff --git a/crates/ui/src/components/grain.rs b/crates/ui/src/components/grain.rs index dfdd245..de0522d 100644 --- a/crates/ui/src/components/grain.rs +++ b/crates/ui/src/components/grain.rs @@ -1,20 +1,29 @@ -//! The grain: a film-noise overlay for material surfaces. +//! Renders tiled film-grain noise over its container. +//! +//! # Examples +//! +//! ```no_run +//! use gpui::{ParentElement as _, Styled as _, div}; +//! use ui::grain::grain; +//! +//! let overlay = grain(); +//! let surface = div().relative().child(overlay); +//! ``` use std::sync::{Arc, OnceLock}; +use crate::components::common::ResultLogErr as _; +use crate::theme::GRAIN_ALPHA; use gpui::{ App, Bounds, Corners, IntoElement, RenderImage, RenderOnce, Styled as _, Window, canvas, point, px, size, }; use image::{Frame, ImageBuffer, Rgba}; -use crate::theme::GRAIN_ALPHA; -use crate::utils::ResultLogErr as _; - /// The side of one noise tile, in device pixels. const TILE_PX: u32 = 256; -/// A film-grain overlay: tiled monochrome noise at [`GRAIN_ALPHA`] strength. +/// A film-grain overlay that tiles monochrome noise at [`GRAIN_ALPHA`] strength. #[derive(IntoElement)] #[must_use] pub struct Grain; @@ -64,7 +73,7 @@ impl RenderOnce for Grain { } } -/// The shared noise tile, every tile reuses its one atlas entry. +/// Returns the shared noise tile so every tile reuses one atlas entry. fn texture() -> Arc { static TEXTURE: OnceLock> = OnceLock::new(); diff --git a/crates/ui/src/editor/highlight.rs b/crates/ui/src/components/highlight.rs similarity index 89% rename from crates/ui/src/editor/highlight.rs rename to crates/ui/src/components/highlight.rs index 4ba949f..fd12d8c 100644 --- a/crates/ui/src/editor/highlight.rs +++ b/crates/ui/src/components/highlight.rs @@ -1,16 +1,25 @@ -//! Tree-sitter highlighting: source text in, role-styled lines out. Roles -//! are resolved to theme colors at render time, so a theme change re-colors -//! code without re-parsing it. +//! Highlights source text into role-styled lines with tree-sitter grammars. +//! Roles are resolved to theme colors at render time, so a theme change +//! re-colors code without re-parsing it. +//! +//! # Examples +//! +//! ```no_run +//! use ui::highlight::{Language, highlight}; +//! +//! let code = highlight("let answer = 42;\n", Language::Rust); +//! for span in &code.lines[0].spans { +//! println!("{} ({:?})", span.text, span.role); +//! } +//! ``` +use crate::components::common::ResultLogErr; +use gpui::SharedString; use std::cell::RefCell; use std::collections::HashMap; - -use gpui::SharedString; #[cfg(not(target_arch = "wasm32"))] use tree_sitter::StreamingIterator as _; -use crate::utils::ResultLogErr; - #[cfg(not(target_arch = "wasm32"))] thread_local! { static HIGHLIGHTERS: RefCell>> = @@ -56,13 +65,16 @@ pub enum Role { /// A run of text sharing one role. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Span { + /// The run's text. pub text: SharedString, + /// The semantic role applied to the text. pub role: Role, } /// One rendered line of code. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct Line { + /// The spans making up the line, in character order. pub spans: Vec, } @@ -80,10 +92,12 @@ impl Line { /// Source text split into role-styled lines. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct HighlightedCode { + /// The source's lines, in order. pub lines: Vec, } -/// Highlights `source` with `language`'s tree-sitter grammar. +/// Highlights `source` with `language`'s tree-sitter grammar, falling back +/// to plain text when the grammar is unavailable or parsing fails. #[cfg(not(target_arch = "wasm32"))] pub fn highlight(source: &str, language: Language) -> HighlightedCode { let Some((grammar, query_source)) = grammar_for(language) else { @@ -147,7 +161,7 @@ pub fn highlight(source: &str, language: Language) -> HighlightedCode { }) } -/// The web target has no tree-sitter parsers. +/// Highlights `source` as plain text; the web target has no grammars. #[cfg(target_arch = "wasm32")] pub fn highlight(source: &str, _language: Language) -> HighlightedCode { plain(source) diff --git a/crates/ui/src/components/input.rs b/crates/ui/src/components/input.rs index d5b3828..f0423c1 100644 --- a/crates/ui/src/components/input.rs +++ b/crates/ui/src/components/input.rs @@ -1,7 +1,37 @@ +//! Renders a text field bound to an application-owned [`InputState`]. +//! +//! The state is a [`gpui::Entity`] the application owns across frames: read it +//! with [`InputState::value`], write it with [`InputState::set_value`], and +//! subscribe to [`InputStateEvent`] for changes. [`Input`] is the view built +//! from that state each frame. Call [`bind_input_keys`] once at startup to +//! register the editing keybindings. +//! +//! # Examples +//! +//! ```no_run +//! use ui::input::{Input, InputState, bind_input_keys}; +//! +//! # let mut cx: gpui::App = unimplemented!(); +//! bind_input_keys(&mut cx, None); +//! +//! let state = InputState::builder() +//! .text("Ada Lovelace") +//! .build(&mut cx); +//! +//! let field = Input::new("name", state).placeholder("Full name"); +//! ``` + use std::ops::Range; use std::rc::Rc; use std::time::{Duration, Instant}; +use unicode_segmentation::UnicodeSegmentation; + +use crate::icons::IconRole; +use crate::theme::{ + ActiveTheme as _, CARET_WIDTH, ColorTokens, DISABLED_OPACITY, Size, UNDERLINE_WIDTH, + WHEEL_LINE_HEIGHT, +}; use gpui::prelude::FluentBuilder as _; use gpui::{ Animation, AnimationExt as _, AnyElement, App, AppContext as _, Bounds, ClipboardItem, @@ -12,17 +42,11 @@ use gpui::{ StatefulInteractiveElement as _, StyleRefinement, Styled as _, TextAlign, TextRun, UTF16Selection, Window, WrappedLine, actions, canvas, div, fill, point, px, }; -use unicode_segmentation::UnicodeSegmentation; use crate::components::button::{Button, ButtonVariant}; use crate::components::common::{Sizable, StyledExt as _, h_flex}; -use crate::icons::IconRole; -use crate::theme::{ - ActiveTheme as _, CARET_WIDTH, ColorTokens, DISABLED_OPACITY, Size, UNDERLINE_WIDTH, - WHEEL_LINE_HEIGHT, -}; -/// The key context input bindings match against. +/// The key context [`InputBindings`] match against. pub const INPUT_CONTEXT: &str = "Input"; /// Consecutive edits within this interval merge into one undo entry. const DEFAULT_GROUP_INTERVAL: Duration = Duration::from_millis(300); @@ -47,13 +71,13 @@ type MouseDownHandler = std::rc::Rc, @@ -478,7 +506,7 @@ impl HistoryEntry { } } -/// The application-owned state of a text field. +/// The application-owned state of a text field that [`Input`] renders. pub struct InputState { text: String, /// The caret's byte offset. @@ -501,7 +529,7 @@ pub struct InputState { redo_stack: Vec, /// Consecutive edits within this interval merge into one undo entry. group_interval: Duration, - /// When set, user edits are refused, focus, movement, selection and copy stay. + /// When set, user edits are refused; focus, movement, selection, and copy still work. read_only: bool, /// When set, the field is a password field. password: bool, @@ -558,7 +586,7 @@ impl InputStateBuilder { self } - /// Refuses user edits, focus, movement, selection and copy stay. + /// Refuses user edits; focus, movement, selection, and copy still work. pub fn read_only(mut self) -> Self { self.read_only = true; self @@ -644,7 +672,7 @@ impl InputState { self.set_value_inner(value, true, window, cx); } - /// Like [`set_value`], but does not emit `TextChanged`. + /// Like [`Self::set_value`], but does not emit [`InputStateEvent::TextChanged`]. pub fn set_value_silent(&mut self, value: V, window: &mut Window, cx: &mut Context) where V: Into, @@ -683,6 +711,8 @@ impl InputState { } /// Sets whether user edits are refused. + /// + /// Focus, movement, selection, and copy still work. pub fn set_read_only(&mut self, read_only: bool, cx: &mut Context) { if self.read_only != read_only { self.read_only = read_only; @@ -874,7 +904,8 @@ impl InputState { self.caret_blink_visible_at(focused, elapsed) } - /// The visibility math at a given time since the epoch started. + /// Whether the caret should paint `elapsed` after the current caret epoch + /// started; [`InputState::caret_visible`] passes the real elapsed time. pub fn caret_blink_visible_at(&self, focused: bool, elapsed: Duration) -> bool { if !focused || self.read_only { return false; @@ -1915,7 +1946,7 @@ impl Input { self } - /// Sets the height of a multiline field, in rows. + /// Sets the height of a multiline field, in rows; ignored for single-line state. pub fn rows(mut self, rows: usize) -> Self { self.rows = rows.max(1); self @@ -1927,13 +1958,15 @@ impl Input { self } - /// Renders the field inert, unfocusable, and dimmed; disabled always wins. + /// Renders the field inert, unfocusable, and dimmed, regardless of the + /// state's read-only setting. pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; self } - /// Overrides the accessibility label. + /// Overrides the accessibility label, which defaults to the placeholder, + /// then the element ID. pub fn accessibility_label(mut self, label: L) -> Self where L: Into, @@ -2435,9 +2468,10 @@ impl RenderOnce for Input { } } -/// Registers input keybindings on the application. +/// Registers the input keybindings on the application, once at startup. /// -/// Pass `None` for the platform defaults. +/// Pass `None` for the platform defaults or an [`InputBindings`] table for +/// custom ones. pub fn bind_input_keys(cx: &mut App, bindings: B) where B: Into>, diff --git a/crates/ui/src/components/link.rs b/crates/ui/src/components/link.rs index 70e5846..fc81fe1 100644 --- a/crates/ui/src/components/link.rs +++ b/crates/ui/src/components/link.rs @@ -1,3 +1,21 @@ +//! Renders a link that opens a URL or fires a click handler. +//! +//! # Examples +//! +//! ```no_run +//! use ui::link::Link; +//! +//! let docs = Link::new("docs-link") +//! .label("Documentation") +//! .href("https://example.com/docs"); +//! +//! let settings = Link::new("settings-link") +//! .label("Open settings") +//! .on_click(|_event, _window, _cx| println!("open settings")); +//! ``` + +use crate::components::common::{Sizable, StyledExt as _, focus_ring, h_flex}; +use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; use gpui::prelude::FluentBuilder as _; use gpui::{ App, ClickEvent, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, @@ -5,14 +23,10 @@ use gpui::{ Window, }; -use crate::components::common::{Sizable, StyledExt as _, h_flex}; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; -use crate::utils::focus_ring; - -/// The click handler. When set it replaces the default `href` opening. +/// The handler called with the [`gpui::ClickEvent`], replacing the default `href` opening. type ClickHandler = Box; -/// Link component. +/// A hyperlink that opens a URL or fires a click handler. #[derive(IntoElement)] #[must_use] pub struct Link { diff --git a/crates/ui/src/data/list.rs b/crates/ui/src/components/list.rs similarity index 89% rename from crates/ui/src/data/list.rs rename to crates/ui/src/components/list.rs index 59b1c8d..ae8cce8 100644 --- a/crates/ui/src/data/list.rs +++ b/crates/ui/src/components/list.rs @@ -1,5 +1,28 @@ +//! Renders a single-selection list of [`ListItem`] rows with keyboard navigation. +//! +//! # Examples +//! +//! ```no_run +//! use ui::list::{List, ListItem}; +//! +//! let folders = List::new("folders") +//! .selected(Some(0)) +//! .items(|_, _| { +//! vec![ +//! ListItem::new("documents", "Documents").detail("24 files"), +//! ListItem::new("downloads", "Downloads"), +//! ] +//! }) +//! .on_change(|_selected, _window, _cx| println!("selection changed")); +//! ``` + use std::rc::Rc; +use crate::components::common::{ + StyledExt as _, nav_key, paint_selectable_row, selectable_label_color, +}; +use crate::icons::Icon; +use crate::theme::{ActiveTheme as _, TextRole, Typeset as _}; use gpui::prelude::FluentBuilder; use gpui::{ AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent, @@ -7,12 +30,9 @@ use gpui::{ StyleRefinement, Styled as _, Window, div, }; -use crate::icons::Icon; -use crate::theme::{ActiveTheme as _, TextRole, Typeset as _}; -use crate::utils::{StyledExt as _, nav_key, paint_selectable_row, selectable_label_color}; - /// The change reporter, fired with the next selection by pointer and keys. type ChangeHandler = Rc, &mut Window, &mut App)>; +/// The row builder, run during render. type ItemsFn = Box Vec>; /// One row of a [`List`]. @@ -69,7 +89,7 @@ impl ListItem { // ListItem is a data builder, not an element, adopt the combinators explicitly. impl FluentBuilder for ListItem {} -/// A single-selection list. +/// A single-selection list of [`ListItem`] rows. #[derive(IntoElement)] #[must_use] pub struct List { @@ -112,7 +132,7 @@ impl List { self } - /// Sets the rows, the closure runs during render and must not mutate entities or notify. + /// Sets the rows; the closure runs during render and must not mutate entities or notify. pub fn items(mut self, items: F) -> Self where F: Fn(&mut Window, &mut App) -> Vec + 'static, @@ -151,7 +171,7 @@ impl RenderOnce for List { .map(|(index, _)| index) .collect(); - let focus = crate::utils::focus_handle(&self.id, window, cx); + let focus = crate::components::common::focus_handle(&self.id, window, cx); let theme = cx.theme(); let label = self diff --git a/crates/ui/src/editor/markdown.rs b/crates/ui/src/components/markdown.rs similarity index 97% rename from crates/ui/src/editor/markdown.rs rename to crates/ui/src/components/markdown.rs index 1173753..8d44ca0 100644 --- a/crates/ui/src/editor/markdown.rs +++ b/crates/ui/src/components/markdown.rs @@ -1,17 +1,37 @@ -//! The markdown view: a read-only rendering of a markdown document as -//! formatted text. Parsing runs once per source change and produces blocks; -//! rendering virtualizes the visible blocks and resolves every style from -//! the theme at draw time. Images render inline or as standalone blocks; -//! text, code, and tables drag-select and copy; task checkboxes report -//! toggles and code blocks offer a copy action. Footnotes, math, and HTML -//! render nothing; long code lines clip rather than scroll. - -use std::borrow::Borrow as _; -use std::collections::HashMap; -use std::hash::{DefaultHasher, Hash, Hasher}; -use std::ops::Range; -use std::sync::Arc; +//! Renders a markdown document as formatted, selectable text. Parsing runs +//! once per source change and produces [`MarkdownBlock`]s; rendering +//! virtualizes the visible blocks and resolves styles from the theme at +//! draw time. Text, code, and tables drag-select and copy; task checkboxes +//! report toggles and code blocks offer a copy action. Images render inline +//! or as standalone blocks. Footnotes, math, and HTML render nothing; long +//! code lines clip rather than scroll. +//! +//! The view is the state: build a [`MarkdownViewState`] in a +//! [`gpui::Entity`] and embed it with [`TextView::new`], or let +//! [`TextView::markdown`] own its state under an element id. +//! +//! # Examples +//! +//! ```no_run +//! use gpui::{App, AppContext as _}; +//! use ui::markdown::{MarkdownViewState, TextView}; +//! +//! fn notes(cx: &mut App) -> TextView { +//! let state = cx.new(|_| MarkdownViewState::new("notes", "# Notes\n- [x] shipped")); +//! TextView::new(&state) +//! .on_link_click(|destination, _window, _cx| println!("{destination}")) +//! .on_task_toggle(|index, checked, _window, _cx| println!("{index}: {checked}")) +//! } +//! ``` +use crate::components::button::{Button, ButtonVariant}; +use crate::components::checkbox::Checkbox; +use crate::components::common::Sizable as _; +use crate::components::scrollbar::{Scrollbar, ScrollbarVisibility}; +use crate::theme::{ + ActiveTheme as _, BORDER_WIDTH, CODE_LINE_HEIGHT, CODE_OVERSCROLL_MAX, Size, TextRole, + Typeset as _, +}; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, Bounds, ClipboardItem, Context, Div, Element, ElementId, Entity, FontStyle, @@ -24,16 +44,14 @@ use gpui::{ }; use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd}; -use crate::components::button::{Button, ButtonVariant}; -use crate::components::checkbox::Checkbox; -use crate::components::common::Sizable as _; -use crate::components::scrollbar::{Scrollbar, ScrollbarVisibility}; -use crate::editor::highlight::{HighlightedCode, Language, highlight, plain}; -use crate::editor::utils::code_line; -use crate::theme::{ - ActiveTheme as _, BORDER_WIDTH, CODE_LINE_HEIGHT, CODE_OVERSCROLL_MAX, Size, TextRole, - Typeset as _, -}; +use std::borrow::Borrow as _; +use std::collections::HashMap; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::ops::Range; +use std::sync::Arc; + +use crate::components::highlight::{HighlightedCode, Language, highlight, plain}; +use crate::components::utils::code_line; /// The bottom padding between sibling blocks, in root font sizes. const BLOCK_GAP: f32 = 0.75; @@ -102,7 +120,9 @@ pub enum ListMarker { pub enum InlineItem { Text(InlineSpan), Image { + /// Where the image loads from. source: SharedString, + /// The image's alt text. alt: SharedString, }, } @@ -110,17 +130,20 @@ pub enum InlineItem { /// The inline style a text run carries. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum InlineStyle { + /// Plain body text. Text, + /// Italic emphasis. Emphasis, + /// Bold emphasis. Strong, + /// Bold and italic together. StrongEmphasis, + /// Struck-through text. Strikethrough, /// Inline code. Code, /// A link with its destination. - Link { - destination: SharedString, - }, + Link { destination: SharedString }, } /// One rendered block of a markdown document. @@ -146,6 +169,7 @@ pub enum MarkdownBlock { items: Vec, /// How many lists wrap this item's list, zero for the outermost. indent: usize, + /// Whether a blockquote wraps the item. quote: bool, }, /// An image that stands alone in its paragraph. @@ -188,7 +212,9 @@ impl MarkdownBlock { /// One run of inline text sharing a style. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct InlineSpan { + /// The run's text. pub text: SharedString, + /// The style applied to the text. pub style: InlineStyle, } @@ -212,6 +238,9 @@ pub struct MarkdownTable { } /// Retained state for a markdown view. +/// +/// Build one in a [`gpui::Entity`] and embed it with [`TextView::new`], or +/// let [`TextView::markdown`] own its state under an element id. pub struct MarkdownViewState { id: ElementId, source: SharedString, @@ -267,7 +296,7 @@ impl MarkdownViewState { self } - /// Replaces the source and re-parses it. + /// Replaces the source and re-parses it; an equal source is a no-op. pub fn set_source(&mut self, source: S, cx: &mut Context) where S: Into, @@ -382,7 +411,8 @@ impl MarkdownViewState { cx.notify(); } - /// The selected range over the rendered text, endpoints in document order, when there is one. + /// The selected range over the rendered text, endpoints in document + /// order, when there is one. pub fn selection(&self) -> Option<(usize, usize)> { let (anchor, head) = self.selection?; Some(if anchor <= head { @@ -648,8 +678,8 @@ impl Styled for TextView { } impl Element for TextView { - type PrepaintState = (); type RequestLayoutState = AnyElement; + type PrepaintState = (); fn id(&self) -> Option { Some(self.id.clone()) diff --git a/crates/ui/src/components/menu.rs b/crates/ui/src/components/menu.rs index 77d1e92..ff2673a 100644 --- a/crates/ui/src/components/menu.rs +++ b/crates/ui/src/components/menu.rs @@ -1,8 +1,32 @@ -//! The floating menu panel shared by menus, dropdowns, and context menus. +//! Renders floating menus of [`MenuItem`] rows for [`Menu`], dropdowns, and +//! context menus. +//! +//! # Examples +//! +//! ```no_run +//! use gpui::{IntoElement as _, ParentElement as _, SharedString, div}; +//! use ui::menu::{Menu, MenuItem}; +//! +//! let menu = Menu::new("file-menu") +//! .trigger(|_window, _cx| { +//! div().child(SharedString::from("File")).into_any_element() +//! }) +//! .items(|_window, _cx| { +//! vec![ +//! MenuItem::new("New File").handler(|_window, _cx| println!("new")), +//! MenuItem::separator(), +//! MenuItem::new("Open Recent").submenu(vec![MenuItem::new("Project One")]), +//! ] +//! }); +//! ``` use std::cell::RefCell; use std::rc::Rc; +use crate::components::common::{OVERLAY_LAYER, StyledExt as _, focus_handle, v_flex}; +use crate::components::scroll_area::{ScrollArea, ScrollAxes}; +use crate::icons::{Icon, IconRole, icon as icon_glyph}; +use crate::theme::{ActiveTheme as _, BORDER_WIDTH, MENU_MIN_WIDTH, POPUP_MAX_HEIGHT}; use gpui::prelude::FluentBuilder; use gpui::{ Animation, AnimationExt as _, AnyElement, App, Bounds, BoxShadow, DefiniteLength, @@ -12,12 +36,6 @@ use gpui::{ Window, anchored, canvas, deferred, div, ease_out_quint, point, px, relative, }; -use crate::components::common::{OVERLAY_LAYER, StyledExt as _, v_flex}; -use crate::components::scroll_area::{ScrollArea, ScrollAxes}; -use crate::icons::{Icon, IconRole, icon as icon_glyph}; -use crate::theme::{ActiveTheme as _, BORDER_WIDTH, MENU_MIN_WIDTH, POPUP_MAX_HEIGHT}; -use crate::utils::focus_handle; - /// Runs the item's action. The menu closes itself before the handler runs. pub type ItemHandler = Rc; @@ -27,7 +45,9 @@ pub(crate) type ChangeHandler = Rc; type FlyoutSetter = Rc, bool, &mut App)>; /// Bounds captured during the last paint, shared with the dismissal listener. pub(crate) type TriggerBoundsCell = Rc>>>; +/// The element the panel anchors below, built during render. type TriggerFn = Box AnyElement>; +/// The menu's rows, rebuilt on each render while open. type ItemsFn = Box Vec>; /// One row of a [`Menu`]: an action, a checkable action, a submenu, or a separator. @@ -53,7 +73,7 @@ enum MenuItemKind { } impl MenuItem { - /// An action row with this label. + /// Creates an action row with this label. pub fn new(label: L) -> Self where L: Into, @@ -71,7 +91,7 @@ impl MenuItem { } } - /// A divider between groups of actions. + /// Creates a divider between groups of actions. pub fn separator() -> Self { Self { id: None, @@ -188,7 +208,7 @@ pub(crate) struct MenuChrome { shadow: Vec, } -/// A floating menu of actions anchored below its trigger. +/// A floating menu of [`MenuItem`] rows anchored below its trigger. #[derive(IntoElement)] #[must_use] pub struct Menu { @@ -255,7 +275,7 @@ impl Menu { } } - /// Sets the row keyboard-highlighted when the menu opens. + /// Sets the row that starts keyboard-selected when the menu opens. pub fn initial_selection(mut self, index: usize) -> Self { self.initial_selection = Some(index); self diff --git a/crates/ui/src/components/mod.rs b/crates/ui/src/components/mod.rs index ec74d3d..cef4505 100644 --- a/crates/ui/src/components/mod.rs +++ b/crates/ui/src/components/mod.rs @@ -6,17 +6,22 @@ pub mod badge; pub mod button; pub mod checkbox; pub mod clipboard; +pub mod code; pub mod combobox; pub mod command_palette; pub mod common; pub mod context_menu; pub mod dialog; +pub mod diff; pub mod dropdown_menu; pub mod empty_state; pub mod field; pub mod grain; +pub mod highlight; pub mod input; pub mod link; +pub mod list; +pub mod markdown; pub mod menu; pub mod popover; pub mod progress; @@ -26,11 +31,16 @@ pub mod scrollbar; pub mod segmented; pub mod select; pub mod separator; +pub mod sidebar; pub mod slider; pub mod speech; pub mod spinner; pub mod status_dot; pub mod switch; +pub mod tabs; pub mod toast; pub mod toggle; pub mod tooltip; +pub mod tree; + +mod utils; diff --git a/crates/ui/src/components/popover.rs b/crates/ui/src/components/popover.rs index 95b293c..4bafd6d 100644 --- a/crates/ui/src/components/popover.rs +++ b/crates/ui/src/components/popover.rs @@ -1,6 +1,28 @@ +//! Renders a floating panel anchored below its trigger, closed by outside +//! clicks and Escape. +//! +//! # Examples +//! +//! ```no_run +//! use gpui::{IntoElement as _, ParentElement as _, SharedString, div}; +//! use ui::popover::Popover; +//! +//! let popover = Popover::new("options") +//! .trigger(|_window, _cx| { +//! div().child(SharedString::from("Options")).into_any_element() +//! }) +//! .content(|_window, _cx| { +//! div() +//! .child(SharedString::from("Panel body")) +//! .into_any_element() +//! }) +//! .on_change(|open, _window, _cx| println!("open: {open}")); +//! ``` + use std::cell::RefCell; use std::rc::Rc; +use crate::theme::{ActiveTheme as _, POPOVER_MIN_WIDTH}; use gpui::prelude::FluentBuilder as _; use gpui::{ Animation, AnimationExt as _, AnyElement, App, Bounds, DispatchPhase, ElementId, @@ -10,11 +32,12 @@ use gpui::{ }; use crate::components::common::{OVERLAY_LAYER, StyledExt as _, v_flex}; -use crate::theme::{ActiveTheme as _, POPOVER_MIN_WIDTH}; /// Reports the next open state of a [`Popover`]: `true` to open, `false` to close. type ChangeHandler = Rc; +/// The element the panel anchors below, built during render. type TriggerFn = Box AnyElement>; +/// The panel's contents, built when it opens. type ContentFn = Box AnyElement>; /// Bounds captured during the last paint, shared with the dismissal listener. type BoundsCell = Rc>>>; @@ -171,7 +194,7 @@ impl RenderOnce for Popover { .when(self.open, |wrapper| { let on_change = self.on_change; let label = fallback_label.clone(); - let focus = crate::utils::focus_handle(&self.id, window, cx); + let focus = crate::components::common::focus_handle(&self.id, window, cx); let content = self.content.map(|content| content(window, cx)); let panel = v_flex() diff --git a/crates/ui/src/components/progress.rs b/crates/ui/src/components/progress.rs index cc9bb73..2b7180e 100644 --- a/crates/ui/src/components/progress.rs +++ b/crates/ui/src/components/progress.rs @@ -1,5 +1,15 @@ -//! The progress bar: determinate fill or an indeterminate sweep. +//! Renders a progress bar with a determinate fill or an indeterminate sweep. +//! +//! # Examples +//! +//! ```no_run +//! use ui::progress::Progress; +//! +//! let upload = Progress::new("upload", 0.4); +//! let loading = Progress::new("loading", 0.0).indeterminate(true); +//! ``` +use crate::theme::{ActiveTheme as _, PROGRESS_ANIMATION_PERIOD, Size}; use gpui::prelude::FluentBuilder as _; use gpui::{ Animation, AnimationExt as _, App, ElementId, InteractiveElement as _, IntoElement, @@ -8,9 +18,8 @@ use gpui::{ }; use crate::components::common::{Sizable, StyledExt as _}; -use crate::theme::{ActiveTheme as _, PROGRESS_ANIMATION_PERIOD, Size}; -/// A progress bar. With a `value` in `0..=1` it paints a determinate fill. +/// A bar that paints a determinate fill from its `value`, or an indeterminate sweep. #[derive(IntoElement)] #[must_use] pub struct Progress { diff --git a/crates/ui/src/components/radio.rs b/crates/ui/src/components/radio.rs index 106d50f..bfc70e8 100644 --- a/crates/ui/src/components/radio.rs +++ b/crates/ui/src/components/radio.rs @@ -1,3 +1,19 @@ +//! Renders a group of radio buttons that reports the clicked choice. +//! +//! # Examples +//! +//! ```no_run +//! use ui::radio::{Radio, RadioGroup}; +//! +//! let plan = RadioGroup::new("plan") +//! .selected(Some("monthly")) +//! .child(Radio::new("monthly", "monthly").label("Monthly")) +//! .child(Radio::new("yearly", "yearly").label("Yearly")) +//! .on_change(|value, _window, _cx| println!("selected: {value}")); +//! ``` + +use crate::components::common::{Sizable, StyledExt as _, focus_ring, h_flex, v_flex}; +use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; use gpui::prelude::FluentBuilder; use gpui::{ App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, @@ -5,14 +21,10 @@ use gpui::{ div, }; -use crate::components::common::{Sizable, StyledExt as _, h_flex, v_flex}; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; -use crate::utils::focus_ring; - /// The group's change reporter, fired with the clicked radio's value. type ChangeHandler = std::rc::Rc; -/// Radio button. +/// A single choice in a [`RadioGroup`]. /// /// Each radio is its own tab stop; the full ARIA radiogroup pattern (single /// stop plus arrow-key roving focus) needs a group owner that does not exist yet. @@ -71,7 +83,7 @@ where // Radio is a data builder, not an element, adopt the combinators explicitly. impl FluentBuilder for Radio {} -/// Group of radio buttons. +/// A set of [`Radio`] choices that reports clicks through [`RadioGroup::on_change`]. #[derive(IntoElement)] #[must_use] pub struct RadioGroup @@ -128,7 +140,7 @@ where self } - /// Sets the change handler. + /// Sets the handler fired with the clicked radio's value. pub fn on_change(mut self, handler: F) -> Self where F: Fn(V, &mut Window, &mut App) + 'static, diff --git a/crates/ui/src/components/scroll_area.rs b/crates/ui/src/components/scroll_area.rs index 62c4105..9f21cfe 100644 --- a/crates/ui/src/components/scroll_area.rs +++ b/crates/ui/src/components/scroll_area.rs @@ -1,4 +1,16 @@ -//! A scrollable container with an overlay scrollbar. +//! Renders children in a scrollable pane with an overlay [`Scrollbar`]. +//! +//! # Examples +//! +//! ```no_run +//! use gpui::{div, px, ParentElement as _, Styled as _}; +//! use ui::scroll_area::{ScrollArea, ScrollAxes}; +//! +//! let log = ScrollArea::new("event-log") +//! .axes(ScrollAxes::Vertical) +//! .h(px(320.)) +//! .children((0..24).map(|line| div().child(format!("event {line}")))); +//! ``` use gpui::prelude::FluentBuilder as _; use gpui::{ diff --git a/crates/ui/src/components/scrollbar.rs b/crates/ui/src/components/scrollbar.rs index 5c68d1a..d7bfc86 100644 --- a/crates/ui/src/components/scrollbar.rs +++ b/crates/ui/src/components/scrollbar.rs @@ -1,9 +1,24 @@ -//! Overlay scrollbars for scroll surfaces. +//! Renders an overlay [`Scrollbar`] over a scrolled surface, driven by a +//! [`ScrollbarHandle`]. +//! +//! # Examples +//! +//! ```no_run +//! use gpui::{div, ScrollHandle, InteractiveElement as _, StatefulInteractiveElement as _}; +//! use ui::scrollbar::{Scrollbar, ScrollbarVisibility}; +//! +//! let handle = ScrollHandle::new(); +//! let content = div().id("log").overflow_y_scroll().track_scroll(&handle); +//! let bar = Scrollbar::vertical("log-bar", handle) +//! .visibility(ScrollbarVisibility::Autohide); +//! ``` use std::rc::Rc; use std::sync::Arc; use std::time::{Duration, Instant}; +use crate::components::common::ResultLogErr as _; +use crate::theme::{ActiveTheme as _, SCROLLBAR_AUTOHIDE_DELAY, SCROLLBAR_FADE_DURATION}; use gpui::{ App, Bounds, DispatchPhase, ElementId, Entity, EntityId, IntoElement, ListState, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, RenderOnce, ScrollEvent, @@ -11,16 +26,15 @@ use gpui::{ point, }; -use crate::theme::{ActiveTheme as _, SCROLLBAR_AUTOHIDE_DELAY, SCROLLBAR_FADE_DURATION}; -use crate::utils::ResultLogErr as _; - /// When an overlay scrollbar shows. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum ScrollbarVisibility { /// The running platform's behavior, from the theme. #[default] Platform, + /// Always visible. Always, + /// Shows on activity, then fades out. Autohide, } @@ -225,7 +239,7 @@ pub struct Scrollbar { } impl Scrollbar { - /// A vertical scrollbar named by `id`, driven by `handle`. + /// Creates a vertical scrollbar named by `id`, driven by `handle`. pub fn vertical(id: I, handle: H) -> Self where I: Into, @@ -239,7 +253,7 @@ impl Scrollbar { } } - /// A horizontal scrollbar named by `id`, driven by `handle`. + /// Creates a horizontal scrollbar named by `id`, driven by `handle`. pub fn horizontal(id: I, handle: H) -> Self where I: Into, diff --git a/crates/ui/src/components/segmented.rs b/crates/ui/src/components/segmented.rs index 9d84eb7..141cc3e 100644 --- a/crates/ui/src/components/segmented.rs +++ b/crates/ui/src/components/segmented.rs @@ -1,5 +1,23 @@ +//! Renders a segmented control for choosing one of several options. +//! +//! # Examples +//! +//! ```no_run +//! use ui::segmented::{Segmented, SegmentedOption}; +//! +//! let mode = Segmented::new("editor-mode", "text") +//! .options([ +//! SegmentedOption::new("text", "Text"), +//! SegmentedOption::new("preview", "Preview"), +//! ]) +//! .on_change(|value, _window, _cx| println!("mode: {value}")); +//! ``` + use std::rc::Rc; +use crate::components::common::{Sizable, StyledExt, focus_handle, focus_ring, h_flex}; +use crate::icons::Icon; +use crate::theme::{ActiveTheme as _, CONTROL_SPRING, Size}; use gpui::prelude::FluentBuilder; use gpui::{ AnimationExt as _, App, Bounds, ElementId, Entity, InteractiveElement as _, IntoElement, @@ -7,15 +25,10 @@ use gpui::{ StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window, canvas, div, }; -use crate::components::common::{Sizable, StyledExt, h_flex}; -use crate::icons::Icon; -use crate::theme::{ActiveTheme as _, CONTROL_SPRING, Size}; -use crate::utils::{focus_handle, focus_ring}; - /// Reports the segment the user chose. type ChangeHandler = Rc; -/// Segment option for a segmented control. +/// One choice in a [`Segmented`] strip. #[derive(Clone)] #[must_use] pub struct SegmentedOption { @@ -47,6 +60,7 @@ impl SegmentedOption { } } +/// Converts a `(value, label)` pair into an option. impl From<(T, L)> for SegmentedOption where L: Into, @@ -84,6 +98,7 @@ impl Segmented where T: Clone + PartialEq + 'static, { + /// Creates a strip with `selected` chosen. pub fn new(id: I, selected: T) -> Self where I: Into, @@ -99,7 +114,7 @@ where } } - /// Sets the choices. + /// Sets the choices from [`SegmentedOption`]s or `(value, label)` pairs. pub fn options(mut self, options: I) -> Self where I: IntoIterator, @@ -118,7 +133,7 @@ where self } - /// Overrides the strip's accessibility label. + /// Overrides the strip's accessibility label, which defaults to the element id. pub fn accessibility_label(mut self, label: L) -> Self where L: Into, diff --git a/crates/ui/src/components/select.rs b/crates/ui/src/components/select.rs index a1a5815..d428b9a 100644 --- a/crates/ui/src/components/select.rs +++ b/crates/ui/src/components/select.rs @@ -1,5 +1,25 @@ +//! Renders a control that shows the chosen value and opens a menu of the choices. +//! +//! # Examples +//! +//! ```no_run +//! use ui::select::{Select, SelectOption}; +//! +//! let theme = Select::new("theme") +//! .options([ +//! SelectOption::new("dark", "Dark"), +//! SelectOption::new("light", "Light"), +//! ]) +//! .selected("dark") +//! .on_change(|value, _window, _cx| println!("{value:?}")); +//! ``` + use std::rc::Rc; +use crate::components::common::{Sizable, StyledExt, focus_handle, h_flex}; +use crate::components::menu::{Menu, MenuItem}; +use crate::icons::{Icon, IconRole, icon}; +use crate::theme::{ActiveTheme as _, Size}; use gpui::prelude::FluentBuilder; use gpui::{ App, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, ParentElement as _, @@ -7,12 +27,6 @@ use gpui::{ Window, canvas, }; -use crate::components::common::{Sizable, StyledExt, h_flex}; -use crate::components::menu::{Menu, MenuItem}; -use crate::icons::{Icon, IconRole, icon}; -use crate::theme::{ActiveTheme as _, Size}; -use crate::utils::focus_handle; - /// Reports the value the user chose. `None` means the select holds no value. pub type SelectHandler = Rc, &mut Window, &mut App)>; diff --git a/crates/ui/src/components/separator.rs b/crates/ui/src/components/separator.rs index 29a704b..69df478 100644 --- a/crates/ui/src/components/separator.rs +++ b/crates/ui/src/components/separator.rs @@ -1,17 +1,25 @@ -//! The separator: a hairline rule between sibling content. +//! Renders a hairline rule between sibling content. +//! +//! # Examples +//! +//! ```no_run +//! use ui::separator::Separator; +//! +//! let rule = Separator::horizontal(); +//! let divider = Separator::vertical(); +//! ``` use std::rc::Rc; +use crate::components::common::StyledExt as _; +use crate::theme::{ActiveTheme as _, BORDER_WIDTH}; use gpui::prelude::FluentBuilder as _; use gpui::{ App, InteractiveElement as _, IntoElement, RenderOnce, StyleRefinement, Styled as _, Window, div, }; -use crate::theme::{ActiveTheme as _, BORDER_WIDTH}; -use crate::utils::StyledExt as _; - -/// Which axis the rule runs along. +/// The axis a [`Separator`] rule runs along. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum SeparatorOrientation { /// A horizontal rule between stacked content. @@ -21,6 +29,7 @@ pub enum SeparatorOrientation { Vertical, } +/// The debug-bounds selector, for headless tests. type DebugSelector = Rc String>; /// A hairline rule that divides sibling content. diff --git a/crates/ui/src/data/sidebar.rs b/crates/ui/src/components/sidebar.rs similarity index 94% rename from crates/ui/src/data/sidebar.rs rename to crates/ui/src/components/sidebar.rs index e6ffdea..28d2432 100644 --- a/crates/ui/src/data/sidebar.rs +++ b/crates/ui/src/components/sidebar.rs @@ -1,9 +1,28 @@ -//! The sidebar: a controlled list with section headers — the Finder -//! sidebar's model of rows grouped under non-selectable labels. Custom -//! entries slot user content between the rows. +//! Renders rows grouped under section headers, with slots for custom content between the rows. +//! +//! # Examples +//! +//! ```no_run +//! use ui::sidebar::{Sidebar, SidebarEntry}; +//! +//! let places = Sidebar::new("places") +//! .entries(|_, _| { +//! vec![ +//! SidebarEntry::header("Favorites"), +//! SidebarEntry::row("documents", "Documents").detail("24 files"), +//! ] +//! }) +//! .on_change(|_selected, _window, _cx| println!("selection changed")); +//! ``` use std::rc::Rc; +use crate::components::common::{ + StyledExt as _, nav_key, paint_selectable_row, selectable_label_color, +}; +use crate::components::grain::grain as grain_overlay; +use crate::components::scroll_area::ScrollArea; +use crate::theme::{ActiveTheme as _, BORDER_WIDTH, SIDEBAR_DEFAULT_WIDTH, TextRole, Typeset as _}; use gpui::prelude::FluentBuilder; use gpui::{ AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent, @@ -11,13 +30,9 @@ use gpui::{ StyleRefinement, Styled as _, Window, div, }; -use crate::components::grain::grain as grain_overlay; -use crate::components::scroll_area::ScrollArea; -use crate::theme::{ActiveTheme as _, BORDER_WIDTH, SIDEBAR_DEFAULT_WIDTH, TextRole, Typeset as _}; -use crate::utils::{StyledExt as _, nav_key, paint_selectable_row, selectable_label_color}; - /// The change reporter, fired with the next selected row by pointer and keys. type ChangeHandler = Rc, &mut Window, &mut App)>; +/// The entries builder, run during render. type EntriesFn = Box Vec>; /// One entry of a [`Sidebar`], a section header, a selectable row, or custom content. @@ -131,7 +146,7 @@ impl SidebarEntry { // SidebarEntry is a data builder, not an element, adopt the combinators explicitly. impl FluentBuilder for SidebarEntry {} -/// A sidebar. +/// A sidebar of [`SidebarEntry`] rows grouped under section headers. #[derive(IntoElement)] #[must_use] pub struct Sidebar { @@ -233,7 +248,7 @@ impl Sidebar { self } - /// Sets the entries, the closure runs during render and must not mutate entities or notify. + /// Sets the entries; the closure runs during render and must not mutate entities or notify. pub fn entries(mut self, entries: F) -> Self where F: Fn(&mut Window, &mut App) -> Vec + 'static, @@ -293,7 +308,7 @@ impl RenderOnce for Sidebar { .map(|(index, _)| index) .collect(); - let focus = crate::utils::focus_handle(&id, window, cx); + let focus = crate::components::common::focus_handle(&id, window, cx); let scroll = window.with_element_namespace(id.clone(), |window| { window .use_keyed_state("scroll", cx, |_, _| gpui::ScrollHandle::new()) diff --git a/crates/ui/src/components/slider.rs b/crates/ui/src/components/slider.rs index 09f6f29..b4b99d9 100644 --- a/crates/ui/src/components/slider.rs +++ b/crates/ui/src/components/slider.rs @@ -1,6 +1,20 @@ +//! Renders a controlled slider that reports its next value on click, drag, and arrow keys. +//! +//! # Examples +//! +//! ```no_run +//! use ui::slider::Slider; +//! +//! let opacity = Slider::new("opacity", 1.0) +//! .step(0.25) +//! .on_change(|value, _window, _cx| println!("opacity: {value}")); +//! ``` + use std::cell::Cell; use std::rc::Rc; +use crate::components::common::{Sizable, StyledExt as _, focus_ring, h_flex}; +use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; use gpui::prelude::FluentBuilder as _; use gpui::{ App, Bounds, DispatchPhase, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, @@ -9,10 +23,6 @@ use gpui::{ div, relative, }; -use crate::components::common::{Sizable, StyledExt as _, h_flex}; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; -use crate::utils::focus_ring; - /// The change reporter, fired with the next value by click, drag, and arrows. type ChangeHandler = Rc; @@ -103,7 +113,7 @@ impl Slider { self } - /// The change handler, fired with the next value by click, drag, and arrows. + /// Sets the change handler, fired with the next value by click, drag, and arrows. pub fn on_change(mut self, handler: F) -> Self where F: Fn(f32, &mut Window, &mut App) + 'static, @@ -145,7 +155,7 @@ impl RenderOnce for Slider { }; let bounds_cell = Rc::new(Cell::new(None::>)); - let focus_handle = crate::utils::focus_handle(&self.id, window, cx); + let focus_handle = crate::components::common::focus_handle(&self.id, window, cx); let dragging = window.use_keyed_state((self.id.clone(), "slider-dragging"), cx, |_, _| false); diff --git a/crates/ui/src/components/speech.rs b/crates/ui/src/components/speech.rs index a7c4de7..1e4bba3 100644 --- a/crates/ui/src/components/speech.rs +++ b/crates/ui/src/components/speech.rs @@ -6,11 +6,34 @@ //! both replaceable seams; without further setup the state uses [`Microphone`] //! and has no recognizer, so [`SpeechButton`] renders nothing until the //! application provides one. +//! +//! # Examples +//! +//! ```no_run +//! use ui::speech::{SpeechButton, SpeechRecognizer, SpeechState}; +//! +//! # use gpui::{App, AppContext as _}; +//! # fn bind(cx: &mut App, recognizer: R) +//! # where +//! # R: SpeechRecognizer + 'static, +//! # { +//! // Create the state once and hold its entity in the owning view. +//! let speech = cx.new(|cx| SpeechState::new(cx).recognizer(recognizer)); +//! +//! let dictation = SpeechButton::new(&speech); +//! # } +//! ``` + +use std::time::Duration; #[cfg(not(target_arch = "wasm32"))] use std::sync::{Arc, Mutex}; -use std::time::Duration; +use crate::components::common::{Sizable, StyledExt as _, focus_ring, h_flex}; +use crate::components::spinner::{Spinner, SpinnerVariant}; +use crate::components::tooltip::Tooltip; +use crate::icons::{IconRole, icon}; +use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, SPEECH_WAVEFORM_WIDTH, Size}; use gpui::prelude::FluentBuilder as _; use gpui::{ App, Context, ElementId, Entity, EventEmitter, InteractiveElement as _, IntoElement, @@ -18,13 +41,6 @@ use gpui::{ StyleRefinement, Styled, Subscription, Task, WeakEntity, Window, div, relative, }; -use crate::components::common::{Sizable, StyledExt as _, h_flex}; -use crate::components::spinner::{Spinner, SpinnerVariant}; -use crate::components::tooltip::Tooltip; -use crate::icons::{IconRole, icon}; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, SPEECH_WAVEFORM_WIDTH, Size}; -use crate::utils::focus_ring; - /// One input-level entry per this much of captured audio. const LEVEL_BUCKET: Duration = Duration::from_millis(80); /// The level history a waveform draws, one entry per [`LEVEL_BUCKET`]. @@ -129,6 +145,10 @@ pub trait SpeechRecognizer { } /// Opens a session. + /// + /// # Errors + /// + /// Errors when the recognizer cannot open a session. fn start( &self, sink: SpeechSink, @@ -203,6 +223,12 @@ impl SpeechSink { /// Captures audio for a session. pub trait AudioInput { + /// Starts capture in `format`, pushing samples to `sink`; dropping the + /// returned `Subscription` stops capture. + /// + /// # Errors + /// + /// Errors when capture cannot start; no samples are delivered. fn start( &self, format: AudioFormat, @@ -668,7 +694,7 @@ impl SpeechButton { } } - /// Renders the button disabled. + /// Shows the button even when dictation is unsupported, rendered disabled. pub fn show_when_unsupported(mut self, show: bool) -> Self { self.show_when_unsupported = show; self diff --git a/crates/ui/src/components/spinner.rs b/crates/ui/src/components/spinner.rs index 290414d..0005706 100644 --- a/crates/ui/src/components/spinner.rs +++ b/crates/ui/src/components/spinner.rs @@ -1,9 +1,22 @@ -//! The loading ring: spins for unknown work, or holds a determinate arc. +//! Renders a loading ring that spins for unknown work, or holds a determinate +//! arc for known progress. +//! +//! # Examples +//! +//! ```no_run +//! use ui::spinner::{Spinner, SpinnerVariant}; +//! +//! let loading = Spinner::new("loading"); +//! let progress = Spinner::new("progress").value(0.5); +//! let glyph = Spinner::new("glyph").variant(SpinnerVariant::Icon); +//! ``` use std::cell::Cell; use std::f32::consts::{PI, TAU}; use std::rc::Rc; +use crate::icons::{Icon, IconRole, icon}; +use crate::theme::{ActiveTheme as _, SPINNER_PERIOD, Size}; use gpui::prelude::FluentBuilder as _; use gpui::{ Animation, AnimationElement, AnimationExt as _, App, Canvas, ElementId, Hsla, @@ -13,8 +26,6 @@ use gpui::{ }; use crate::components::common::{Sizable, StyledExt as _}; -use crate::icons::{Icon, IconRole, icon}; -use crate::theme::{ActiveTheme as _, SPINNER_PERIOD, Size}; /// The share of the circle the spinning arc paints. const SPIN_SWEEP: f32 = 0.75; @@ -31,7 +42,7 @@ pub enum SpinnerVariant { Icon, } -/// A loading ring. +/// A loading ring that spins for unknown work or paints a determinate arc. #[derive(IntoElement)] #[must_use] pub struct Spinner { @@ -200,6 +211,7 @@ fn spinning_icon(side: Pixels, accent: Hsla) -> Icon { .with_rotation_animation(SPINNER_PERIOD) } +/// Paints a stroked circle into the window. fn paint_circle( center: Point, radius: Pixels, @@ -260,41 +272,3 @@ fn circle_path(center: Point, radius: Pixels, stroke: Pixels) -> Option< ); builder.build().ok() } - -#[cfg(test)] -mod tests { - use std::f32::consts::FRAC_PI_2; - - use super::*; - - #[test] - fn ring_points_run_clockwise_from_twelve() { - let center = point(px(10.0), px(20.0)); - let radius = px(4.0); - assert_eq!(ring_point(center, radius, 0.0), point(px(10.0), px(16.0))); - assert_eq!( - ring_point(center, radius, FRAC_PI_2), - point(px(14.0), px(20.0)) - ); - assert_eq!(ring_point(center, radius, PI), point(px(10.0), px(24.0))); - assert_eq!( - ring_point(center, radius, -FRAC_PI_2), - point(px(6.0), px(20.0)) - ); - } - - #[test] - fn arcs_tessellate_across_the_range() { - let center = point(px(0.0), px(0.0)); - let radius = px(8.0); - let stroke = px(2.0); - // The large-arc flag flips past half a circle; both sides must build. - for fraction in [0.25, 0.5, 0.75] { - assert!( - arc_path(center, radius, stroke, 0.0, fraction * TAU).is_some(), - "fraction {fraction} failed to build" - ); - } - assert!(circle_path(center, radius, stroke).is_some()); - } -} diff --git a/crates/ui/src/components/status_dot.rs b/crates/ui/src/components/status_dot.rs index 2a077f6..90c7b61 100644 --- a/crates/ui/src/components/status_dot.rs +++ b/crates/ui/src/components/status_dot.rs @@ -1,5 +1,16 @@ -//! The status dot: a small colored bead for row state. +//! Renders a small colored bead that marks a row's state. +//! +//! # Examples +//! +//! ```no_run +//! use ui::status_dot::{StatusDot, StatusDotVariant}; +//! +//! let dot = StatusDot::new("deploy-status") +//! .variant(StatusDotVariant::Success) +//! .label("Deployed"); +//! ``` +use crate::theme::{ActiveTheme as _, Size, Theme}; use gpui::prelude::FluentBuilder as _; use gpui::{ App, ElementId, Hsla, InteractiveElement as _, IntoElement, RenderOnce, Role, SharedString, @@ -7,16 +18,20 @@ use gpui::{ }; use crate::components::common::{Sizable, StyledExt}; -use crate::theme::{ActiveTheme as _, Size, Theme}; /// How loud a dot is, the same vocabulary as [`crate::components::badge::BadgeVariant`]. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum StatusDotVariant { + /// The theme's muted foreground color. #[default] Neutral, + /// The theme's primary color. Accent, + /// The theme's success color. Success, + /// The theme's warning color. Warning, + /// The theme's destructive color. Danger, } @@ -64,7 +79,7 @@ impl StatusDot { self } - /// The state the dot announces to screen readers. + /// Sets the state the dot announces to screen readers. pub fn label(mut self, label: L) -> Self where L: Into, diff --git a/crates/ui/src/components/switch.rs b/crates/ui/src/components/switch.rs index c586f5e..e5ced1d 100644 --- a/crates/ui/src/components/switch.rs +++ b/crates/ui/src/components/switch.rs @@ -1,5 +1,18 @@ -//! The switch: a controlled on/off pill with a thumb. +//! Renders a controlled on/off switch with a spring-animated thumb. +//! +//! # Examples +//! +//! ```no_run +//! use ui::switch::Switch; +//! +//! let wifi = Switch::new("wifi") +//! .label("Wi-Fi") +//! .checked(false) +//! .on_change(|checked, _window, _cx| println!("checked: {checked}")); +//! ``` +use crate::components::common::{Sizable, StyledExt as _, focus_ring, h_flex}; +use crate::theme::{ActiveTheme as _, BORDER_WIDTH, CONTROL_SPRING, DISABLED_OPACITY, Size}; use gpui::prelude::FluentBuilder as _; use gpui::{ AnimationExt as _, App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, @@ -7,14 +20,10 @@ use gpui::{ StyleRefinement, Styled as _, Toggled, Window, div, px, }; -use crate::components::common::{Sizable, StyledExt as _, h_flex}; -use crate::theme::{ActiveTheme as _, BORDER_WIDTH, CONTROL_SPRING, DISABLED_OPACITY, Size}; -use crate::utils::focus_ring; - /// The change reporter, fired with the next value by pointer, Enter, and Space. type ChangeHandler = Box; -/// Switch component. +/// A controlled on/off switch that fires [`Switch::on_change`] on toggle. #[derive(IntoElement)] #[must_use] pub struct Switch { @@ -61,7 +70,7 @@ impl Switch { self } - /// Renders the switch inert, unfocusable, and dimmed; disabled always wins. + /// Renders the switch inert, unfocusable, and dimmed. pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; self @@ -76,7 +85,7 @@ impl Switch { self } - /// The change handler, fired with the next value by pointer, Enter, and Space. + /// Sets the change handler, fired with the next value by pointer, Enter, and Space. pub fn on_change(mut self, handler: F) -> Self where F: Fn(bool, &mut Window, &mut App) + 'static, diff --git a/crates/ui/src/data/tabs.rs b/crates/ui/src/components/tabs.rs similarity index 85% rename from crates/ui/src/data/tabs.rs rename to crates/ui/src/components/tabs.rs index 5dc1143..1827b91 100644 --- a/crates/ui/src/data/tabs.rs +++ b/crates/ui/src/components/tabs.rs @@ -1,24 +1,43 @@ +//! Renders a strip of [`Tab`]s with selection, close controls, drag reordering, and overflow. +//! +//! # Examples +//! +//! ```no_run +//! use ui::tabs::{Tab, Tabs}; +//! +//! let editors = Tabs::new("editors") +//! .tabs(|_, _| { +//! vec![ +//! Tab::new("readme", "README").closeable(true), +//! Tab::new("changelog", "CHANGELOG").closeable(true), +//! ] +//! }) +//! .on_change(|_index, _window, _cx| println!("tab changed")); +//! ``` + use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; -use gpui::prelude::FluentBuilder; -use gpui::{ - AnyElement, App, AppContext as _, Bounds, ClickEvent, Context, Div, ElementId, Global, - InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, ParentElement as _, Pixels, - Point, Render, RenderOnce, Role, SharedString, Stateful, StatefulInteractiveElement as _, - StyleRefinement, Styled as _, Window, canvas, div, px, relative, -}; - use crate::components::button::{Button, ButtonVariant}; -use crate::components::common::{Sizable as _, v_flex}; +use crate::components::common::{Sizable as _, StyledExt as _, adjacent_selectable, v_flex}; use crate::components::popover::Popover; use crate::components::scroll_area::{ScrollArea, ScrollAxes}; use crate::components::spinner::Spinner; use crate::components::tooltip::Tooltip; use crate::icons::IconRole; -use crate::theme::{ActiveTheme as _, POPUP_MAX_HEIGHT, Size, TAB_INDICATOR_WIDTH}; -use crate::utils::{StyledExt as _, adjacent_selectable}; +use crate::theme::{ + ActiveTheme as _, ControlMetrics, POPUP_MAX_HEIGHT, Size, TAB_INDICATOR_WIDTH, TAB_MAX_WIDTH, + TAB_MIN_WIDTH, +}; +use gpui::prelude::FluentBuilder; +use gpui::{ + AnyElement, App, AppContext as _, Bounds, ClickEvent, Context, Div, ElementId, Global, + InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, ParentElement as _, Pixels, + Point, Render, RenderOnce, Role, SharedString, Stateful, StatefulInteractiveElement as _, + StyleRefinement, Styled as _, TextOverflow, Window, canvas, div, linear_color_stop, + linear_gradient, px, relative, +}; /// Reports the next selected tab by pointer and keys. type ChangeHandler = Rc; @@ -28,6 +47,7 @@ type CloseHandler = Rc; type ReorderHandler = Rc; /// Decorates the rendered tab, e.g. to attach a drag payload. type TabWrap = Box) -> AnyElement>; +/// The tab builder, run during render. type TabsFn = Box Vec>; /// The open-state reporter of the overflow popover. type OpenHandler = Rc; @@ -204,9 +224,20 @@ impl Render for TabDragPreview { /// The visual language of a [`Tabs`] strip. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum TabsVariant { + /// A bottom indicator line on the active tab. #[default] Underline, + /// Capsule tabs with an elevated active background. Pill, + /// Floating capsule tabs sized for a window titlebar. + Titlebar, +} + +impl TabsVariant { + /// Whether the variant draws capsule-shaped tabs. + fn is_capsule(self) -> bool { + matches!(self, Self::Pill | Self::Titlebar) + } } /// One tab of a [`Tabs`] strip. @@ -299,7 +330,7 @@ impl Tab { // Tab is a data builder, not an element, adopt the combinators explicitly. impl FluentBuilder for Tab {} -/// A tab strip. +/// A tab strip with selection, close, and reorder handling. #[derive(IntoElement)] #[must_use] pub struct Tabs { @@ -343,7 +374,7 @@ impl Tabs { } } - /// Sets the current selection, as an index into the `tabs` vec — not a tab key. + /// Sets the current selection as an index into the `tabs` vec, not a tab key. pub fn selected(mut self, selected: usize) -> Self { self.selected = selected; self @@ -388,7 +419,8 @@ impl Tabs { self } - /// Reports the next selected tab, as an index into the `tabs` vec — not a tab key; indices shift on reorder. + /// Reports the next selected tab as an index into the `tabs` vec, not a tab key; indices + /// shift on reorder. pub fn on_change(mut self, handler: F) -> Self where F: Fn(usize, &mut Window, &mut App) + 'static, @@ -397,7 +429,8 @@ impl Tabs { self } - /// Reports a closed tab, as an index into the `tabs` vec — not a tab key; indices shift on reorder. + /// Reports a closed tab as an index into the `tabs` vec, not a tab key; indices shift on + /// reorder. pub fn on_close(mut self, handler: F) -> Self where F: Fn(usize, &mut Window, &mut App) + 'static, @@ -588,6 +621,7 @@ impl Tabs { let theme = cx.theme(); let metrics = theme.sizes.resolve(Size::default()); let small = theme.sizes.small; + let group_key = group_key(&tabs_id, &kind); let label_color = match ctx.variant { TabsVariant::Underline => { @@ -598,9 +632,15 @@ impl Tabs { } } TabsVariant::Pill => theme.colors.foreground, + TabsVariant::Titlebar => { + if active { + theme.colors.foreground + } else { + theme.colors.muted_foreground + } + } }; - let group_key = group_key(&tabs_id, &kind); let chip = div() .id((group_key.clone(), "group-tab")) .debug_selector({ @@ -617,7 +657,12 @@ impl Tabs { .aria_label(SharedString::from(format!("{kind}, {count} tabs"))) .text_color(label_color) .when(!active, |chip| { - chip.hover(|chip| chip.bg(theme.colors.muted)) + chip.hover(|chip| { + chip.bg(match ctx.variant { + TabsVariant::Titlebar => theme.colors.muted_hover, + _ => theme.colors.muted, + }) + }) }) .map(|chip| match ctx.variant { TabsVariant::Underline => chip @@ -628,18 +673,24 @@ impl Tabs { .border_b(TAB_INDICATOR_WIDTH) .border_color(gpui::transparent_black()) .when(active, |chip| chip.border_color(theme.ramps.primary.base)), - TabsVariant::Pill => chip + TabsVariant::Pill | TabsVariant::Titlebar => chip .h(small.control_height + metrics.plate_inset * 2.0) .px(metrics.dense_padding_x) .pr(metrics.plate_inset) - .rounded(theme.radius.control) + .rounded(match ctx.variant { + TabsVariant::Titlebar => theme.radius.full, + _ => theme.radius.control, + }) + .when(ctx.variant == TabsVariant::Titlebar, |chip| { + chip.bg(theme.colors.muted) + }) .when(active, |chip| { chip.bg(theme.colors.background) .shadow(theme.elevations.control.shadows()) }), }) .child(SharedString::from(format!("{kind} ({count})"))) - .when(ctx.variant == TabsVariant::Pill, |chip| { + .when(ctx.variant.is_capsule(), |chip| { chip.child(div().flex_none().w(metrics.padding_x * 1.5)) }) .when_some(ctx.measure.clone(), |chip, measure| { @@ -745,12 +796,12 @@ impl RenderOnce for Tabs { }) .collect(); - let focus = crate::utils::focus_handle(&self.id, window, cx); + let focus = crate::components::common::focus_handle(&self.id, window, cx); // Theme reads end here, so the strip's group chips can take `cx` mutably. let (medium_text_size, border_color, shadow_bleed) = { let theme = cx.theme(); let shadow_bleed = match self.variant { - TabsVariant::Pill => theme.elevations.control.bleed(), + TabsVariant::Pill | TabsVariant::Titlebar => theme.elevations.control.bleed(), TabsVariant::Underline => Pixels::ZERO, }; ( @@ -901,7 +952,7 @@ impl RenderOnce for Tabs { }) .map(|root| match self.variant { TabsVariant::Underline => root.gap_1().border_b_1().border_color(border_color), - TabsVariant::Pill => root.items_center().gap_1(), + TabsVariant::Pill | TabsVariant::Titlebar => root.items_center().gap_1(), }) .map(|root| { if self.overflow_popover { @@ -955,7 +1006,7 @@ impl RenderOnce for Tabs { .flex_none() .flex() .gap_1() - .when(self.variant == TabsVariant::Pill, |row| row.items_center()) + .when(self.variant.is_capsule(), |row| row.items_center()) .children(strip), ) .child(control.child(trigger_canvas)) @@ -969,7 +1020,7 @@ impl RenderOnce for Tabs { .flex_none() .flex() .gap_1() - .when(self.variant == TabsVariant::Pill, |row| row.items_center()) + .when(self.variant.is_capsule(), |row| row.items_center()) .children(strip), ) } else { @@ -1006,10 +1057,85 @@ impl Tab { theme.colors.foreground } } + TabsVariant::Titlebar => { + if self.disabled || !active { + theme.colors.muted_foreground + } else { + theme.colors.foreground + } + } }; - let close = (self.closeable && ctx.on_close.is_some() && !self.disabled) - .then(|| self.render_tab_close(&ctx.id, index, &ctx.on_close)); + let titlebar = ctx.variant == TabsVariant::Titlebar; + let group = SharedString::from(format!("{}-tab-{}", ctx.id, self.key)); + let close = (self.closeable && ctx.on_close.is_some() && !self.disabled).then(|| { + let close_metrics = ControlMetrics { + control_height: small.control_height - metrics.plate_inset * 2.0, + icon_size: theme.sizes.xsmall.icon_size, + ..small + }; + self.render_tab_close(&ctx.id, index, &ctx.on_close, close_metrics) + }); + + let label = div() + .flex_grow(1.0) + .when(titlebar, |label| { + let fade = if active { + theme.colors.background + } else { + theme.colors.muted + }; + + let hover_fade = if active { + theme.colors.background + } else { + theme.colors.muted_hover + }; + + let fade_width = metrics.padding_x; + let hover_fade_width = metrics.padding_x * 2.0; + + label + .min_w_0() + .relative() + .overflow_hidden() + .child( + div() + .w_full() + .whitespace_nowrap() + .text_overflow(TextOverflow::Truncate(SharedString::default())) + .child(self.label.clone()), + ) + .child( + div() + .absolute() + .top_0() + .right_0() + .bottom_0() + .w(fade_width) + .bg(linear_gradient( + 90., + linear_color_stop(fade.opacity(0.), 0.), + linear_color_stop(fade, 1.), + )), + ) + .child( + div() + .absolute() + .top_0() + .right_0() + .bottom_0() + .w(hover_fade_width) + .bg(linear_gradient( + 90., + linear_color_stop(hover_fade.opacity(0.), 0.), + linear_color_stop(hover_fade, 1.), + )) + .invisible() + .group_hover(group.clone(), |style| style.visible()), + ) + }) + .when(!titlebar, |label| label.child(self.label.clone())); let strip_tab = div() .id((self.key.clone(), "tab")) @@ -1025,8 +1151,14 @@ impl Tab { .aria_selected(selected) .text_color(label_color) .line_height(relative(1.0)) + .when(titlebar, |strip_tab| strip_tab.group(group.clone())) .when(!self.disabled && !active, |strip_tab| { - strip_tab.hover(|strip_tab| strip_tab.bg(theme.colors.muted)) + strip_tab.hover(|strip_tab| { + strip_tab.bg(match ctx.variant { + TabsVariant::Titlebar => theme.colors.muted_hover, + _ => theme.colors.muted, + }) + }) }) .map(|strip_tab| match ctx.variant { TabsVariant::Underline => strip_tab @@ -1039,11 +1171,20 @@ impl Tab { .when(active, |strip_tab| { strip_tab.border_color(theme.ramps.primary.base) }), - TabsVariant::Pill => strip_tab + TabsVariant::Pill | TabsVariant::Titlebar => strip_tab .h(small.control_height + metrics.plate_inset * 2.0) .px(metrics.dense_padding_x) .pr(metrics.plate_inset) - .rounded(theme.radius.control) + .rounded(match ctx.variant { + TabsVariant::Titlebar => theme.radius.full, + _ => theme.radius.control, + }) + .when(titlebar, |strip_tab| { + strip_tab + .min_w(TAB_MIN_WIDTH) + .max_w(TAB_MAX_WIDTH) + .bg(theme.colors.muted) + }) .when(active, |strip_tab| { strip_tab .bg(theme.colors.background) @@ -1051,7 +1192,7 @@ impl Tab { }), }) .when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead)) - .child(div().flex_grow(1.0).child(self.label.clone())) + .child(label) .when(ctx.variant == TabsVariant::Pill, |strip_tab| { strip_tab.child(div().flex_none().w(metrics.padding_x * 1.5)) }) @@ -1062,7 +1203,19 @@ impl Tab { .accessibility_label("Loading"), ) }) - .when_some(close, |strip_tab, close| strip_tab.child(close)) + .when_some(close, |strip_tab, close| { + if titlebar { + strip_tab.child( + div() + .flex_none() + .invisible() + .group_hover(group, |style| style.visible()) + .child(close), + ) + } else { + strip_tab.child(close) + } + }) .when( { let drop = ctx.drop_at.read(cx); @@ -1198,11 +1351,13 @@ impl Tab { tabs_id: &ElementId, index: usize, on_close: &Option, + metrics: ControlMetrics, ) -> AnyElement { Button::new((self.key.clone(), "tab-close")) .icon(IconRole::Close) .variant(ButtonVariant::Ghost) - .xsmall() + .custom_size(metrics) + .fully_rounded(true) .tab_stop(false) .debug_selector({ let tabs_id = tabs_id.clone(); diff --git a/crates/ui/src/components/toast.rs b/crates/ui/src/components/toast.rs index 2bd313b..80e60ee 100644 --- a/crates/ui/src/components/toast.rs +++ b/crates/ui/src/components/toast.rs @@ -1,8 +1,26 @@ //! Toasts: succinct, temporary messages at the bottom center of the window. +//! +//! A [`Toasts`] entity holds the raised toast, and a [`ToastsView`] renders +//! it; mount the view at the window root. +//! +//! # Examples +//! +//! ```no_run +//! use ui::toast::{Toast, ToastAction}; +//! +//! let toast = Toast::new("Copied to clipboard") +//! .action(ToastAction::new("Undo", |_cx| println!("undo"))); +//! ``` use std::rc::Rc; use std::time::Duration; +use crate::components::button::{Button, ButtonVariant}; +use crate::components::common::{ + DismissHandler, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, +}; +use crate::icons::{Icon, IconRole}; +use crate::theme::{ActiveTheme as _, TOAST_MAX_WIDTH}; use gpui::prelude::FluentBuilder; use gpui::{ Animation, AnimationExt as _, App, Context, ElementId, Entity, InteractiveElement as _, @@ -11,12 +29,6 @@ use gpui::{ ease_out_quint, px, }; -use crate::components::button::{Button, ButtonVariant}; -use crate::components::common::{DismissHandler, Sizable as _, StyledExt as _, TOAST_LAYER}; -use crate::icons::{Icon, IconRole}; -use crate::theme::{ActiveTheme as _, TOAST_MAX_WIDTH}; -use crate::utils::ResultLogErr as _; - /// The action handler of a [`Toast`]. pub type ActionHandler = Rc; diff --git a/crates/ui/src/components/toggle.rs b/crates/ui/src/components/toggle.rs index 9abd382..dbc21e1 100644 --- a/crates/ui/src/components/toggle.rs +++ b/crates/ui/src/components/toggle.rs @@ -1,18 +1,29 @@ +//! Renders a two-state control that reports its next pressed state on click. +//! +//! # Examples +//! +//! ```no_run +//! use ui::toggle::Toggle; +//! +//! let bold = Toggle::new("bold") +//! .label("Bold") +//! .pressed(true) +//! .on_change(|pressed, _window, _cx| println!("bold: {pressed}")); +//! ``` + +use crate::components::common::{Sizable, StyledExt as _, focus_ring, h_flex}; +use crate::icons::Icon; +use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; use gpui::prelude::FluentBuilder as _; use gpui::{ App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window, }; -use crate::components::common::{Sizable, StyledExt as _, h_flex}; -use crate::icons::Icon; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; -use crate::utils::focus_ring; - /// The change handler, fired with the next pressed state. type ChangeHandler = Box; -/// A toggle component. +/// A two-state control that reports the next pressed state on click. #[derive(IntoElement)] #[must_use] pub struct Toggle { diff --git a/crates/ui/src/components/tooltip.rs b/crates/ui/src/components/tooltip.rs index 6cb4648..9f0bf54 100644 --- a/crates/ui/src/components/tooltip.rs +++ b/crates/ui/src/components/tooltip.rs @@ -1,11 +1,26 @@ -use gpui::{ - AnyView, App, AppContext as _, Bounds, Context, ElementId, Entity, InteractiveElement as _, - IntoElement, ParentElement as _, Pixels, Render, Role, SharedString, - StatefulInteractiveElement as _, Styled as _, Window, canvas, div, point, -}; +//! Renders a small text panel next to a hovered element. +//! +//! Most call sites hand [`Tooltip::text`] or [`Tooltip::anchored`] to gpui's +//! `.tooltip(...)` method; [`Tooltip::new`] creates the view for callers that +//! hold the [`gpui::Entity`] themselves. +//! +//! # Examples +//! +//! ```no_run +//! use ui::tooltip::Tooltip; +//! +//! # let mut cx: gpui::App = unimplemented!(); +//! let tip = Tooltip::new("Delete the selected project", &mut cx); +//! ``` +use crate::components::common::{anchor_bounds, record_anchor_bounds}; use crate::theme::{ActiveTheme as _, BORDER_WIDTH, TOOLTIP_MAX_WIDTH, TOOLTIP_OFFSET}; -use crate::utils::{anchor_bounds, record_anchor_bounds}; +use gpui::AppContext as _; +use gpui::{ + AnyView, App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, + ParentElement as _, Pixels, Render, Role, SharedString, StatefulInteractiveElement as _, + Styled as _, Window, canvas, div, point, +}; const PANEL_BOUNDS_ID: &str = "tooltip-panel-bounds"; @@ -27,9 +42,10 @@ impl Tooltip { }) } - /// Sets the anchor element ID for the tooltip. + /// Returns the `.tooltip(...)` closure that pins the panel next to the + /// element identified by `anchor_id`. /// - /// The `.tooltip(...)` closure pinning the panel next to `anchor_id`. + /// [`Tooltip::text`] places the panel at the pointer instead. pub fn anchored( text: L, anchor_id: I, @@ -50,7 +66,7 @@ impl Tooltip { } } - /// The `.tooltip(...)` closure for a plain text tooltip. + /// Returns the `.tooltip(...)` closure for a plain text tooltip. pub fn text(text: L) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static where L: Into, diff --git a/crates/ui/src/data/tree.rs b/crates/ui/src/components/tree.rs similarity index 91% rename from crates/ui/src/data/tree.rs rename to crates/ui/src/components/tree.rs index e5088ab..11b867b 100644 --- a/crates/ui/src/data/tree.rs +++ b/crates/ui/src/components/tree.rs @@ -1,5 +1,27 @@ +//! Renders a single-selection tree of [`TreeItem`] rows with disclosure chevrons. +//! +//! # Examples +//! +//! ```no_run +//! use ui::tree::{Tree, TreeItem}; +//! +//! let project = Tree::new("project") +//! .items(|_, _| { +//! vec![ +//! TreeItem::new("src", "src").expandable(true).expanded(true), +//! TreeItem::new("main", "main.rs").depth(1), +//! ] +//! }) +//! .on_change(|_selected, _window, _cx| println!("selection changed")); +//! ``` + use std::rc::Rc; +use crate::components::common::{ + StyledExt as _, nav_key, paint_selectable_row, selectable_label_color, +}; +use crate::icons::{Icon, IconRole, icon}; +use crate::theme::ActiveTheme as _; use gpui::prelude::FluentBuilder; use gpui::{ AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent, @@ -7,17 +29,14 @@ use gpui::{ StyleRefinement, Styled as _, Window, div, }; -use crate::icons::{Icon, IconRole, icon}; -use crate::theme::ActiveTheme as _; -use crate::utils::{StyledExt as _, nav_key, paint_selectable_row, selectable_label_color}; - /// The change reporter, fired with the next selection by pointer and keys. type ChangeHandler = Rc, &mut Window, &mut App)>; /// The disclosure reporter, fired with the toggled row's index. type DisclosureHandler = Rc; +/// The visible row builder, run during render. type ItemsFn = Box Vec>; -/// Tree item. +/// One row of a [`Tree`]. #[derive(Clone)] #[must_use] pub struct TreeItem { @@ -85,7 +104,7 @@ impl TreeItem { // TreeItem is a data builder, not an element, adopt the combinators explicitly. impl FluentBuilder for TreeItem {} -/// A tree. +/// A tree of [`TreeItem`] rows with single selection and disclosure handling. #[derive(IntoElement)] #[must_use] pub struct Tree { @@ -233,7 +252,7 @@ impl RenderOnce for Tree { .map(|(index, _)| index) .collect(); - let focus = crate::utils::focus_handle(&self.id, window, cx); + let focus = crate::components::common::focus_handle(&self.id, window, cx); let theme = cx.theme(); let label = self @@ -438,40 +457,3 @@ impl TreeItem { .into_any_element() } } - -#[cfg(test)] -mod tests { - use super::*; - - fn item(depth: usize) -> TreeItem { - TreeItem::new("item", "Item").depth(depth) - } - - #[test] - fn flat_rows_number_one_of_three() { - let sets = Tree::sibling_sets(&[item(0), item(0), item(0)]); - assert_eq!(sets, vec![(1, 3), (2, 3), (3, 3)]); - } - - #[test] - fn nested_rows_number_per_level() { - let sets = Tree::sibling_sets(&[item(0), item(1), item(2), item(1), item(0)]); - assert_eq!(sets, vec![(1, 2), (1, 2), (1, 1), (2, 2), (2, 2)]); - } - - #[test] - fn parent_skips_the_subtree_above() { - let rows = [item(0), item(1), item(2), item(1), item(0)]; - assert_eq!(Tree::parent_of(&rows, 3), Some(0)); - assert_eq!(Tree::parent_of(&rows, 2), Some(1)); - assert_eq!(Tree::parent_of(&rows, 0), None); - } - - #[test] - fn first_descendant_skips_disabled_rows() { - let rows = [item(0), item(1), item(1), item(0)]; - let selectable = vec![0, 2, 3]; - assert_eq!(Tree::first_descendant(&rows, &selectable, 0), Some(2)); - assert_eq!(Tree::first_descendant(&rows, &selectable, 2), None); - } -} diff --git a/crates/ui/src/editor/utils.rs b/crates/ui/src/components/utils.rs similarity index 90% rename from crates/ui/src/editor/utils.rs rename to crates/ui/src/components/utils.rs index 372f170..7ba90d0 100644 --- a/crates/ui/src/editor/utils.rs +++ b/crates/ui/src/components/utils.rs @@ -3,15 +3,15 @@ use std::ops::Range; -use gpui::{ - App, HighlightStyle, Hsla, IntoElement, ParentElement as _, Styled as _, StyledText, div, -}; +use crate::components::highlight::{Language, Line}; +use crate::theme::{ActiveTheme as _, CODE_GUTTER_WIDTH}; +use crate::theme::{ColorTokens, Ramps}; +use crate::theme::{WASH_ALPHA, WASH_ALPHA_GUTTER, WASH_ALPHA_STRONG}; +use gpui::StyledText; +use gpui::{App, IntoElement, ParentElement as _, Styled as _, div}; +use gpui::{HighlightStyle, Hsla}; -use crate::editor::highlight::{Language, Line, Role}; -use crate::theme::{ - ActiveTheme as _, CODE_GUTTER_WIDTH, ColorTokens, Ramps, WASH_ALPHA, WASH_ALPHA_GUTTER, - WASH_ALPHA_STRONG, -}; +use crate::components::highlight::Role; impl Role { /// Maps the role to the theme's semantic palette. diff --git a/crates/ui/src/data/mod.rs b/crates/ui/src/data/mod.rs deleted file mode 100644 index afea2d8..0000000 --- a/crates/ui/src/data/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -//! Data-heavy components: lists, trees, tabs, sidebars. - -pub mod list; -pub mod sidebar; -pub mod tabs; -pub mod tree; diff --git a/crates/ui/src/editor/mod.rs b/crates/ui/src/editor/mod.rs deleted file mode 100644 index 0666282..0000000 --- a/crates/ui/src/editor/mod.rs +++ /dev/null @@ -1,8 +0,0 @@ -//! Read-only code surfaces: tree-sitter highlighted code views. - -pub mod code; -pub mod diff; -pub mod highlight; -pub mod markdown; - -mod utils; diff --git a/crates/ui/src/icons/freedesktop.rs b/crates/ui/src/icons/freedesktop.rs index 38a201f..c386745 100644 --- a/crates/ui/src/icons/freedesktop.rs +++ b/crates/ui/src/icons/freedesktop.rs @@ -274,156 +274,3 @@ fn active_theme() -> String { fn base_dirs() -> Vec { Vec::new() } - -#[cfg(test)] -mod tests { - use super::*; - - fn scratch(name: &str) -> PathBuf { - let root = - std::env::temp_dir().join(format!("gpui-native-icons-{name}-{}", std::process::id())); - // NotFound is the expected first run; anything else is a setup failure. - if let Err(error) = std::fs::remove_dir_all(&root) - && error.kind() != std::io::ErrorKind::NotFound - { - panic!("failed to clear scratch dir {root:?}: {error}"); - } - std::fs::create_dir_all(&root).expect("scratch dir"); - root - } - - fn write(path: &Path, contents: &str) { - std::fs::create_dir_all(path.parent().expect("parent")).expect("dirs"); - std::fs::write(path, contents).expect("write"); - } - - #[test] - fn the_theme_beats_hicolor() { - let base = scratch("precedence"); - write( - &base.join("mytheme/scalable/actions/object-select-symbolic.svg"), - "", - ); - write( - &base.join("hicolor/scalable/actions/object-select-symbolic.svg"), - "", - ); - - assert_eq!( - lookup( - &["object-select-symbolic"], - "mytheme", - 16, - std::slice::from_ref(&base) - ), - Some(base.join("mytheme/scalable/actions/object-select-symbolic.svg")) - ); - std::fs::remove_dir_all(&base).expect("cleanup"); - } - - #[test] - fn a_missing_glyph_falls_through_to_hicolor() { - let base = scratch("hicolor"); - write(&base.join("hicolor/24/actions/search.svg"), ""); - - assert_eq!( - lookup(&["search"], "breeze", 24, std::slice::from_ref(&base)), - Some(base.join("hicolor/24/actions/search.svg")) - ); - std::fs::remove_dir_all(&base).expect("cleanup"); - } - - #[test] - fn the_inherits_chain_is_walked() { - let base = scratch("inherits"); - write(&base.join("parent/scalable/actions/add.svg"), ""); - write( - &base.join("child/index.theme"), - "[Icon Theme]\nInherits=parent\n", - ); - - assert_eq!( - lookup(&["add"], "child", 16, std::slice::from_ref(&base)), - Some(base.join("parent/scalable/actions/add.svg")) - ); - std::fs::remove_dir_all(&base).expect("cleanup"); - } - - #[test] - fn scalable_wins_and_the_closest_size_wins_without_it() { - let base = scratch("sizes"); - write(&base.join("theme/16x16/actions/check.svg"), ""); - write(&base.join("theme/48x48/actions/check.svg"), ""); - write(&base.join("theme/scalable/actions/check.svg"), ""); - - assert_eq!( - lookup(&["check"], "theme", 16, std::slice::from_ref(&base)), - Some(base.join("theme/scalable/actions/check.svg")) - ); - - let base = scratch("sizes-plain"); - write(&base.join("theme/16x16/actions/check.svg"), ""); - write(&base.join("theme/48x48/actions/check.svg"), ""); - - assert_eq!( - lookup(&["check"], "theme", 16, std::slice::from_ref(&base)), - Some(base.join("theme/16x16/actions/check.svg")) - ); - std::fs::remove_dir_all(&base).expect("cleanup"); - } - - #[test] - fn both_theme_layouts_are_searched() { - let adwaita = scratch("layout-adwaita"); - write(&adwaita.join("theme/scalable/actions/check.svg"), ""); - assert_eq!( - lookup(&["check"], "theme", 16, std::slice::from_ref(&adwaita)), - Some(adwaita.join("theme/scalable/actions/check.svg")) - ); - - let breeze = scratch("layout-breeze"); - write(&breeze.join("theme/actions/16/check.svg"), ""); - assert_eq!( - lookup(&["check"], "theme", 16, std::slice::from_ref(&breeze)), - Some(breeze.join("theme/actions/16/check.svg")) - ); - std::fs::remove_dir_all(&adwaita).expect("cleanup"); - std::fs::remove_dir_all(&breeze).expect("cleanup"); - } - - #[test] - fn png_only_themes_are_skipped() { - let base = scratch("png"); - write(&base.join("theme/16x16/actions/check.png"), "png"); - - assert_eq!( - lookup(&["check"], "theme", 16, std::slice::from_ref(&base)), - None - ); - std::fs::remove_dir_all(&base).expect("cleanup"); - } - - #[test] - fn a_themes_second_candidate_beats_hicolors_first() { - let base = scratch("candidates"); - write( - &base.join("mytheme/scalable/actions/emblem-ok-symbolic.svg"), - "", - ); - write( - &base.join("hicolor/scalable/actions/object-select-symbolic.svg"), - "", - ); - - assert_eq!( - lookup( - &["object-select-symbolic", "emblem-ok-symbolic"], - "mytheme", - 16, - std::slice::from_ref(&base) - ), - Some(base.join("mytheme/scalable/actions/emblem-ok-symbolic.svg")) - ); - std::fs::remove_dir_all(&base).expect("cleanup"); - } -} diff --git a/crates/ui/src/icons/mod.rs b/crates/ui/src/icons/mod.rs index 6b7e3fa..695ba68 100644 --- a/crates/ui/src/icons/mod.rs +++ b/crates/ui/src/icons/mod.rs @@ -865,31 +865,3 @@ impl AssetSource for Assets { .collect()) } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn every_role_has_a_unique_slug() { - for (index, role) in IconRole::all().iter().enumerate() { - for other in &IconRole::all()[index + 1..] { - assert_ne!( - role.slug(), - other.slug(), - "{role:?} and {other:?} share a slug" - ); - } - } - } - - #[test] - fn every_role_resolves_to_a_bundled_asset() { - for role in IconRole::all() { - assert!( - asset_bytes(role.asset_path()).is_some(), - "missing bundled asset for {role:?}" - ); - } - } -} diff --git a/crates/ui/src/icons/segoe.rs b/crates/ui/src/icons/segoe.rs index 02605ff..eb1b2f3 100644 --- a/crates/ui/src/icons/segoe.rs +++ b/crates/ui/src/icons/segoe.rs @@ -107,18 +107,3 @@ pub(crate) fn glyph(role: IconRole) -> Option<&'static str> { /// The system font the codepoints resolve against (Windows 11+). pub(crate) const FONT_FAMILY: &str = "Segoe Fluent Icons"; - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn every_role_maps_a_codepoint_or_falls_back_to_the_bundled_svg() { - for role in crate::icons::IconRole::all() { - assert!( - glyph(*role).is_some() || crate::icons::asset_bytes(role.asset_path()).is_some(), - "no Segoe codepoint or bundled asset for {role:?}" - ); - } - } -} diff --git a/crates/ui/src/layout/mod.rs b/crates/ui/src/layout/mod.rs index 5e2c377..e80c8f4 100644 --- a/crates/ui/src/layout/mod.rs +++ b/crates/ui/src/layout/mod.rs @@ -1,5 +1,11 @@ //! Application window layout: a titlebar over a panel row. +use crate::theme::{FOCUS_RING_ALPHA, FOCUS_RING_SPREAD}; +use gpui::{ + App, BoxShadow, Div, ElementId, FocusHandle, Hsla, Refineable as _, StyleRefinement, Styled, + Window, div, px, +}; + pub mod panel; pub mod resizable; pub mod resize_handle; @@ -8,3 +14,44 @@ pub mod titlebar; pub mod window_controls; mod window_frame; + +/// A row whose children center on the cross axis. +#[must_use] +pub fn h_flex() -> Div { + div().flex().flex_row().items_center() +} + +/// A column whose children stack on the main axis. +#[must_use] +pub fn v_flex() -> Div { + div().flex().flex_col() +} + +/// Extensions over [`Styled`], shared by the layout views. +pub trait StyledExt: Styled + Sized { + #[must_use] + fn refine_style(mut self, style: &StyleRefinement) -> Self { + self.style().refine(style); + self + } +} + +impl StyledExt for E {} + +/// Returns a focus handle for the given element ID. +pub fn focus_handle(id: &ElementId, window: &mut Window, cx: &mut App) -> FocusHandle { + window + .with_element_namespace(id.clone(), |window| { + window.use_keyed_state("focus-handle", cx, |_, cx| cx.focus_handle()) + }) + .read(cx) + .clone() +} + +/// Returns a focus ring shadow with the given color at half ink. +pub fn focus_ring(color: Hsla) -> Vec { + vec![ + BoxShadow::new(px(0.), px(0.), color.alpha(FOCUS_RING_ALPHA)) + .spread_radius(FOCUS_RING_SPREAD), + ] +} diff --git a/crates/ui/src/layout/panel.rs b/crates/ui/src/layout/panel.rs index 51d3fcb..142d535 100644 --- a/crates/ui/src/layout/panel.rs +++ b/crates/ui/src/layout/panel.rs @@ -5,14 +5,14 @@ use std::sync::Arc; +use crate::layout::StyledExt as _; +use crate::theme::ActiveTheme as _; use gpui::{ AnyElement, AnyView, App, Axis, Div, ElementId, Entity, IntoElement, ParentElement as _, Render, RenderOnce, SharedString, StyleRefinement, Styled as _, Window, div, }; use crate::layout::resizable::{Resizable, ResizableState}; -use crate::theme::ActiveTheme as _; -use crate::utils::StyledExt as _; /// A user-defined panel the row can show. #[allow(unused_variables)] diff --git a/crates/ui/src/layout/resizable.rs b/crates/ui/src/layout/resizable.rs index 983e33a..4acdefd 100644 --- a/crates/ui/src/layout/resizable.rs +++ b/crates/ui/src/layout/resizable.rs @@ -1,5 +1,7 @@ //! The resizable group: stacked panes with drag dividers, outside the dock. +use crate::layout::StyledExt as _; +use crate::theme::{PANE_DEFAULT_SIZE, PANE_MIN_SIZE}; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Axis, Bounds, Context, ElementId, Entity, @@ -8,8 +10,6 @@ use gpui::{ }; use crate::layout::resize_handle::ResizeHandle; -use crate::theme::{PANE_DEFAULT_SIZE, PANE_MIN_SIZE}; -use crate::utils::StyledExt as _; type DebugSelector = std::rc::Rc String>; diff --git a/crates/ui/src/layout/resize_handle.rs b/crates/ui/src/layout/resize_handle.rs index fdf7a29..1cbd917 100644 --- a/crates/ui/src/layout/resize_handle.rs +++ b/crates/ui/src/layout/resize_handle.rs @@ -3,6 +3,10 @@ use std::rc::Rc; +use crate::layout::{StyledExt as _, focus_handle, focus_ring}; +use crate::theme::{ + ActiveTheme as _, BORDER_WIDTH, DISABLED_OPACITY, HAIRLINE_WIDTH, RESIZE_KEYBOARD_STEP, +}; use gpui::prelude::FluentBuilder as _; use gpui::{ App, Axis, Bounds, CursorStyle, DispatchPhase, ElementId, HitboxBehavior, @@ -12,11 +16,6 @@ use gpui::{ deferred, div, fill, point, px, }; -use crate::theme::{ - ActiveTheme as _, BORDER_WIDTH, DISABLED_OPACITY, HAIRLINE_WIDTH, RESIZE_KEYBOARD_STEP, -}; -use crate::utils::{StyledExt as _, focus_handle, focus_ring}; - /// How far one keyboard arrow step moves the seam. const KEYBOARD_STEP: Pixels = RESIZE_KEYBOARD_STEP; diff --git a/crates/ui/src/layout/shell.rs b/crates/ui/src/layout/shell.rs index ffcc2a3..7d291b4 100644 --- a/crates/ui/src/layout/shell.rs +++ b/crates/ui/src/layout/shell.rs @@ -2,19 +2,19 @@ //! client-side window frame, with the toast and alert overlays mounted at //! the window root. +use crate::components::alert::{Alerts, AlertsView}; +use crate::components::grain::grain as grain_overlay; +use crate::components::toast::{Toasts, ToastsView}; +use crate::layout::{StyledExt as _, v_flex}; +use crate::theme::ActiveTheme as _; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, ElementId, Entity, IntoElement, ParentElement as _, RenderOnce, StyleRefinement, Styled as _, Window, div, }; -use crate::components::alert::{Alerts, AlertsView}; -use crate::components::grain::grain as grain_overlay; -use crate::components::toast::{Toasts, ToastsView}; use crate::layout::titlebar::Titlebar; use crate::layout::window_frame::frame; -use crate::theme::ActiveTheme as _; -use crate::utils::{StyledExt as _, v_flex}; /// The application shell. #[derive(IntoElement)] diff --git a/crates/ui/src/layout/titlebar.rs b/crates/ui/src/layout/titlebar.rs index f976a59..6029972 100644 --- a/crates/ui/src/layout/titlebar.rs +++ b/crates/ui/src/layout/titlebar.rs @@ -4,6 +4,8 @@ //! edge. The bar itself moves the window, tab bar included; the prefix and //! suffix opt out, so a press on a control never starts a drag. +use crate::layout::{StyledExt as _, h_flex}; +use crate::theme::{ActiveTheme as _, Size, TRAFFIC_LIGHT_PAD}; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce, @@ -11,8 +13,6 @@ use gpui::{ }; use crate::layout::window_controls::{WindowControls, titlebar_strip}; -use crate::theme::{ActiveTheme as _, Size, TRAFFIC_LIGHT_PAD}; -use crate::utils::{StyledExt as _, h_flex}; /// The window's titlebar. #[derive(IntoElement)] @@ -84,6 +84,7 @@ impl RenderOnce for Titlebar { let theme = cx.theme(); let height = theme.titlebar_height; let padding_x = theme.sizes.resolve(Size::default()).dense_padding_x; + let shadow_bleed = theme.elevations.control.bleed(); let id = self.id; let bar_id = SharedString::from(format!("{id}-bar")); @@ -118,6 +119,9 @@ impl RenderOnce for Titlebar { .min_w_0() .h_full() .overflow_hidden() + // Include the tabs' outer shadow in the clip without shifting content. + .px(shadow_bleed) + .mx(-shadow_bleed) .when(cfg!(target_os = "windows"), |slot| slot.occlude()) .child(tab_bar), ) diff --git a/crates/ui/src/layout/window_controls.rs b/crates/ui/src/layout/window_controls.rs index 137fd28..97303a4 100644 --- a/crates/ui/src/layout/window_controls.rs +++ b/crates/ui/src/layout/window_controls.rs @@ -4,25 +4,21 @@ //! never moves it; macOS draws its traffic lights in the shell's reserved pad //! and needs no controls of ours. -#[cfg(target_os = "linux")] -use gpui::Decorations; +use gpui::WindowControlArea; +use gpui::{App, ClickEvent, Div, ElementId, IntoElement, RenderOnce, Stateful, Window, div}; +use gpui::{InteractiveElement as _, MouseButton, StatefulInteractiveElement as _}; + #[cfg(any(target_os = "windows", target_os = "linux"))] -use gpui::SharedString; +use crate::icons::{IconRole, icon}; +#[cfg(any(target_os = "windows", target_os = "linux"))] +use crate::theme::ActiveTheme as _; #[cfg(any(target_os = "windows", target_os = "linux"))] use gpui::Styled as _; #[cfg(any(target_os = "windows", target_os = "linux"))] use gpui::prelude::FluentBuilder as _; #[cfg(any(target_os = "windows", target_os = "linux"))] use gpui::{AnyElement, ParentElement as _}; -use gpui::{ - App, ClickEvent, Div, ElementId, InteractiveElement as _, IntoElement, MouseButton, RenderOnce, - Stateful, StatefulInteractiveElement as _, Window, WindowControlArea, div, -}; -#[cfg(any(target_os = "windows", target_os = "linux"))] -use crate::icons::{IconRole, icon}; -#[cfg(any(target_os = "windows", target_os = "linux"))] -use crate::theme::ActiveTheme as _; /// macOS traffic-lights zone: the pad a leading titlebar strip reserves. pub use crate::theme::TRAFFIC_LIGHT_PAD; #[cfg(target_os = "windows")] @@ -30,6 +26,10 @@ use crate::theme::{ WINDOWS_CAPTION_WIDTH as CAPTION_WIDTH, WINDOWS_CLOSE_FOREGROUND, WINDOWS_CLOSE_HOVER, WINDOWS_CLOSE_PRESSED, }; +#[cfg(target_os = "linux")] +use gpui::Decorations; +#[cfg(any(target_os = "windows", target_os = "linux"))] +use gpui::SharedString; /// The window controls for the trailing end of a titlebar strip. #[derive(IntoElement)] diff --git a/crates/ui/src/layout/window_frame.rs b/crates/ui/src/layout/window_frame.rs index 97d988f..d21a88f 100644 --- a/crates/ui/src/layout/window_frame.rs +++ b/crates/ui/src/layout/window_frame.rs @@ -1,6 +1,7 @@ //! The client-side window frame: the border, corners, shadow, and resize //! edges of a window the system does not decorate. +use crate::theme::{ActiveTheme as _, BORDER_WIDTH, INACTIVE_SHADOW_OPACITY, WINDOW_RESIZE_INSET}; use gpui::prelude::FluentBuilder as _; use gpui::{ App, Bounds, BoxShadow, CursorStyle, Decorations, Div, HitboxBehavior, InteractiveElement as _, @@ -8,8 +9,6 @@ use gpui::{ Tiling, Window, canvas, div, point, px, size, }; -use crate::theme::{ActiveTheme as _, BORDER_WIDTH, INACTIVE_SHADOW_OPACITY, WINDOW_RESIZE_INSET}; - /// Wraps a window's root in the frame it owes. pub fn frame(child: E, window: &mut Window, cx: &App) -> Div where diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index ea6916f..86298fb 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -1,23 +1,21 @@ -//! Signed's native GPUI layer: theme, icons, components, layout, and editor. +//! Signed's native GPUI layer: theme, icons, components, and layout. pub mod components; -pub mod data; -pub mod editor; pub mod icons; pub mod layout; pub mod theme; -pub mod utils; pub use components::*; -use gpui::App; pub use icons::{Assets, Icon, IconRole}; +use gpui::App; + /// Initializes the theme and every key binding the UI layer owns. pub fn init(cx: &mut App) { theme::Theme::init(cx); components::input::bind_input_keys(cx, None); components::combobox::bind_combobox_keys(cx); components::command_palette::bind_command_palette_keys(cx); - editor::code::bind_code_view_keys(cx); - editor::markdown::bind_text_view_keys(cx); + components::code::bind_code_view_keys(cx); + components::markdown::bind_text_view_keys(cx); } diff --git a/crates/ui/src/theme/definition.rs b/crates/ui/src/theme/definition.rs index 2b1dbeb..509dd35 100644 --- a/crates/ui/src/theme/definition.rs +++ b/crates/ui/src/theme/definition.rs @@ -224,51 +224,3 @@ pub(crate) fn parse_hex(value: &str) -> Option { fn expand_rgb([r, g, b]: [f32; 3]) -> Hsla { Hsla::from(Rgba { r, g, b, a: 1.0 }) } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parses_six_and_three_digit_hex() { - let Rgba { r, g, b, a } = Rgba::from(parse_hex("#7aa2f7").unwrap()); - assert!((r - 0x7a as f32 / 255.0).abs() < 0.001); - assert!((g - 0xa2 as f32 / 255.0).abs() < 0.001); - assert!((b - 0xf7 as f32 / 255.0).abs() < 0.001); - assert_eq!(a, 1.0); - - // Compare in RGB space: Rgba -> Hsla -> Rgba is lossy at low saturation. - let short = Rgba::from(parse_hex("#f00").unwrap()); - assert!((short.r - 1.0).abs() < 0.001); - assert!(short.g.abs() < 0.001); - assert!(short.b.abs() < 0.001); - } - - #[test] - fn rejects_malformed_values() { - assert!(parse_hex("").is_none()); - assert!(parse_hex("#12").is_none()); - assert!(parse_hex("#12345").is_none()); - assert!(parse_hex("#zzzzzz").is_none()); - assert!(parse_hex("7aa2f7").is_none()); - } - - #[test] - fn parses_a_full_definition() { - let def = ThemeDefinition::parse_toml( - "mode = \"dark\"\naccent = \"#7aa2f7\"\nbackground = \"#1a1b26\"\ninfo = \"#38bdf8\"\noverlay_radius = 15.0\nsm_radius = 6.0\n", - ) - .unwrap(); - assert_eq!(def.mode(), Some(crate::theme::ThemeVariant::Dark)); - assert!(def.accent().is_some()); - assert!(def.info().is_some()); - assert!(def.foreground().is_none()); - assert_eq!(def.overlay_radius(), Some(15.0)); - assert_eq!(def.sm_radius(), Some(6.0)); - } - - #[test] - fn an_invalid_mode_fails_the_parse_instead_of_being_ignored() { - assert!(ThemeDefinition::parse_toml("mode = \"blue\"\n").is_err()); - } -} diff --git a/crates/ui/src/theme/mod.rs b/crates/ui/src/theme/mod.rs index 1a28d29..63eb0f5 100644 --- a/crates/ui/src/theme/mod.rs +++ b/crates/ui/src/theme/mod.rs @@ -15,22 +15,26 @@ mod source; mod system; mod typography; -use std::time::Duration; - pub use colors::{ColorTokens, MaterialTokens}; pub use definition::ThemeDefinition; -use gpui::{ - App, Global, Hsla, Pixels, SpringConfig, WindowAppearance, WindowBackgroundAppearance, hsla, px, -}; pub use ramps::{AccentShades, Oklch}; pub use resolve::{Ramps, ResolvedTheme}; pub use system::{AccessibilityPreferences, SourceKind, SystemTheme}; pub use typography::{TextRole, TypeMetrics, Typeset, Typography}; +use gpui::{ + App, Global, Hsla, Pixels, SpringConfig, WindowAppearance, WindowBackgroundAppearance, hsla, px, +}; +use std::time::Duration; + /// The hairline width of the control border every button and field paints. pub const BORDER_WIDTH: Pixels = px(1.0); /// The underline and drop indicators a tab strip paints. pub const TAB_INDICATOR_WIDTH: Pixels = px(2.0); +/// The widest a titlebar tab grows before its label fades. +pub const TAB_MAX_WIDTH: Pixels = px(240.0); +/// The narrowest a titlebar tab shrinks, keeping short labels clear of the fade. +pub const TAB_MIN_WIDTH: Pixels = px(140.0); /// Opacity applied to disabled controls. pub const DISABLED_OPACITY: f32 = 0.5; /// The focus ring's ink alpha. @@ -764,27 +768,3 @@ pub fn detected_source(cx: &App) -> &'static str { let engine = cx.global::(); engine.source.label() } - -#[cfg(test)] -mod tests { - use gpui::Rgba; - - use super::*; - - #[test] - fn the_windows_close_colors_match_the_legacy_hex() { - let hover = Hsla::from(gpui::rgba(0xE81123FF)); - let pressed = hover.opacity(0.8); - for (token, expected) in [ - (WINDOWS_CLOSE_HOVER, hover), - (WINDOWS_CLOSE_PRESSED, pressed), - ] { - let (token, expected) = (Rgba::from(token), Rgba::from(expected)); - assert!((token.r - expected.r).abs() < 1e-4); - assert!((token.g - expected.g).abs() < 1e-4); - assert!((token.b - expected.b).abs() < 1e-4); - assert!((token.a - expected.a).abs() < 1e-4); - } - assert_eq!(WINDOWS_CLOSE_FOREGROUND, gpui::white()); - } -} diff --git a/crates/ui/src/theme/presets.rs b/crates/ui/src/theme/presets.rs index 3411844..1a011cc 100644 --- a/crates/ui/src/theme/presets.rs +++ b/crates/ui/src/theme/presets.rs @@ -25,16 +25,3 @@ pub fn builtin(name: &str) -> Option<(&'static str, ThemeDefinition)> { } } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_name_table_and_lookup_agree() { - for name in preset_names() { - assert!(builtin(name).is_some(), "{name} fails to parse"); - } - assert!(builtin("no-such-preset").is_none()); - } -} diff --git a/crates/ui/src/theme/ramps.rs b/crates/ui/src/theme/ramps.rs index 920e2b5..3db2938 100644 --- a/crates/ui/src/theme/ramps.rs +++ b/crates/ui/src/theme/ramps.rs @@ -178,98 +178,3 @@ pub fn derive_shades(accent: Hsla, background: Hsla, is_dark: bool) -> AccentSha foreground: contrast_foreground(accent), } } - -#[cfg(test)] -mod tests { - use gpui::rgb; - - use super::*; - - fn hsla(hex: u32) -> Hsla { - Hsla::from(rgb(hex)) - } - - #[test] - fn white_and_black_have_extreme_lightness_and_no_chroma() { - let white = Oklch::from_hsla(hsla(0xffffff)); - assert!((white.l - 1.0).abs() < 0.001, "white L = {}", white.l); - assert!(white.c < 0.001, "white C = {}", white.c); - - let black = Oklch::from_hsla(hsla(0x000000)); - assert!(black.l.abs() < 0.001, "black L = {}", black.l); - } - - #[test] - fn oklch_round_trips_within_one_step_of_eight_bit_color() { - for hex in [0x2563eb, 0xdc2626, 0x7aa2f7, 0x1a1b26, 0xf7768e] { - let ok = Oklch::from_hsla(hsla(hex)); - let Rgba { r, g, b, .. } = Rgba::from(ok.to_hsla()); - let (er, eg, eb) = { - let expected = Rgba::from(hsla(hex)); - (expected.r, expected.g, expected.b) - }; - assert!((r - er).abs() < 1.0 / 255.0, "{hex:06x} r {r} vs {er}"); - assert!((g - eg).abs() < 1.0 / 255.0, "{hex:06x} g {g} vs {eg}"); - assert!((b - eb).abs() < 1.0 / 255.0, "{hex:06x} b {b} vs {eb}"); - } - } - - #[test] - fn shades_move_toward_the_background_in_light_mode() { - let accent = hsla(0x2563eb); - let background = hsla(0xffffff); - let shades = derive_shades(accent, background, false); - let hover_l = Oklch::from_hsla(shades.hover).l; - let base_l = Oklch::from_hsla(accent).l; - assert!( - hover_l < base_l, - "light-mode hover darkens: {hover_l} vs {base_l}" - ); - - let dark_shades = derive_shades(accent, hsla(0x09090b), true); - let dark_hover_l = Oklch::from_hsla(dark_shades.hover).l; - assert!(dark_hover_l > base_l, "dark-mode hover lightens"); - } - - #[test] - fn subtle_stays_between_accent_and_background() { - let accent = Oklch::from_hsla(hsla(0x2563eb)); - let background = Oklch::from_hsla(hsla(0xffffff)); - let subtle = Oklch::from_hsla(derive_shades(hsla(0x2563eb), hsla(0xffffff), false).subtle); - assert!(subtle.l > accent.l && subtle.l < background.l); - } - - #[test] - fn contrast_foreground_follows_native_fill_conventions() { - // Dark fills get white. - assert_eq!(contrast_foreground(hsla(0x101010)), hsla(0xffffff)); - // macOS blue accent keeps white, like AppKit, even though black has - // the higher raw WCAG ratio. - assert_eq!(contrast_foreground(hsla(0x007aff)), hsla(0xffffff)); - // Light fills — white fails the 3:1 bar and black wins. - assert_eq!(contrast_foreground(hsla(0xefefef)), hsla(0x000000)); - assert_eq!(contrast_foreground(hsla(0xffd60a)), hsla(0x000000)); - } - - #[test] - fn mix_takes_the_shortest_arc_around_the_hue_wheel() { - let a = Oklch { - l: 0.5, - c: 0.1, - h: 350.0, - a: 1.0, - }; - let b = Oklch { - l: 0.5, - c: 0.1, - h: 10.0, - a: 1.0, - }; - let mid = mix(a, b, 0.5); - assert!( - mid.h < 10.0 || mid.h > 350.0, - "mid hue should cross 0/360, got {}", - mid.h - ); - } -} diff --git a/crates/ui/src/theme/resolve.rs b/crates/ui/src/theme/resolve.rs index c73e821..4407668 100644 --- a/crates/ui/src/theme/resolve.rs +++ b/crates/ui/src/theme/resolve.rs @@ -1,5 +1,3 @@ -use gpui::{WindowBackgroundAppearance, px}; - use crate::theme::definition::ThemeDefinition; use crate::theme::ramps::{AccentShades, Oklch, contrast_foreground, derive_shades, mix}; use crate::theme::system::{SourceKind, SystemTheme}; @@ -7,6 +5,7 @@ use crate::theme::{ ColorTokens, CustomTheme, Elevations, MaterialTokens, Motion, Radius, Scrollbar, SizeTable, Spacing, ThemeVariant, Typography, }; +use gpui::{WindowBackgroundAppearance, px}; /// Derived state shades for the colors that get pressed and hovered. #[derive(Clone, Copy, Debug, PartialEq)] @@ -243,564 +242,3 @@ fn mono_font() -> &'static str { "monospace" } } - -#[cfg(test)] -mod tests { - use gpui::{Rgba, WindowBackgroundAppearance, rgb}; - - use super::*; - use crate::theme::system::{AccessibilityPreferences, SourceKind}; - use crate::theme::{Elevation, Shadow}; - - fn hsla(hex: u32) -> gpui::Hsla { - gpui::Hsla::from(rgb(hex)) - } - - fn system(variant: ThemeVariant, accent: Option) -> SystemTheme { - SystemTheme { - variant, - accent, - accessibility: AccessibilityPreferences::default(), - window_background: None, - source: SourceKind::Macos, - } - } - - #[test] - fn empty_system_resolves_to_the_neutral_fallback() { - for variant in [ThemeVariant::Light, ThemeVariant::Dark] { - let resolved = resolve( - &SystemTheme { - source: SourceKind::Fallback, - ..system(variant, None) - }, - None, - None, - None, - ); - let base = match variant { - ThemeVariant::Light => ColorTokens::light(), - ThemeVariant::Dark => ColorTokens::dark(), - }; - assert_eq!(resolved.colors.background, base.background); - assert_eq!(resolved.colors.accent, base.accent); - assert_eq!(resolved.colors.ring, base.accent); - assert_eq!(resolved.ramps.primary.base, base.primary); - assert_eq!(resolved.ramps.secondary.base, base.secondary); - assert_eq!(resolved.colors.selection, resolved.ramps.primary.subtle); - assert_eq!(resolved.radius.sm, px(4.)); - assert_eq!(resolved.radius.control, px(6.)); - assert_eq!(resolved.radius.overlay, px(10.)); - assert_eq!(resolved.root_font_size, px(16.)); - assert_eq!(resolved.sizes.medium.control_height, px(32.)); - assert_eq!(resolved.sizes.medium.input_height, px(32.)); - assert_eq!(resolved.sizes.medium.text_size, px(14.)); - assert_eq!(resolved.sizes.xsmall.control_height, px(20.)); - assert_eq!(resolved.sizes.xsmall.input_height, px(20.)); - assert_eq!(resolved.sizes.xsmall.text_size, px(11.)); - assert_eq!(resolved.sizes.xsmall.icon_size, px(10.)); - assert_eq!(resolved.sizes.xsmall.indicator_size, px(10.)); - assert_eq!(resolved.sizes.xsmall.avatar_size, px(18.)); - assert_eq!(resolved.sizes.xsmall.caption_size, px(10.)); - assert_eq!(resolved.sizes.xsmall.dense_padding_x, px(4.)); - assert_eq!(resolved.sizes.xsmall.plate_inset, px(0.)); - assert_eq!(resolved.sizes.xsmall.menu_item_height, px(20.)); - assert_eq!(resolved.sizes.xsmall.switch_height, px(14.)); - assert_eq!(resolved.sizes.xsmall.switch_width, px(24.)); - assert_eq!(resolved.sizes.xsmall.switch_knob, px(8.)); - assert_eq!(resolved.sizes.small.control_height, px(28.)); - assert_eq!(resolved.sizes.small.text_size, px(12.)); - assert_eq!(resolved.sizes.small.avatar_size, px(24.)); - assert_eq!(resolved.sizes.medium.avatar_size, px(32.)); - assert_eq!(resolved.sizes.large.avatar_size, px(40.)); - assert_eq!(resolved.sizes.small.caption_size, px(12.)); - assert_eq!(resolved.sizes.medium.caption_size, px(12.)); - assert_eq!(resolved.sizes.large.caption_size, px(14.)); - assert_eq!(resolved.sizes.medium.dense_padding_x, px(8.)); - assert_eq!(resolved.sizes.medium.plate_inset, px(2.)); - assert_eq!(resolved.sizes.medium.strip_height, px(32.)); - assert_eq!(resolved.sizes.medium.icon_size, px(16.)); - assert_eq!(resolved.sizes.medium.indicator_size, px(16.)); - assert_eq!(resolved.sizes.medium.menu_item_height, px(32.)); - assert_eq!(resolved.sizes.large.control_height, px(40.)); - assert_eq!(resolved.sizes.large.text_size, px(16.)); - assert_eq!(resolved.sizes.medium.switch_height, px(20.)); - assert_eq!(resolved.sizes.medium.switch_width, px(36.)); - assert_eq!(resolved.sizes.medium.switch_knob, px(14.)); - assert_eq!(resolved.spacing.unit, px(4.)); - assert_eq!(resolved.titlebar_height, px(40.)); - assert_eq!(resolved.typography.body.size, px(16.)); - } - } - - #[test] - fn scrollbar_autohide_follows_the_platform_source() { - let mut stated = system(ThemeVariant::Dark, None); - stated.source = SourceKind::Macos; - assert!(resolve(&stated, None, None, None).scrollbar.autohide); - - stated.source = SourceKind::Gnome; - assert!(resolve(&stated, None, None, None).scrollbar.autohide); - - stated.source = SourceKind::Omarchy; - assert!(resolve(&stated, None, None, None).scrollbar.autohide); - - stated.source = SourceKind::Windows; - assert!(!resolve(&stated, None, None, None).scrollbar.autohide); - - stated.source = SourceKind::Kde; - assert!(!resolve(&stated, None, None, None).scrollbar.autohide); - - stated.source = SourceKind::Fallback; - assert!(!resolve(&stated, None, None, None).scrollbar.autohide); - } - - #[test] - fn accent_drives_primary_ring_and_selection() { - let red = hsla(0xdc2626); - let resolved = resolve(&system(ThemeVariant::Light, Some(red)), None, None, None); - assert_eq!(resolved.colors.accent, red); - assert_eq!(resolved.colors.primary, red); - assert_eq!(resolved.colors.ring, red); - assert_eq!(resolved.ramps.primary.base, red); - assert_eq!(resolved.colors.selection, resolved.ramps.primary.subtle); - - let base = ColorTokens::light(); - assert_eq!(resolved.colors.background, base.background); - assert_eq!(resolved.colors.foreground, base.foreground); - assert_eq!(resolved.colors.border, base.border); - } - - #[test] - fn every_source_resolves_the_same_tokens() { - let mut stated = system(ThemeVariant::Dark, None); - stated.accent = Some(hsla(0x7aa2f7)); - stated.window_background = Some(WindowBackgroundAppearance::Blurred); - let sources = [ - SourceKind::Fallback, - SourceKind::Macos, - SourceKind::Windows, - SourceKind::Gnome, - SourceKind::Kde, - SourceKind::Omarchy, - ]; - - let first = resolve( - &SystemTheme { - source: sources[0], - ..stated - }, - None, - None, - None, - ); - for source in &sources[1..] { - let next = resolve( - &SystemTheme { - source: *source, - ..stated - }, - None, - None, - None, - ); - assert_eq!(next.colors, first.colors, "{source:?}"); - assert_eq!(next.radius, first.radius, "{source:?}"); - assert_eq!(next.spacing, first.spacing, "{source:?}"); - assert_eq!(next.elevations, first.elevations, "{source:?}"); - assert_eq!(next.titlebar_height, first.titlebar_height, "{source:?}"); - assert_eq!(next.root_font_size, first.root_font_size, "{source:?}"); - assert_eq!(next.typography, first.typography, "{source:?}"); - assert_eq!(next.sizes, first.sizes, "{source:?}"); - } - } - - #[test] - fn the_radius_ladder_follows_custom_values_with_preset_priority() { - let resolved = resolve(&system(ThemeVariant::Light, None), None, None, None); - assert_eq!(resolved.radius.sm, px(4.)); - assert_eq!(resolved.radius.control, px(6.)); - assert_eq!(resolved.radius.overlay, px(10.)); - - let def = ThemeDefinition::parse_toml("overlay_radius = 12.0\n").unwrap(); - let overridden = resolve(&system(ThemeVariant::Light, None), Some(&def), None, None); - assert_eq!(overridden.radius.overlay, px(12.)); - assert_eq!(overridden.radius.sm, px(4.)); - - let custom = CustomTheme { - sm_radius: Some(px(2.)), - control_radius: Some(px(9.)), - ..CustomTheme::default() - }; - let custom = resolve( - &system(ThemeVariant::Light, None), - Some(&def), - None, - Some(custom), - ); - assert_eq!(custom.radius.sm, px(2.)); - assert_eq!(custom.radius.control, px(9.)); - assert_eq!(custom.radius.overlay, px(12.)); - } - - #[test] - fn elevations_follow_the_variant() { - let light = resolve(&system(ThemeVariant::Light, None), None, None, None); - assert_eq!(light.elevations.popover.shadows().len(), 2); - assert_eq!(light.elevations.dialog.shadows().len(), 2); - assert_eq!(light.elevations.control.shadows().len(), 1); - - let dark = resolve(&system(ThemeVariant::Dark, None), None, None, None); - assert!(dark.elevations.popover.shadows().is_empty()); - assert!(dark.elevations.dialog.shadows().is_empty()); - assert_eq!(dark.elevations.control.shadows().len(), 1); - } - - #[test] - fn the_platforms_window_material_resolves_into_the_theme() { - let mut stated = system(ThemeVariant::Light, None); - stated.window_background = Some(WindowBackgroundAppearance::MicaBackdrop); - let resolved = resolve(&stated, None, None, None); - - assert_eq!( - resolved.window_background, - WindowBackgroundAppearance::MicaBackdrop - ); - // Material surfaces stay translucent over the stated backdrop. - assert!(resolved.material.background.a < resolved.colors.background.a); - assert!(resolved.material.selection.a < 1.0); - - let unstated = resolve(&system(ThemeVariant::Light, None), None, None, None); - assert_eq!( - unstated.window_background, - WindowBackgroundAppearance::Opaque - ); - assert_eq!(unstated.material.background, unstated.colors.background); - assert_eq!(unstated.material.hover, unstated.colors.muted); - assert_eq!(unstated.material.selection, unstated.ramps.primary.base); - } - - #[test] - fn reduced_transparency_forces_an_opaque_window_and_material() { - let mut stated = system(ThemeVariant::Dark, None); - stated.window_background = Some(WindowBackgroundAppearance::Blurred); - stated.accessibility.reduce_transparency = true; - let resolved = resolve(&stated, None, None, None); - - assert_eq!( - resolved.window_background, - WindowBackgroundAppearance::Opaque - ); - assert_eq!(resolved.material.background, resolved.colors.background); - assert_eq!(resolved.material.hover, resolved.colors.muted); - assert_eq!(resolved.material.selection, resolved.ramps.primary.base); - } - - #[test] - fn a_custom_transparency_level_scales_the_material_fill() { - let mut stated = system(ThemeVariant::Dark, None); - stated.window_background = Some(WindowBackgroundAppearance::Blurred); - let custom = CustomTheme { - transparency: Some(80), - ..CustomTheme::default() - }; - let resolved = resolve(&stated, None, None, Some(custom)); - - assert_eq!( - resolved.window_background, - WindowBackgroundAppearance::Blurred - ); - assert!((resolved.material.background.a - 0.32).abs() < 1e-6); - - // Levels past 100 clamp, bottoming out at the dark floor. - let clamped = resolve( - &stated, - None, - None, - Some(CustomTheme { - transparency: Some(150), - ..CustomTheme::default() - }), - ); - assert!((clamped.material.background.a - 0.15).abs() < 1e-6); - } - - #[test] - fn light_mode_keeps_a_heavier_fill_at_full_transparency() { - let mut light_system = system(ThemeVariant::Light, None); - light_system.window_background = Some(WindowBackgroundAppearance::Blurred); - let mut dark_system = system(ThemeVariant::Dark, None); - dark_system.window_background = Some(WindowBackgroundAppearance::Blurred); - let maxed = CustomTheme { - transparency: Some(100), - ..CustomTheme::default() - }; - let light = resolve(&light_system, None, None, Some(maxed)); - let dark = resolve(&dark_system, None, None, Some(maxed)); - - assert!((light.material.background.a - 0.45).abs() < 1e-6); - assert!((dark.material.background.a - 0.15).abs() < 1e-6); - } - - #[test] - fn transparency_zero_opens_an_opaque_window() { - let mut stated = system(ThemeVariant::Dark, None); - stated.window_background = Some(WindowBackgroundAppearance::Blurred); - let resolved = resolve( - &stated, - None, - None, - Some(CustomTheme { - transparency: Some(0), - ..CustomTheme::default() - }), - ); - - assert_eq!( - resolved.window_background, - WindowBackgroundAppearance::Opaque - ); - assert_eq!(resolved.material.background, resolved.colors.background); - assert_eq!(resolved.material.hover, resolved.colors.muted); - assert_eq!(resolved.material.selection, resolved.ramps.primary.base); - } - - #[test] - fn the_transparency_knob_skips_windows_and_platforms_without_a_material() { - let mut windows = system(ThemeVariant::Dark, None); - windows.source = SourceKind::Windows; - windows.window_background = Some(WindowBackgroundAppearance::MicaBackdrop); - let resolved_windows = resolve( - &windows, - None, - None, - Some(CustomTheme { - transparency: Some(100), - ..CustomTheme::default() - }), - ); - - assert_eq!( - resolved_windows.window_background, - WindowBackgroundAppearance::MicaBackdrop - ); - // The knob's value is ignored on Windows; the default drives the fill. - let unset = resolve(&windows, None, None, None); - assert_eq!( - resolved_windows.material.background, - unset.material.background - ); - - let mut unstated = system(ThemeVariant::Dark, None); - unstated.window_background = None; - let resolved_unstated = resolve( - &unstated, - None, - None, - Some(CustomTheme { - transparency: Some(100), - ..CustomTheme::default() - }), - ); - - assert_eq!( - resolved_unstated.window_background, - WindowBackgroundAppearance::Opaque - ); - assert_eq!( - resolved_unstated.material.background, - resolved_unstated.colors.background - ); - } - - #[test] - fn overlay_is_translucent_and_overridable() { - let light = resolve(&system(ThemeVariant::Light, None), None, None, None); - let dark = resolve(&system(ThemeVariant::Dark, None), None, None, None); - - // Both scrims are translucent black; dark is denser for contrast. - assert!(light.colors.overlay.a > 0.0 && light.colors.overlay.a < 0.5); - assert!(dark.colors.overlay.a > light.colors.overlay.a); - - let def = ThemeDefinition::parse_toml("overlay = \"#000000\"").unwrap(); - let overridden = resolve(&system(ThemeVariant::Light, None), Some(&def), None, None); - assert_eq!(overridden.colors.overlay, hsla(0x000000)); - assert_eq!(overridden.colors.overlay.a, 1.0); - } - - #[test] - fn elevations_and_motion_resolve_with_defaults() { - let resolved = resolve(&system(ThemeVariant::Light, None), None, None, None); - - // The popover shadow is softer and tighter than the dialog's. - assert!( - resolved.elevations.popover.layers[0].blur_radius - < resolved.elevations.dialog.layers[0].blur_radius - ); - assert!(resolved.motion.overlay > std::time::Duration::ZERO); - let shadows = resolved.elevations.popover.shadows(); - assert_eq!(shadows.len(), 2); - assert!(!shadows[0].inset); - } - - #[test] - fn preset_beats_system_and_the_mode_override_beats_everything() { - let def = ThemeDefinition::parse_toml( - "mode = \"dark\"\nbackground = \"#1a1b26\"\naccent = \"#7aa2f7\"\ncontrol_radius = 12.0\n", - ) - .unwrap(); - let resolved = resolve(&system(ThemeVariant::Light, None), Some(&def), None, None); - assert_eq!(resolved.variant, ThemeVariant::Dark); - // Compare in RGB space: Hsla round-trips are lossy at low saturation. - let bg = Rgba::from(resolved.colors.background); - assert!((bg.r - 0x1a as f32 / 255.0).abs() < 0.001); - assert!((bg.b - 0x26 as f32 / 255.0).abs() < 0.001); - let accent = Rgba::from(resolved.colors.accent); - assert!((accent.r - 0x7a as f32 / 255.0).abs() < 0.001); - // And the metric override beats the radius default. - assert_eq!(resolved.radius.control, px(12.)); - - let forced = resolve( - &system(ThemeVariant::Light, None), - Some(&def), - Some(ThemeVariant::Light), - None, - ); - assert_eq!(forced.variant, ThemeVariant::Light); - // The override flips the variant (and with it the base roles), but - // the preset's explicit background still wins over the base. - let forced_bg = Rgba::from(forced.colors.background); - assert!((forced_bg.r - 0x1a as f32 / 255.0).abs() < 0.001); - } - - #[test] - fn an_accent_only_override_derives_foregrounds_and_ramps() { - let def = ThemeDefinition::parse_toml("mode = \"dark\"\naccent = \"#7aa2f7\"\n").unwrap(); - let resolved = resolve(&system(ThemeVariant::Dark, None), Some(&def), None, None); - // The definition sets accent only; primary follows it, and both - // foregrounds derive from their own color. - let accent = Rgba::from(resolved.colors.accent); - assert!((accent.r - 0x7a as f32 / 255.0).abs() < 0.001); - assert_eq!(resolved.colors.primary, resolved.colors.accent); - assert_eq!(resolved.colors.ring, resolved.colors.accent); - assert_eq!(resolved.colors.selection, resolved.ramps.primary.subtle); - assert_eq!(resolved.ramps.primary.base, resolved.colors.primary); - assert_eq!(resolved.ramps.destructive.base, resolved.colors.destructive); - assert_ne!(resolved.ramps.primary.hover, resolved.ramps.primary.base); - assert_ne!(resolved.ramps.primary.subtle, resolved.ramps.primary.base); - } - - #[test] - fn system_accent_becomes_primary() { - let resolved = resolve( - &system(ThemeVariant::Dark, Some(hsla(0x7aa2f7))), - None, - None, - None, - ); - let primary = Rgba::from(resolved.colors.primary); - assert!((primary.r - 0x7a as f32 / 255.0).abs() < 0.001); - assert_eq!(resolved.ramps.primary.base, resolved.colors.primary); - assert_eq!( - resolved.colors.primary_foreground, - resolved.colors.accent_foreground - ); - } - - #[test] - fn high_contrast_sharpens_the_border_toward_the_foreground() { - let mut a11y = AccessibilityPreferences::default(); - let plain = resolve(&system(ThemeVariant::Dark, None), None, None, None); - a11y.high_contrast = true; - let contrasted = resolve( - &SystemTheme { - accessibility: a11y, - ..system(ThemeVariant::Dark, None) - }, - None, - None, - None, - ); - let plain_border = Oklch::from_hsla(plain.colors.border); - let contrasted_border = Oklch::from_hsla(contrasted.colors.border); - let foreground_l = Oklch::from_hsla(plain.colors.foreground).l; - assert!((contrasted_border.l - foreground_l).abs() < (plain_border.l - foreground_l).abs()); - } - - #[test] - fn every_resolved_role_is_distinct_enough_to_paint_with() { - for variant in [ThemeVariant::Light, ThemeVariant::Dark] { - let resolved = resolve(&system(variant, None), None, None, None); - assert_ne!(resolved.colors.background, resolved.colors.foreground); - assert_ne!(resolved.colors.border, resolved.colors.background); - assert_ne!(resolved.colors.muted_foreground, resolved.colors.foreground); - assert!(resolved.colors.ring != resolved.colors.background); - } - } - - #[test] - fn info_stays_calm_when_the_accent_warms_up() { - // The whole point of the info role: a warm platform accent (GNOME - // red, Omarchy red themes) must not make Info toasts read as Danger. - let red_accent = hsla(0xdc2626); - let resolved = resolve( - &system(ThemeVariant::Dark, Some(red_accent)), - None, - None, - None, - ); - assert_eq!(resolved.ramps.primary.base, red_accent); - assert_ne!(resolved.colors.info, resolved.colors.destructive); - assert_ne!(resolved.ramps.info.base, resolved.ramps.destructive.base); - } - - #[test] - fn info_follows_the_preset() { - let def = ThemeDefinition::parse_toml("info = \"#0ea5e9\"\n").unwrap(); - let resolved = resolve(&system(ThemeVariant::Dark, None), Some(&def), None, None); - assert_eq!(resolved.colors.info, hsla(0x0ea5e9)); - assert_eq!(resolved.ramps.info.base, hsla(0x0ea5e9)); - } - - #[test] - fn a_custom_theme_beats_the_preset_and_defaults() { - let def = ThemeDefinition::parse_toml("overlay_radius = 12.0\n").unwrap(); - let popover = Elevation::single(Shadow::black(0., 2., 8., 0.3)); - let custom = CustomTheme { - sm_radius: Some(px(2.)), - control_radius: Some(px(4.)), - popover_elevation: Some(popover), - ..CustomTheme::default() - }; - let resolved = resolve( - &system(ThemeVariant::Light, None), - Some(&def), - None, - Some(custom), - ); - assert_eq!(resolved.radius.control, px(4.)); - assert_eq!(resolved.radius.sm, px(2.)); - // Fields the custom theme leaves unstated keep the resolved values. - assert_eq!(resolved.radius.overlay, px(12.)); - assert_eq!(resolved.elevations.popover, popover); - let defaults = Elevations::for_variant(ThemeVariant::Light); - assert_eq!(resolved.elevations.dialog, defaults.dialog); - assert_eq!(resolved.elevations.control, defaults.control); - } - - #[test] - fn a_custom_root_font_size_rescales_the_table() { - let custom = CustomTheme { - root_font_size: Some(px(20.)), - ..CustomTheme::default() - }; - let resolved = resolve(&system(ThemeVariant::Light, None), None, None, Some(custom)); - assert_eq!(resolved.root_font_size, px(20.)); - assert_eq!(resolved.sizes.medium.control_height, px(40.)); - assert_eq!(resolved.sizes.medium.text_size, px(17.5)); - assert_eq!(resolved.spacing.unit, px(5.)); - assert_eq!(resolved.titlebar_height, px(50.)); - assert_eq!(resolved.typography.body.size, px(20.)); - assert_eq!(resolved.typography.large_title.size, px(30.)); - } -} diff --git a/crates/ui/src/theme/source/kde.rs b/crates/ui/src/theme/source/kde.rs index 448d19d..b7185f9 100644 --- a/crates/ui/src/theme/source/kde.rs +++ b/crates/ui/src/theme/source/kde.rs @@ -125,131 +125,3 @@ pub(crate) mod io { Some(KdeScheme::parse(&text)) } } - -#[cfg(test)] -mod tests { - use super::*; - - const BREEZE_DARK: &str = "\ -[Colors:Button] -BackgroundAlternate=30,87,116 -BackgroundNormal=41,44,48 -DecorationFocus=61,174,233 -DecorationHover=61,174,233 -ForegroundInactive=161,169,177 -ForegroundNegative=218,68,83 -ForegroundNormal=252,252,252 -ForegroundPositive=39,174,96 - -[Colors:Selection] -BackgroundNormal=61,174,233 -DecorationFocus=61,174,233 -ForegroundNormal=252,252,252 - -[Colors:View] -BackgroundNormal=20,22,24 -BackgroundAlternate=29,31,34 -DecorationFocus=61,174,233 -DecorationHover=61,174,233 -ForegroundInactive=161,169,177 -ForegroundNormal=252,252,252 - -[Colors:Window] -BackgroundNormal=32,35,38 -DecorationFocus=61,174,233 -DecorationHover=61,174,233 -DecorationNormal=49,54,59 -ForegroundInactive=161,169,177 -ForegroundNegative=218,68,83 -ForegroundNormal=252,252,252 -ForegroundPositive=39,174,96 - -[General] -ColorScheme=BreezeDark -Name[de]=Breeze Dunkel - -[KDE] -contrast=4 - -[WM] -activeBackground=39,44,49 -"; - - #[test] - fn breeze_states_the_window_background() { - let scheme = KdeScheme::parse(BREEZE_DARK); - let scale = |component: u32| component as f32 / 255.0; - let background = scheme.background.expect("window background"); - - assert_eq!( - gpui::Rgba::from(background), - gpui::Rgba { - r: scale(32), - g: scale(35), - b: scale(38), - a: 1.0, - } - ); - } - - #[test] - fn localized_and_unrelated_keys_are_ignored() { - let scheme = KdeScheme::parse(BREEZE_DARK); - assert!(scheme.accent.is_none()); - } - - #[test] - fn a_stated_accent_reaches_the_system_theme() { - let text = - "[General]\nAccentColor=255,100,50\n[Colors:Window]\nBackgroundNormal=32,35,38\n"; - let scheme = KdeScheme::parse(text); - let system = scheme.into_system(Default::default(), None, None); - - let accent = system.accent.expect("stated accent"); - assert_eq!( - accent, - Hsla::from(gpui::Rgba { - r: 255.0 / 255.0, - g: 100.0 / 255.0, - b: 50.0 / 255.0, - a: 1.0, - }) - ); - assert_eq!(system.source, SourceKind::Kde); - assert_eq!(system.variant, crate::theme::ThemeVariant::Dark); - } - - #[test] - fn the_portal_accent_covers_the_unset_marker() { - let text = - "[General]\nAccentColor=-1,-1,-1\n[Colors:Window]\nBackgroundNormal=250,250,250\n"; - let scheme = KdeScheme::parse(text); - assert!(scheme.accent.is_none()); - - let portal_accent = Some(Hsla::from(gpui::rgb(0x3584e4))); - let system = scheme.into_system(Default::default(), portal_accent, None); - assert_eq!(system.accent, portal_accent); - assert_eq!(system.variant, crate::theme::ThemeVariant::Light); - } - - #[test] - fn the_portal_mode_beats_the_lightness_derivation() { - let text = "[Colors:Window]\nBackgroundNormal=32,35,38\n"; - let scheme = KdeScheme::parse(text); - let system = scheme.into_system( - Default::default(), - None, - Some(crate::theme::ThemeVariant::Light), - ); - assert_eq!(system.variant, crate::theme::ThemeVariant::Light); - } - - #[test] - fn color_components_outside_0_to_255_are_rejected() { - let above = KdeScheme::parse("[Colors:Window]\nBackgroundNormal=300,20,20\n"); - assert!(above.background.is_none()); - - let below = KdeScheme::parse("[Colors:Window]\nBackgroundNormal=-5,20,20\n"); - assert!(below.background.is_none()); - } -} diff --git a/crates/ui/src/theme/source/linux.rs b/crates/ui/src/theme/source/linux.rs index 681351c..69c8983 100644 --- a/crates/ui/src/theme/source/linux.rs +++ b/crates/ui/src/theme/source/linux.rs @@ -8,9 +8,14 @@ use std::path::{Path, PathBuf}; use gpui::Hsla; use notify::{RecursiveMode, Watcher}; +use super::ThemeSource; +use super::kde; +use super::omarchy; +use super::portal; use super::signal::ReapplySignal; -use super::{ThemeSource, kde, omarchy, portal}; + use crate::theme::ThemeVariant; + use crate::theme::system::{SourceKind, SystemTheme}; pub(crate) struct LinuxSource { @@ -280,46 +285,3 @@ impl ThemeSource for LinuxSource { } } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_detection_cascade_prefers_the_marker_files() { - let home = std::env::temp_dir().join(format!("signed-theme-detect-{}", std::process::id())); - std::fs::create_dir_all(&home).expect("temp home"); - assert_eq!(detect(&home, false, false), Backend::Fallback); - assert_eq!(detect(&home, false, true), Backend::Portal); - - std::fs::create_dir_all(home.join(".config/omarchy")).expect("omarchy marker"); - assert_eq!(detect(&home, false, false), Backend::Omarchy); - assert_eq!(detect(&home, true, true), Backend::Omarchy); - std::fs::remove_dir_all(home.join(".config/omarchy")).expect("remove marker"); - - std::fs::write(home.join(".config/kdeglobals"), "").expect("kdeglobals"); - assert_eq!(detect(&home, false, false), Backend::Kde); - assert_eq!(detect(&home, true, false), Backend::Kde); - std::fs::remove_dir_all(&home).expect("cleanup"); - } - - #[test] - fn the_gnome_snapshot_labels_gnome() { - let source = LinuxSource { - backend: Backend::Portal, - portal: None, - gsettings: None, - file_watcher: None, - _signal: None, - }; - let system = source.gnome_snapshot( - ThemeVariant::Light, - None, - crate::theme::system::AccessibilityPreferences::default(), - ); - - assert_eq!(system.source, SourceKind::Gnome); - assert_eq!(system.variant, ThemeVariant::Light); - assert_eq!(system.accent, None); - } -} diff --git a/crates/ui/src/theme/source/macos.rs b/crates/ui/src/theme/source/macos.rs index 52e489d..4697c29 100644 --- a/crates/ui/src/theme/source/macos.rs +++ b/crates/ui/src/theme/source/macos.rs @@ -13,8 +13,10 @@ use objc2_foundation::{ NSNotificationName, NSObjectNSKeyValueObserverRegistration, NSString, NSUserDefaults, }; +use super::narrow_component; + +use super::ThemeSource; use super::signal::ReapplySignal; -use super::{ThemeSource, narrow_component}; use crate::theme::ThemeVariant; use crate::theme::system::{AccessibilityPreferences, SourceKind, SystemTheme}; diff --git a/crates/ui/src/theme/source/omarchy.rs b/crates/ui/src/theme/source/omarchy.rs index de14e2a..aa34c16 100644 --- a/crates/ui/src/theme/source/omarchy.rs +++ b/crates/ui/src/theme/source/omarchy.rs @@ -84,87 +84,3 @@ pub(crate) mod io { OmarchyTheme::parse(&text) } } - -#[cfg(test)] -mod tests { - use super::*; - - const TOKYO_NIGHT: &str = "\ -mode = \"dark\" - -accent = \"#7aa2f7\" -selection = \"#292e42\" -muted = \"#414868\" - -background = \"#1a1b26\" -dark_background = \"#13141c\" -darker_background = \"#0e0e14\" -lighter_background = \"#24283b\" - -foreground = \"#a9b1d6\" -dark_foreground = \"#565f89\" - -red = \"#f7768e\" -yellow = \"#e0af68\" -orange = \"#eb927b\" -green = \"#9ece6a\" -"; - - const ANSI_GENERATED: &str = "\ -accent = \"#0060ff\" -selection = \"#c1c8d2\" - -background = \"#e8e8ec\" -foreground = \"#251f32\" - -color0 = \"#e8e8ec\" -color1 = \"#ab2833\" -color2 = \"#3f7c38\" -color3 = \"#8f6235\" -color4 = \"#0060ff\" -color5 = \"#8d439d\" -color6 = \"#3e7d96\" -color7 = \"#251f32\" -color8 = \"#625e6a\" -color9 = \"#cd3d45\" -color10 = \"#44a540\" -color11 = \"#c18a41\" -color12 = \"#278aff\" -color13 = \"#a659b9\" -color14 = \"#4b9fc0\" -color15 = \"#635d6f\" -"; - - #[test] - fn semantic_keys_state_the_mode_and_accent() { - let theme = OmarchyTheme::parse(TOKYO_NIGHT).expect("tokyo-night parses"); - - assert_eq!(theme.variant, ThemeVariant::Dark); - assert_eq!(theme.accent, Some(Hsla::from(gpui::rgb(0x7aa2f7)))); - } - - #[test] - fn ansi_fallback_derives_the_variant_from_the_background() { - let theme = OmarchyTheme::parse(ANSI_GENERATED).expect("ANSI palette parses"); - - assert_eq!(theme.variant, ThemeVariant::Light); - assert_eq!(theme.accent, Some(Hsla::from(gpui::rgb(0x0060ff)))); - } - - #[test] - fn a_stated_mode_beats_the_derivation() { - let text = "mode = \"light\"\naccent = \"#7aa2f7\"\nbackground = \"#1a1b26\"\nforeground = \"#a9b1d6\"\n"; - let theme = OmarchyTheme::parse(text).expect("parses"); - assert_eq!(theme.variant, ThemeVariant::Light); - } - - #[test] - fn the_system_snapshot_keeps_only_mode_and_accent() { - let theme = OmarchyTheme::parse(TOKYO_NIGHT).expect("parses"); - let system = theme.into_system(Default::default()); - - assert_eq!(system.variant, ThemeVariant::Dark); - assert_eq!(system.accent, theme.accent); - assert_eq!(system.source, SourceKind::Omarchy); - } -} diff --git a/crates/ui/src/theme/source/portal.rs b/crates/ui/src/theme/source/portal.rs index 7ac3cdd..7301bb2 100644 --- a/crates/ui/src/theme/source/portal.rs +++ b/crates/ui/src/theme/source/portal.rs @@ -6,8 +6,8 @@ use gpui::Hsla; use super::narrow_component; -use crate::theme::ThemeVariant; -use crate::theme::system::AccessibilityPreferences; + +use crate::theme::{ThemeVariant, system::AccessibilityPreferences}; /// The raw portal values, already converted off the DBus wire types. #[derive(Clone, Copy, Debug, Default, PartialEq)] @@ -176,55 +176,3 @@ pub(crate) mod io { ) } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_full_appearance_decodes() { - let appearance = AppearanceValues { - color_scheme: Some(1), - accent_rgb: Some((0.48, 0.62, 0.89)), - contrast: Some(0), - reduced_motion: Some(0), - } - .decode(); - - assert_eq!( - appearance.variant(crate::theme::ThemeVariant::Light), - crate::theme::ThemeVariant::Dark - ); - let accent = appearance.accent.expect("accent decodes"); - let rgba = gpui::Rgba::from(accent); - assert!(rgba.b > rgba.r); - } - - #[test] - fn no_preference_yields_the_callers_variant() { - let appearance = AppearanceValues { - color_scheme: Some(0), - ..AppearanceValues::default() - } - .decode(); - assert_eq!( - appearance.variant(crate::theme::ThemeVariant::Light), - crate::theme::ThemeVariant::Light - ); - } - - #[test] - fn accessibility_flags_forward() { - let accessibility = AppearanceValues { - contrast: Some(1), - reduced_motion: Some(1), - ..AppearanceValues::default() - } - .decode() - .accessibility(); - - assert!(accessibility.high_contrast); - assert!(accessibility.reduce_motion); - assert!(!accessibility.reduce_transparency); - } -} diff --git a/crates/ui/src/theme/typography.rs b/crates/ui/src/theme/typography.rs index 18d4caf..be5886e 100644 --- a/crates/ui/src/theme/typography.rs +++ b/crates/ui/src/theme/typography.rs @@ -144,66 +144,3 @@ pub trait Typeset: Styled + Sized { } impl Typeset for E {} - -#[cfg(test)] -mod tests { - use super::*; - - fn typography(root_font_size: f32) -> Typography { - Typography::resolve(px(root_font_size)) - } - - #[test] - fn the_unified_ladder_matches_the_base_contract() { - let typography = typography(16.0); - let expected = [ - (TextRole::LargeTitle, 24.0, 32.0, FontWeight::SEMIBOLD), - (TextRole::Title, 20.0, 28.0, FontWeight::SEMIBOLD), - (TextRole::Title2, 18.0, 24.0, FontWeight::SEMIBOLD), - (TextRole::Title3, 16.0, 24.0, FontWeight::SEMIBOLD), - (TextRole::Headline, 14.0, 20.0, FontWeight::SEMIBOLD), - (TextRole::Body, 16.0, 24.0, FontWeight::NORMAL), - (TextRole::Callout, 14.0, 20.0, FontWeight::NORMAL), - (TextRole::Subheadline, 14.0, 20.0, FontWeight::NORMAL), - (TextRole::Footnote, 13.0, 18.0, FontWeight::NORMAL), - (TextRole::Caption, 12.0, 16.0, FontWeight::NORMAL), - (TextRole::Caption2, 12.0, 16.0, FontWeight::MEDIUM), - ]; - for (role, size, line_height, weight) in expected { - assert_eq!( - typography.get(role), - TypeMetrics { - size: px(size), - line_height: px(line_height), - weight, - }, - "{role:?}" - ); - } - } - - #[test] - fn the_ladder_scales_from_a_16px_root() { - let base = typography(16.0); - let raised = typography(20.0); - for role in [ - TextRole::LargeTitle, - TextRole::Title, - TextRole::Title2, - TextRole::Title3, - TextRole::Headline, - TextRole::Body, - TextRole::Callout, - TextRole::Subheadline, - TextRole::Footnote, - TextRole::Caption, - TextRole::Caption2, - ] { - let base = base.get(role); - let raised = raised.get(role); - assert!((raised.size - base.size * 1.25).abs() < px(0.01)); - assert!((raised.line_height - base.line_height * 1.25).abs() < px(0.01)); - assert_eq!(raised.weight, base.weight); - } - } -} diff --git a/crates/ui/src/utils.rs b/crates/ui/src/utils.rs deleted file mode 100644 index 4a53bd4..0000000 --- a/crates/ui/src/utils.rs +++ /dev/null @@ -1,173 +0,0 @@ -use std::collections::HashMap; - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - App, Bounds, BoxShadow, Div, ElementId, FocusHandle, Global, Hsla, IntoElement, Pixels, - Refineable as _, StatefulInteractiveElement, StyleRefinement, Styled, Window, WindowId, div, - px, -}; - -use crate::theme::{ActiveTheme as _, FOCUS_RING_ALPHA, FOCUS_RING_SPREAD}; - -/// A row whose children center on the cross axis. -#[must_use] -pub fn h_flex() -> Div { - div().flex().flex_row().items_center() -} - -/// A column whose children stack on the main axis. -#[must_use] -pub fn v_flex() -> Div { - div().flex().flex_col() -} - -/// Logs the error and yields the success value, if any. -pub trait ResultLogErr { - /// Logs the error and yields the success value, if any. - fn log_err(self) -> Option; -} - -impl ResultLogErr for Result { - fn log_err(self) -> Option { - match self { - Ok(value) => Some(value), - Err(error) => { - log::warn!("{error}"); - None - } - } - } -} - -/// Extensions over [`Styled`], shared by the components. -pub trait StyledExt: Styled + Sized { - #[must_use] - fn refine_style(mut self, style: &StyleRefinement) -> Self { - self.style().refine(style); - self - } -} - -impl StyledExt for E {} - -/// Returns a focus handle for the given element ID. -pub fn focus_handle(id: &ElementId, window: &mut Window, cx: &mut App) -> FocusHandle { - window - .with_element_namespace(id.clone(), |window| { - window.use_keyed_state("focus-handle", cx, |_, cx| cx.focus_handle()) - }) - .read(cx) - .clone() -} - -/// The painted bounds of elements that tooltips anchor to, per window and element id. -/// Entries are never evicted: bounds are bounded by live windows, though long-lived processes minting dynamic per-item ids could accumulate. -#[derive(Default)] -struct AnchorBoundsRegistry(HashMap<(WindowId, ElementId), Bounds>); - -impl Global for AnchorBoundsRegistry {} - -impl AnchorBoundsRegistry { - fn record(&mut self, window: WindowId, id: ElementId, bounds: Bounds) { - self.0.insert((window, id), bounds); - } - - fn get(&self, window: WindowId, id: &ElementId) -> Option> { - self.0.get(&(window, id.clone())).copied() - } -} - -/// The last bounds an element painted at, in the given window. -pub fn anchor_bounds(window: WindowId, id: &ElementId, cx: &App) -> Option> { - cx.try_global::() - .and_then(|registry| registry.get(window, id)) -} - -/// A canvas prepaint closure recording the element's painted bounds. -pub fn record_anchor_bounds( - id: ElementId, -) -> impl Fn(Bounds, &mut Window, &mut App) + 'static { - move |bounds, window, cx| { - let window_id = window.window_handle().window_id(); - cx.default_global::() - .record(window_id, id.clone(), bounds); - } -} - -/// Returns a focus ring shadow with the given color at half ink. -pub fn focus_ring(color: Hsla) -> Vec { - vec![ - BoxShadow::new(px(0.), px(0.), color.alpha(FOCUS_RING_ALPHA)) - .spread_radius(FOCUS_RING_SPREAD), - ] -} - -/// The next selectable row in the direction, or `None` at the ends. -pub fn adjacent_selectable( - selectable: &[usize], - selected: Option, - forward: bool, -) -> Option { - if forward { - selectable - .iter() - .copied() - .find(|index| Some(*index) > selected) - } else { - selectable - .iter() - .copied() - .rev() - .find(|index| Some(*index) < selected) - } -} - -/// Whether the given key is a vertical navigation key. -pub fn nav_key(selectable: &[usize], selected: Option, key: &str, select: S) -> bool -where - S: FnOnce(Option), -{ - let target = match key { - "down" => adjacent_selectable(selectable, selected, true), - "up" => adjacent_selectable(selectable, selected, false), - "home" => selectable.first().copied(), - "end" => selectable.last().copied(), - _ => return false, - }; - if let Some(next) = target - && Some(next) != selected - { - select(Some(next)); - } - true -} - -/// A selectable row's label and icon color. -pub fn selectable_label_color(cx: &App, selected: bool, disabled: bool) -> Hsla { - let theme = cx.theme(); - if disabled { - theme.colors.muted_foreground - } else if selected { - theme.colors.primary_foreground - } else { - theme.colors.foreground - } -} - -/// A selectable row's background. -#[must_use] -pub fn paint_selectable_row(cx: &App, row: R, selected: bool, disabled: bool) -> R -where - R: IntoElement + Styled + StatefulInteractiveElement, -{ - let theme = cx.theme(); - row.map(|row| { - if disabled { - row - } else if selected { - row.bg(theme.ramps.primary.base) - } else { - row.hover(|row| row.bg(theme.colors.muted)) - } - }) -} diff --git a/crates/ui/tests/tabs.rs b/crates/ui/tests/tabs.rs index c85478e..2ba264c 100644 --- a/crates/ui/tests/tabs.rs +++ b/crates/ui/tests/tabs.rs @@ -11,7 +11,7 @@ use gpui::{ ParentElement as _, Render, Styled as _, TestAppContext, VisualTestContext, Window, div, point, px, size, }; -use ui::data::tabs::{Tab, Tabs, TabsVariant}; +use ui::tabs::{Tab, Tabs, TabsVariant}; use ui::theme::Theme; struct StripHarness { diff --git a/docs/ui-gaps.md b/docs/ui-gaps.md index 1a09cd9..c74b901 100644 --- a/docs/ui-gaps.md +++ b/docs/ui-gaps.md @@ -21,10 +21,10 @@ modifying it or reimplementing a parallel mechanism. `CommitDiff` carries hunks only. The custom hunk rows are retained. 7. **Tree data.** `ui` tree is flat with caller-managed expansion. Folder rows use `IconRole::Folder` and file rows use `IconRole::File`. -8. **Dynamic dock panels.** `DockState` has no unregister or `open_view` API. - Per-repository/per-entity panels register a builder keyed by a unique id and - stay in the builder map. No dock persistence, zoom, or bottom/right - placement; splits only. +8. **Dock panels.** `ui` has no dock, tab-group, or view registry API: `Panel` + covers one split row and `Resizable` stacked panes. Per-repository panels + register a builder keyed by a unique id and stay in the builder map. No dock + persistence, zoom, or bottom/right placement; splits only. 9. **Dialogs.** Dialogs are elements mounted at the window root; there is no `window.open_dialog`, dialog stack, or non-dismissible option. A single-slot `DialogHost` is used, and the passphrase dialog ignores dismiss requests.