new layout (wip) (#34)
Rust / build (macos-latest, stable) (push) Canceled after 0s
Rust / build (ubuntu-latest, stable) (push) Canceled after 0s
Rust / build (windows-latest, stable) (push) Canceled after 0s

Reviewed-on: #34
This commit was merged in pull request #34.
This commit is contained in:
2026-11-19 07:43:44 +00:00
parent a249174026
commit 5a597f43c4
368 changed files with 38791 additions and 18423 deletions
+425
View File
@@ -0,0 +1,425 @@
//! 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 gpui::prelude::FluentBuilder as _;
use gpui::{
Animation, AnimationExt as _, App, Context, ElementId, Entity, InteractiveElement as _,
IntoElement, ParentElement as _, RenderOnce, Role, SharedString,
StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, deferred, div,
ease_out_quint,
};
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 _,
};
/// How alarming an [`Alert`] is; picks the accent color.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AlertSeverity {
/// The default; uses the info role.
#[default]
Info,
/// Uses the success role.
Success,
/// Uses the warning role.
Warning,
/// Uses the destructive role.
Danger,
}
/// How an [`Alert`] presents.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AlertStyle {
/// A floating banner styled like a popover; the default.
#[default]
Overlay,
/// A tinted callout embedded in the page.
Inline,
}
/// A static callout banner.
#[derive(Clone, IntoElement)]
#[must_use]
pub struct Alert {
id: ElementId,
title: Option<SharedString>,
message: Option<SharedString>,
severity: AlertSeverity,
presentation: AlertStyle,
icon: Option<Icon>,
on_dismiss: Option<DismissHandler>,
style: StyleRefinement,
}
impl Alert {
/// Creates an alert.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
title: None,
message: None,
severity: AlertSeverity::Info,
presentation: AlertStyle::default(),
icon: None,
on_dismiss: None,
style: StyleRefinement::default(),
}
}
/// Sets the primary line.
pub fn title<L>(mut self, title: L) -> Self
where
L: Into<SharedString>,
{
self.title = Some(title.into());
self
}
/// Sets a secondary line under the title.
pub fn message<L>(mut self, message: L) -> Self
where
L: Into<SharedString>,
{
self.message = Some(message.into());
self
}
/// Sets how alarming the alert is.
pub fn severity(mut self, severity: AlertSeverity) -> Self {
self.severity = severity;
self
}
/// Sets how the alert presents.
pub fn style(mut self, style: AlertStyle) -> Self {
self.presentation = style;
self
}
/// Shows an icon before the text.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Runs when the user dismisses the alert.
pub fn on_dismiss<F>(mut self, handler: F) -> Self
where
F: Fn(&mut App) + 'static,
{
self.on_dismiss = Some(Rc::new(handler));
self
}
fn rekey(mut self, id: usize) -> Self {
self.id = ElementId::from(id);
self
}
}
impl gpui::Styled for Alert {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Alert {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let ramp = match self.severity {
AlertSeverity::Info => theme.ramps.info,
AlertSeverity::Success => theme.ramps.success,
AlertSeverity::Warning => theme.ramps.warning,
AlertSeverity::Danger => theme.ramps.destructive,
};
let foreground = theme.colors.foreground;
let muted_foreground = theme.colors.muted_foreground;
let metrics = theme.sizes.resolve(Size::Medium);
let icon_size = metrics.icon_size;
let dense_icon_size = metrics.dense_icon_size;
let content = v_flex()
.flex_1()
.gap_0p5()
.when_some(self.title.clone(), |alert, title| {
alert.child(
div()
.typeset(TextRole::Headline, cx)
.text_color(foreground)
.child(title),
)
})
.when_some(self.message.clone(), |alert, message| {
let color = if self.title.is_some() {
muted_foreground
} else {
foreground
};
alert.child(
div()
.text_size(metrics.text_size)
.text_color(color)
.child(message),
)
});
let dismiss = self.on_dismiss.clone().map(|on_dismiss| {
Button::new((self.id.clone(), "alert-close"))
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.xsmall()
.accessibility_label("Dismiss")
.on_click(move |_, _window, cx| on_dismiss(cx))
});
match self.presentation {
AlertStyle::Overlay => {
let surface = theme.colors.surface;
let border = theme.colors.border;
div()
.id(self.id.clone())
.role(Role::Alert)
.w_full()
.flex()
.items_start()
.gap_2()
.px_3()
.py_2()
.rounded(theme.radius.overlay)
.bg(surface)
.border_1()
.border_color(border)
.shadow(theme.elevations.popover.shadows())
.refine_style(&self.style)
.when_some(self.icon.clone(), |alert, icon_glyph| {
alert.child(
div()
.flex_none()
.flex()
.items_center()
.h(window.line_height())
.child(icon_glyph.size(icon_size).color(ramp.base)),
)
})
.child(content)
.when_some(dismiss, |alert, dismiss| alert.child(dismiss))
}
AlertStyle::Inline => div()
.id(self.id.clone())
.role(Role::Alert)
.w_full()
.flex()
.overflow_hidden()
.bg(ramp.subtle)
.refine_style(&self.style)
.child(
div()
.flex_none()
.w(ALERT_EDGE_WIDTH)
.self_stretch()
.bg(ramp.base),
)
.child(
div()
.flex_1()
.flex()
.items_start()
.gap_3()
.px_3()
.py_2()
.when_some(self.icon.clone(), |alert, icon_glyph| {
alert.child(
div()
.flex_none()
.flex()
.items_center()
.justify_center()
.size(theme.sizes.small.avatar_size)
.rounded(theme.radius.full)
.bg(ramp.base)
.child(icon_glyph.size(dense_icon_size).color(ramp.foreground)),
)
})
.child(content),
)
.when_some(dismiss, |alert, dismiss| {
alert.child(div().flex_none().self_center().pr_3().child(dismiss))
}),
}
}
}
/// 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<DismissHandler>,
}
/// The stack of pushed alerts.
#[derive(Default)]
pub struct Alerts {
entries: Vec<AlertEntry>,
next_id: usize,
}
impl Alerts {
/// Pushes an alert onto the stack and returns its id.
pub fn push(&mut self, mut alert: Alert, cx: &mut Context<Self>) -> usize {
let id = self.next_id;
self.next_id += 1;
let on_dismiss = alert.on_dismiss.take();
let stack = cx.entity().downgrade();
alert.on_dismiss = Some(Rc::new(move |cx: &mut App| {
stack
.update(cx, |alerts, cx| alerts.dismiss(id, cx))
.log_err();
}));
self.entries.push(AlertEntry {
id,
alert: alert.rekey(id),
on_dismiss,
});
cx.notify();
id
}
/// Dismisses one alert by id, running its dismiss handler.
pub fn dismiss(&mut self, id: usize, cx: &mut Context<Self>) {
if let Some(position) = self.entries.iter().position(|entry| entry.id == id) {
let entry = self.entries.remove(position);
cx.notify();
if let Some(on_dismiss) = &entry.on_dismiss {
(on_dismiss.clone())(cx);
}
}
}
/// Dismisses every alert, running each entry's `on_dismiss` handler.
pub fn clear(&mut self, cx: &mut Context<Self>) {
if self.entries.is_empty() {
return;
}
let entries = std::mem::take(&mut self.entries);
cx.notify();
for entry in entries {
if let Some(on_dismiss) = entry.on_dismiss {
on_dismiss(cx);
}
}
}
/// The stacked alerts, oldest first.
pub fn entries(&self) -> &[AlertEntry] {
&self.entries
}
/// How many alerts are stacked.
pub fn count(&self) -> usize {
self.entries.len()
}
}
/// The floating stack of pushed alerts, topmost right.
#[derive(IntoElement)]
#[must_use]
pub struct AlertsView {
alerts: Entity<Alerts>,
id: ElementId,
}
impl AlertsView {
/// Binds the view to an alert stack.
pub fn new<I>(id: I, alerts: Entity<Alerts>) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
alerts,
}
}
}
impl RenderOnce for AlertsView {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let enter_duration = theme.motion.overlay;
let entries = self.alerts.read(cx).entries();
deferred(
div()
.id(self.id)
.absolute()
.top_4()
.right_4()
.w(ALERT_STACK_WIDTH)
.flex()
.flex_col()
.items_end()
.gap_2()
.children(entries.iter().rev().map(|entry| {
let id = entry.id;
let ease_slide = ease_out_quint();
div()
.relative()
.w_full()
.debug_selector(|| "alert-entry".to_string())
.child(entry.alert.clone())
.with_animation(
("alert-enter", id),
Animation::new(enter_duration),
move |layer, delta| {
layer.left(ENTER_SLIDE_DISTANCE * (1. - ease_slide(delta)))
},
)
})),
)
.with_priority(TOAST_LAYER)
}
}
+296
View File
@@ -0,0 +1,296 @@
//! 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 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;
/// Empty cells kept between the pattern and the avatar edge.
const MARGIN: usize = 1;
/// Probability that a cell in the left half of the pattern area is filled.
const FILL_PROBABILITY: f32 = 0.42;
/// Probability that a filled cell uses the shade instead of the main color.
const SHADE_PROBABILITY: f32 = 0.25;
/// Minimum number of filled left-half cells.
const MIN_FILLED: usize = 5;
/// An avatar for a user or other entity.
#[derive(IntoElement)]
#[must_use]
pub struct Avatar {
id: SharedString,
name: Option<SharedString>,
picture: Option<SharedString>,
size: Size,
fully_rounded: bool,
style: StyleRefinement,
}
impl Avatar {
/// 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<T>(id: T) -> Self
where
T: Display,
{
Self {
id: id.to_string().into(),
name: None,
picture: None,
size: Size::default(),
fully_rounded: false,
style: StyleRefinement::default(),
}
}
/// Sets the display name used as the image's accessibility label.
pub fn name<N>(mut self, name: N) -> Self
where
N: Into<SharedString>,
{
self.name = Some(name.into());
self
}
/// Sets the picture URL; `None` shows the pixel fallback.
pub fn picture<P>(mut self, picture: Option<P>) -> Self
where
P: Into<SharedString>,
{
self.picture = picture.map(Into::into);
self
}
/// 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
}
}
impl Sizable for Avatar {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl gpui::Styled for Avatar {
fn style(&mut self) -> &mut gpui::StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Avatar {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
// Avatars sit one class below the shared control scale.
let size = match self.size {
Size::XSmall | Size::Small => Size::XSmall,
Size::Medium => Size::Small,
Size::Large => Size::Medium,
};
let side = theme.sizes.resolve(size).avatar_size;
let radius = if self.fully_rounded {
theme.radius.full
} else {
theme.radius.sm
};
let base = h_flex()
.id(ElementId::from(self.id.clone()))
.flex_none()
.justify_center()
.overflow_hidden()
.size(side)
.bg(theme.colors.secondary)
.rounded(radius)
.role(Role::Image)
.aria_label(self.name.clone().unwrap_or_else(|| self.id.clone()))
.refine_style(&self.style);
match self.picture {
Some(url) => base.child(gpui::img(url).size_full().rounded(radius)),
None => base.child(PixelAvatar {
seed: fnv1a(self.id.as_bytes()),
side,
radius,
fully_rounded: self.fully_rounded,
}),
}
.into_any_element()
}
}
/// A deterministic, offline pixel-art avatar.
#[derive(IntoElement)]
struct PixelAvatar {
seed: u64,
side: gpui::Pixels,
radius: gpui::Pixels,
fully_rounded: bool,
}
impl RenderOnce for PixelAvatar {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let pattern = pattern(self.seed);
let mut cells = Vec::new();
let hue = (self.seed as f32 / u64::MAX as f32) * 360.0;
let accent = Oklch::from_hsla(theme.colors.accent);
let main = Oklch { h: hue, ..accent }.to_hsla();
let shade = if theme.variant == ThemeVariant::Dark {
Oklch {
l: (accent.l * PIXEL_AVATAR_LIGHT_LIFT).min(PIXEL_AVATAR_LIGHT_CAP),
..Oklch::from_hsla(main)
}
.to_hsla()
} else {
Oklch {
l: (accent.l * PIXEL_AVATAR_DARK_FACTOR).max(PIXEL_AVATAR_DARK_FLOOR),
..Oklch::from_hsla(main)
}
.to_hsla()
};
let inset = if self.fully_rounded {
self.side / GRID_SIZE as f32
} else {
gpui::Pixels::ZERO
};
for row in 0..GRID_SIZE {
for col in 0..GRID_SIZE {
let value = pattern[row * GRID_SIZE + col];
if value != 0 {
let color = if value == 2 { shade } else { main };
cells.push(
div()
.row_start(row as i16 + 1)
.row_end(row as i16 + 2)
.col_start(col as i16 + 1)
.col_end(col as i16 + 2)
.bg(color),
);
}
}
}
div()
.grid()
.grid_cols(GRID_SIZE as u16)
.grid_rows(GRID_SIZE as u16)
.size(self.side)
.flex_none()
.p(inset)
.rounded(self.radius)
.bg(gpui::Hsla {
a: PIXEL_AVATAR_TINT_ALPHA,
..main
})
.children(cells)
}
}
fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] {
let mut rng = PixelRng::new(seed);
let mut pattern = [0u8; GRID_SIZE * GRID_SIZE];
let mut filled = 0usize;
let art_rows = GRID_SIZE - 2 * MARGIN;
let art_columns = GRID_SIZE / 2 - MARGIN;
for row in MARGIN..GRID_SIZE - MARGIN {
for col in MARGIN..GRID_SIZE / 2 {
if rng.chance(FILL_PROBABILITY) {
let shade = rng.chance(SHADE_PROBABILITY);
set_cell(&mut pattern, row, col, if shade { 2 } else { 1 });
filled += 1;
}
}
}
if filled < MIN_FILLED {
let total = art_rows * art_columns;
let start = (rng.next() % total as u64) as usize;
for offset in 0..total {
if filled >= MIN_FILLED {
break;
}
let flat_index = (start + offset) % total;
let row = MARGIN + flat_index / art_columns;
let col = MARGIN + flat_index % art_columns;
if pattern[row * GRID_SIZE + col] == 0 {
set_cell(&mut pattern, row, col, 1);
filled += 1;
}
}
}
pattern
}
/// Fill `cell (row, col)` and its horizontal mirror.
fn set_cell(pattern: &mut [u8; GRID_SIZE * GRID_SIZE], row: usize, col: usize, value: u8) {
pattern[row * GRID_SIZE + col] = value;
pattern[row * GRID_SIZE + (GRID_SIZE - 1 - col)] = value;
}
/// FNV-1a 64-bit hash, stable across platforms and runs.
fn fnv1a(bytes: &[u8]) -> u64 {
let mut hash = 0xcbf2_9ce4_8422_2325u64;
for &byte in bytes {
hash ^= byte as u64;
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
hash
}
/// Tiny xorshift64* PRNG for deriving the pattern from the seed.
struct PixelRng(u64);
impl PixelRng {
fn new(seed: u64) -> Self {
Self(seed.max(1))
}
fn next(&mut self) -> u64 {
let mut x = self.0;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.0 = x;
x.wrapping_mul(0x2545_f491_4f6c_dd1d)
}
fn chance(&mut self, probability: f32) -> bool {
self.next() as f32 / (u64::MAX as f32) < probability
}
}
+184
View File
@@ -0,0 +1,184 @@
//! 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 gpui::prelude::FluentBuilder as _;
use gpui::{
AnyView, App, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _,
RenderOnce, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
Window, transparent_black,
};
use crate::components::common::{Sizable, 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<dyn Fn(&mut Window, &mut App) -> AnyView>;
/// The visual treatment of a [`Badge`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BadgeVariant {
/// The default; quiet muted fill for counts.
#[default]
Neutral,
/// The accent ramp; something active or newly added.
Accent,
/// The success ramp.
Success,
/// The warning ramp.
Warning,
/// The destructive ramp.
Danger,
/// No fill, just a border; the quietest badge.
Outline,
}
impl BadgeVariant {
fn tokens(self, theme: &Theme) -> (Hsla, Hsla, Hsla) {
match self {
Self::Neutral => (
theme.colors.muted,
theme.colors.muted_foreground,
transparent_black(),
),
Self::Accent => (
theme.ramps.primary.base,
theme.colors.primary_foreground,
transparent_black(),
),
Self::Success => (
theme.ramps.success.base,
theme.colors.success_foreground,
transparent_black(),
),
Self::Warning => (
theme.ramps.warning.base,
theme.colors.warning_foreground,
transparent_black(),
),
Self::Danger => (
theme.ramps.destructive.base,
theme.colors.destructive_foreground,
transparent_black(),
),
Self::Outline => (
transparent_black(),
theme.colors.foreground,
theme.colors.border,
),
}
}
}
/// A small pill for a count or a state.
#[derive(IntoElement)]
#[must_use]
pub struct Badge {
id: ElementId,
label: SharedString,
icon: Option<Icon>,
variant: BadgeVariant,
size: Size,
tooltip: Option<TooltipBuilder>,
style: StyleRefinement,
}
impl Badge {
/// Creates a badge with `label`, a count or state word the caller formats.
pub fn new<I, L>(id: I, label: L) -> Self
where
I: Into<ElementId>,
L: Into<SharedString>,
{
Self {
id: id.into(),
label: label.into(),
icon: None,
variant: BadgeVariant::default(),
size: Size::default(),
tooltip: None,
style: StyleRefinement::default(),
}
}
/// Sets the badge's [`BadgeVariant`].
pub fn variant(mut self, variant: BadgeVariant) -> Self {
self.variant = variant;
self
}
/// Shows an icon before the label.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Shows a tooltip view next to the badge after it is hovered.
pub fn tooltip<F>(mut self, tooltip: F) -> Self
where
F: Fn(&mut Window, &mut App) -> AnyView + 'static,
{
self.tooltip = Some(Rc::new(tooltip));
self
}
}
impl Sizable for Badge {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl gpui::Styled for Badge {
fn style(&mut self) -> &mut gpui::StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Badge {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let metrics = theme.sizes.resolve(self.size);
let label_size = match self.size {
Size::XSmall | Size::Small => metrics.caption_size * 0.9,
Size::Medium | Size::Large => metrics.caption_size,
};
let square = label_size * 2.;
let (background, foreground, border) = self.variant.tokens(theme);
h_flex()
.id(self.id.clone())
.flex_none()
.justify_center()
.gap_1()
.rounded(theme.radius.full)
.border_1()
.border_color(border)
.bg(background)
.text_color(foreground)
.text_size(label_size)
.px(label_size * 0.5)
.min_w(square)
.min_h(square)
.when_some(self.icon, |badge, icon| {
badge.child(icon.size(metrics.dense_icon_size).color(foreground))
})
.child(self.label)
.refine_style(&self.style)
.when_some(self.tooltip, |badge, tooltip| {
badge.tooltip(move |window, cx| tooltip(window, cx))
})
}
}
+393
View File
@@ -0,0 +1,393 @@
//! 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 std::rc::Rc;
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 crate::components::common::{
Sizable, StyledExt as _, focus_ring, h_flex, record_anchor_bounds,
};
use crate::components::spinner::Spinner;
use crate::icons::Icon;
use crate::spinner::SpinnerVariant;
use crate::theme::{ActiveTheme as _, ControlMetrics, DISABLED_OPACITY, Size};
/// The single activation handler, shared by pointer, Enter, and Space.
type ClickHandler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
/// The tooltip view builder gpui's `.tooltip(...)` expects.
type TooltipBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyView>;
/// Which visual treatment a button uses.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ButtonVariant {
/// The platform's default action.
#[default]
Primary,
/// The everyday companion to `Primary`.
Secondary,
/// Unpainted until hovered, for toolbars and dense UI.
Ghost,
/// The destructive action.
Destructive,
}
/// Which edge the button's content aligns to.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ButtonSide {
/// Centered content.
#[default]
Center,
/// Content on the left edge, icon leading the label.
Left,
/// Content on the right edge, icon trailing the label.
Right,
}
/// 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 {
id: ElementId,
label: Option<SharedString>,
icon: Option<Icon>,
children: Vec<AnyElement>,
variant: ButtonVariant,
size: Size,
custom_metrics: Option<ControlMetrics>,
disabled: bool,
loading: bool,
padded: bool,
fully_rounded: bool,
full_width: bool,
side: ButtonSide,
tab_stop: bool,
debug_selector: Option<Rc<dyn Fn() -> String>>,
a11y_label: Option<SharedString>,
tooltip: Option<TooltipBuilder>,
on_click: Option<ClickHandler>,
style: StyleRefinement,
}
impl Button {
/// Creates a primary button.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
label: None,
icon: None,
children: Vec::new(),
variant: ButtonVariant::default(),
size: Size::default(),
custom_metrics: None,
disabled: false,
loading: false,
padded: true,
fully_rounded: false,
full_width: false,
side: ButtonSide::default(),
tab_stop: true,
debug_selector: None,
a11y_label: None,
tooltip: None,
on_click: None,
style: StyleRefinement::default(),
}
}
/// Sets the visible label.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Shows an icon beside the label; without a label the button renders square.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Shows a tooltip view next to the button after it is hovered.
pub fn tooltip<F>(mut self, tooltip: F) -> Self
where
F: Fn(&mut Window, &mut App) -> AnyView + 'static,
{
self.tooltip = Some(Rc::new(tooltip));
self
}
/// Sets the button's visual language.
pub fn variant(mut self, variant: ButtonVariant) -> Self {
self.variant = variant;
self
}
/// 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
}
/// Sets the debug-bounds selector, for headless tests.
pub fn debug_selector<F>(mut self, selector: F) -> Self
where
F: Fn() -> String + 'static,
{
self.debug_selector = Some(Rc::new(selector));
self
}
/// Renders the button inert, unfocusable, and dimmed.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Shows the spinner in place of the content and suppresses activation.
pub fn loading(mut self, loading: bool) -> Self {
self.loading = loading;
self
}
/// 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
}
/// Stretches the button and its content across the available width.
pub fn full_width(mut self, full_width: bool) -> Self {
self.full_width = full_width;
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;
self
}
/// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Sets the single activation handler, fired by pointer, Enter, and Space.
pub fn on_click<F>(mut self, handler: F) -> Self
where
F: Fn(&ClickEvent, &mut Window, &mut App) + 'static,
{
self.on_click = Some(Box::new(handler));
self
}
}
impl ParentElement for Button {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl gpui::Styled for Button {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Button {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Button {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
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());
let is_icon_only = self.icon.is_some() && self.label.is_none() && self.children.is_empty();
let icon_trailing = self.side == ButtonSide::Right;
let (background, foreground, hover, pressed) = match self.variant {
ButtonVariant::Primary => (
Some(ramps.primary.base),
colors.primary_foreground,
ramps.primary.hover,
ramps.primary.pressed,
),
ButtonVariant::Secondary => (
Some(colors.surface),
colors.foreground,
colors.muted,
colors.muted_hover,
),
ButtonVariant::Ghost => (
None,
colors.foreground,
colors.muted_hover,
ramps.secondary.pressed,
),
ButtonVariant::Destructive => (
Some(ramps.destructive.base),
colors.destructive_foreground,
ramps.destructive.hover,
ramps.destructive.pressed,
),
};
let (border, hover_border, pressed_border) = match self.variant {
ButtonVariant::Primary => (
ramps.primary.base,
ramps.primary.hover,
ramps.primary.pressed,
),
ButtonVariant::Secondary => (colors.border, colors.border, colors.border),
ButtonVariant::Ghost => (
transparent_black(),
transparent_black(),
transparent_black(),
),
ButtonVariant::Destructive => (
ramps.destructive.base,
ramps.destructive.hover,
ramps.destructive.pressed,
),
};
h_flex()
.id(self.id.clone())
.when_some(self.debug_selector, |button, selector| {
button.debug_selector(move || selector())
})
.role(Role::Button)
.map(|button| match self.side {
ButtonSide::Center => button.justify_center(),
ButtonSide::Left => button.justify_start(),
ButtonSide::Right => button.justify_end(),
})
.h(metrics.control_height)
.when(is_icon_only, |button| button.w(metrics.control_height))
.when(self.full_width, |button| button.w_full())
.when(!is_icon_only && self.padded, |button| {
button.px(metrics.padding_x)
})
.line_height(relative(1.0))
.rounded(radius)
.text_size(metrics.text_size)
.border_1()
.border_color(border)
.when_some(background, |button, background| button.bg(background))
.text_color(foreground)
.refine_style(&self.style)
.when_some(a11y_label, |button, label| button.aria_label(label))
.child(
h_flex()
.gap_2()
.when(self.full_width, |content| content.flex_1())
.when(self.loading, |content| content.invisible())
.map(|content| {
if icon_trailing {
content
.when_some(self.label, |content, label| content.child(label))
.children(self.children)
.when_some(self.icon, |content, icon| {
content.child(icon.size(metrics.icon_size))
})
} else {
content
.when_some(self.icon, |content, icon| {
content.child(icon.size(metrics.icon_size))
})
.when_some(self.label, |content, label| content.child(label))
.children(self.children)
}
}),
)
.when(self.loading, |button| {
button.child(
h_flex().absolute().inset_0().justify_center().child(
Spinner::new((self.id.clone(), "spinner"))
.with_size(self.size)
.variant(SpinnerVariant::Icon)
.color(foreground),
),
)
})
.child(
canvas(record_anchor_bounds(self.id.clone()), |_, _, _, _| {})
.absolute()
.inset_0(),
)
.when(self.disabled, |button| button.opacity(DISABLED_OPACITY))
.when_some(self.tooltip, |button, tooltip| {
button.tooltip(move |window, cx| tooltip(window, cx))
})
.when(!self.disabled && !self.loading, |button| {
button
.cursor_pointer()
.focusable()
.tab_stop(self.tab_stop)
.hover(move |style| style.bg(hover).border_color(hover_border))
.active(move |style| style.bg(pressed).border_color(pressed_border))
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.when_some(on_click, |button, on_click| {
button.on_click(move |event, window, cx| on_click(event, window, cx))
})
})
}
}
+187
View File
@@ -0,0 +1,187 @@
//! 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 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 _, focus_ring, h_flex};
use crate::icons::{IconRole, icon};
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
/// The change reporter, fired with the next value by pointer, Enter, and Space.
type ChangeHandler = Box<dyn Fn(bool, &mut Window, &mut App)>;
/// A controlled checkbox component.
#[derive(IntoElement)]
#[must_use]
pub struct Checkbox {
id: ElementId,
label: Option<SharedString>,
checked: bool,
size: Size,
disabled: bool,
debug_selector: Option<Rc<dyn Fn() -> String>>,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
style: StyleRefinement,
}
impl Checkbox {
/// Creates an unchecked checkbox.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
label: None,
checked: false,
size: Size::default(),
disabled: false,
debug_selector: None,
a11y_label: None,
on_change: None,
style: StyleRefinement::default(),
}
}
/// Sets the visible label; clicking it toggles too.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Sets the current value; the checkbox never owns it.
pub fn checked(mut self, checked: bool) -> Self {
self.checked = checked;
self
}
/// Renders the checkbox inert, unfocusable, and dimmed; disabled always wins.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Sets the debug-bounds selector, for headless tests.
pub fn debug_selector<F>(mut self, selector: F) -> Self
where
F: Fn() -> String + 'static,
{
self.debug_selector = Some(Rc::new(selector));
self
}
/// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Sets the change handler, fired with the next value by pointer, Enter, and Space.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(bool, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Box::new(handler));
self
}
}
impl gpui::Styled for Checkbox {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Checkbox {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Checkbox {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let metrics = theme.sizes.resolve(self.size);
let on_change = self.on_change;
let next = !self.checked;
let a11y_label = self.a11y_label.or_else(|| self.label.clone());
h_flex()
.id(self.id)
.gap_2()
.text_size(metrics.text_size)
.refine_style(&self.style)
.when_some(self.debug_selector, |checkbox, selector| {
checkbox.debug_selector(move || selector())
})
.role(Role::CheckBox)
.when_some(a11y_label, |checkbox, label| checkbox.aria_label(label))
.aria_toggled(Toggled::from(self.checked))
.when(self.disabled, |checkbox| checkbox.opacity(DISABLED_OPACITY))
.when(!self.disabled, |checkbox| {
checkbox
.cursor_pointer()
.focusable()
.tab_stop(true)
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.when_some(on_change, |checkbox, on_change| {
checkbox.on_click(move |_, window, cx| on_change(next, window, cx))
})
})
.child(
h_flex()
.justify_center()
.flex_none()
.size(metrics.indicator_size)
.rounded(theme.radius.sm)
.border_1()
.when(self.checked, |indicator| {
indicator
.bg(ramps.primary.base)
.border_color(ramps.primary.base)
.hover(|style| {
style
.bg(ramps.primary.hover)
.border_color(ramps.primary.hover)
})
.child(
icon(IconRole::Check)
.size(metrics.dense_icon_size)
.color(colors.primary_foreground),
)
})
.when(!self.checked, |indicator| {
indicator
.bg(colors.input)
.border_color(colors.border)
.hover(|style| style.border_color(colors.muted_foreground))
}),
)
.when_some(self.label, |checkbox, label| checkbox.child(label))
}
}
+186
View File
@@ -0,0 +1,186 @@
//! 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 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::{ResultLogErr as _, Sizable, StyledExt as _};
use crate::icons::IconRole;
use crate::theme::Size;
/// How long the check mark shows before reverting to the copy icon.
pub const COPIED_DURATION: Duration = Duration::from_secs(1);
/// The tooltip view builder gpui's `.tooltip(...)` expects.
type TooltipBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyView>;
/// Runs after the value lands on the clipboard.
type CopiedHandler = Box<dyn Fn(&mut App)>;
/// A quiet icon button that copies a value to the system clipboard.
#[derive(IntoElement)]
#[must_use]
pub struct ClipboardButton {
id: ElementId,
value: SharedString,
size: Size,
disabled: bool,
a11y_label: Option<SharedString>,
tooltip: Option<TooltipBuilder>,
on_copied: Option<CopiedHandler>,
style: StyleRefinement,
}
impl ClipboardButton {
/// Creates a copy button for this value.
pub fn new<I, V>(id: I, value: V) -> Self
where
I: Into<ElementId>,
V: Into<SharedString>,
{
Self {
id: id.into(),
value: value.into(),
size: Size::default(),
disabled: false,
a11y_label: None,
tooltip: None,
on_copied: None,
style: StyleRefinement::default(),
}
}
/// Shows a tooltip view next to the button after it is hovered.
pub fn tooltip<F>(mut self, tooltip: F) -> Self
where
F: Fn(&mut Window, &mut App) -> AnyView + 'static,
{
self.tooltip = Some(Rc::new(tooltip));
self
}
/// Renders the button inert and dimmed.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Overrides the accessibility label, which defaults to `Copy`.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Runs after the value lands on the clipboard.
pub fn on_copied<F>(mut self, handler: F) -> Self
where
F: Fn(&mut App) + 'static,
{
self.on_copied = Some(Box::new(handler));
self
}
}
impl Sizable for ClipboardButton {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
/// The transient copied marker keyed per button.
struct CopiedState {
generation: u64,
tasks: Vec<Task<()>>,
}
impl RenderOnce for ClipboardButton {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let copied: Entity<CopiedState> =
window.use_keyed_state((self.id.clone(), "clipboard-copied"), cx, |_, _| {
CopiedState {
generation: 0,
tasks: Vec::new(),
}
});
let is_copied = copied.read(cx).generation != 0;
let selector = if is_copied {
"clipboard-copied"
} else {
"clipboard"
};
Button::new((self.id.clone(), "clipboard-button"))
.icon(if is_copied {
IconRole::Check
} else {
IconRole::Copy
})
.variant(ButtonVariant::Ghost)
.with_size(self.size)
.disabled(self.disabled)
.refine_style(&self.style)
.debug_selector(move || selector.to_string())
.accessibility_label(self.a11y_label.unwrap_or_else(|| "Copy".into()))
.when_some(self.tooltip, |button, tooltip| {
button.tooltip(move |window, cx| tooltip(window, cx))
})
.on_click({
let value = self.value;
let copied = copied.clone();
let on_copied = self.on_copied;
move |_, window, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(value.to_string()));
let generation = copied.update(cx, |state, cx| {
state.generation += 1;
cx.notify();
state.generation
});
let weak = copied.downgrade();
let task = window.spawn(cx, async move |cx| {
cx.background_executor().timer(COPIED_DURATION).await;
cx.update(|_, cx| {
weak.update(cx, |state, cx| {
if state.generation == generation {
state.generation = 0;
cx.notify();
}
})
.log_err();
})
.log_err();
});
copied.update(cx, |state, _| {
state.tasks.push(task);
});
// Invoke the callback after copying
if let Some(on_copied) = &on_copied {
on_copied(cx);
}
}
})
}
}
+621
View File
@@ -0,0 +1,621 @@
//! 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<CodeViewState> {
//! 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 std::rc::Rc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, Bounds, ClipboardItem, Context, ElementId, HighlightStyle, Hsla, InteractiveElement as _,
IntoElement, KeyBinding, KeyBindingContextPredicate, MouseButton, MouseDownEvent,
MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Point, Render, ScrollStrategy,
SharedString, StatefulInteractiveElement as _, Styled as _, TextStyle, UniformListScrollHandle,
Window, actions, canvas, div, uniform_list,
};
use crate::components::highlight::{HighlightedCode, Language, Role, highlight};
use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility};
use crate::components::utils::gutter_cell;
use crate::theme::{
ActiveTheme as _, CODE_GUTTER_WIDTH, CODE_LINE_HEIGHT, ColorTokens, MONO_ADVANCE_RATIO, Ramps,
WASH_ALPHA_SOFT,
};
actions!(code_view, [Copy]);
/// The key context the code view declares while it holds focus.
pub const CODE_VIEW_CONTEXT: &str = "CodeView";
/// Binds the code view's copy chord: cmd-c on macOS, ctrl-c elsewhere.
///
/// Call once at startup. Without it, selection copy has no key.
pub fn bind_code_view_keys(cx: &mut App) {
let context = match KeyBindingContextPredicate::parse(CODE_VIEW_CONTEXT) {
Ok(context) => Some(Rc::new(context)),
Err(error) => {
log::error!("failed to parse code view key context: {error}");
return;
}
};
let binding = match KeyBinding::load("secondary-c", Box::new(Copy), context, false, None, cx) {
Ok(binding) => binding,
Err(error) => {
log::error!("failed to parse code view copy keystroke: {error}");
return;
}
};
cx.bind_keys([binding]);
}
/// 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,
}
impl SelectionPoint {
/// The earlier of two points, in document order.
fn earlier_than(&self, other: &Self) -> bool {
(self.row, self.col) <= (other.row, other.col)
}
}
/// 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,
language: Language,
code: HighlightedCode,
handle: UniformListScrollHandle,
/// The hovered line, driving the active-line wash and number emphasis.
active_line: Option<usize>,
/// `(anchor, head)` in the order they were set.
selection: Option<(SelectionPoint, SelectionPoint)>,
/// Whether a drag that started on a row is still extending the selection.
selecting: bool,
focus_handle: gpui::FocusHandle,
a11y_label: Option<SharedString>,
}
impl CodeViewState {
/// Builds the state, highlighting `source` with `language`.
pub fn new<I, S>(id: I, source: S, language: Language, cx: &mut App) -> Self
where
I: Into<ElementId>,
S: Into<SharedString>,
{
let source = source.into();
let code = highlight(&source, language);
Self {
id: id.into(),
source,
language,
code,
handle: UniformListScrollHandle::new(),
active_line: None,
selection: None,
selecting: false,
focus_handle: cx.focus_handle().tab_stop(true),
a11y_label: None,
}
}
/// Replaces the source and re-highlights it, clearing the selection and
/// scrolling back to the top.
pub fn set_source<S>(&mut self, source: S, language: Language, cx: &mut Context<Self>)
where
S: Into<SharedString>,
{
let source = source.into();
self.code = highlight(&source, language);
self.source = source;
self.language = language;
self.selection = None;
self.handle.scroll_to_item(0, ScrollStrategy::Top);
cx.notify();
}
/// 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<T>(&mut self, line_ix: usize, text: T, cx: &mut Context<Self>)
where
T: AsRef<str>,
{
let trailing_newline = self.source.ends_with('\n');
let mut lines: Vec<String> = self.source.lines().map(str::to_string).collect();
let line_ix = line_ix.min(lines.len().saturating_sub(1));
let replacement: Vec<String> = if text.as_ref().is_empty() {
vec![String::new()]
} else {
text.as_ref().lines().map(str::to_string).collect()
};
lines.splice(line_ix..line_ix + 1, replacement);
self.source = (lines.join("\n") + if trailing_newline { "\n" } else { "" }).into();
self.code = highlight(&self.source, self.language);
self.selection = None;
cx.notify();
}
/// The source text the view renders.
pub fn source(&self) -> &str {
&self.source
}
/// The highlighted lines.
pub fn code(&self) -> &HighlightedCode {
&self.code
}
/// 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)),
ScrollStrategy::Top,
);
}
/// The line the pointer last hovered, if any.
pub fn active_line(&self) -> Option<usize> {
self.active_line
}
/// Selects a range, endpoints in lines and characters.
pub fn select_range(
&mut self,
start: SelectionPoint,
end: SelectionPoint,
cx: &mut Context<Self>,
) {
self.selection = if start.earlier_than(&end) {
Some((start, end))
} else {
Some((end, start))
};
self.selecting = false;
cx.notify();
}
/// The selected range, endpoints in document order, when there is one.
pub fn selection(&self) -> Option<(SelectionPoint, SelectionPoint)> {
self.selection.map(|(anchor, head)| {
if anchor.earlier_than(&head) {
(anchor, head)
} else {
(head, anchor)
}
})
}
/// The selected text, or `None` when nothing is selected.
pub fn selected_text(&self) -> Option<String> {
let (start, end) = self.selection()?;
let lines: Vec<&str> = self.source.split('\n').collect();
let mut selected = Vec::new();
for row in start.row..=end.row.min(lines.len().saturating_sub(1)) {
let line_chars: Vec<char> = lines.get(row)?.chars().collect();
let start_col = if row == start.row {
start.col.min(line_chars.len())
} else {
0
};
let end_col = if row == end.row {
end.col.min(line_chars.len())
} else {
line_chars.len()
};
selected.push(line_chars[start_col..end_col].iter().collect::<String>());
}
(!selected.is_empty()).then(|| selected.join("\n"))
}
/// Overrides the accessibility label of the view.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Maps a window position to a point in the source.
fn position_at(
&self,
bounds: Bounds<Pixels>,
position: Point<Pixels>,
scroll_y: Pixels,
line_height: Pixels,
char_width: Pixels,
text_x: Pixels,
) -> SelectionPoint {
// Saturating so an empty document cannot invert the clamp.
let last_row = self.code.lines.len().saturating_sub(1);
let row = (((position.y - bounds.origin.y - scroll_y) / line_height).floor() as isize)
.clamp(0, last_row as isize) as usize;
let chars = self.code.lines.get(row).map_or(0, |line| {
line.spans
.iter()
.map(|span| span.text.chars().count())
.sum::<usize>()
});
let col = (((position.x - text_x) / char_width).round() as isize).clamp(0, chars as isize)
as usize;
SelectionPoint { row, col }
}
}
impl gpui::Focusable for CodeViewState {
fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
self.focus_handle.clone()
}
}
impl Render for CodeViewState {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let mono_font = theme.mono_font;
let text_size = theme.sizes.small.text_size;
let line_height = text_size * CODE_LINE_HEIGHT;
let char_width = text_size * MONO_ADVANCE_RATIO;
let root_font_size = theme.root_font_size;
let id = self.id.clone();
let state = cx.entity();
let line_count = self.code.lines.len();
let selection = self.selection();
let gutter_width = CODE_GUTTER_WIDTH;
let bounds_cell: std::rc::Rc<std::cell::RefCell<Option<Bounds<Pixels>>>> =
std::rc::Rc::new(std::cell::RefCell::new(None));
let rows = uniform_list((id.clone(), "rows"), line_count, {
let id = id.clone();
let state = state.clone();
move |range, _window, cx| {
let code = state.read(cx);
let active_line = code.active_line;
let theme = cx.theme();
range
.map(|line_ix| {
render_row(
code,
&id,
line_ix,
active_line == Some(line_ix),
selection,
theme.mono_font,
theme.colors,
theme.ramps,
theme.sizes.small.text_size,
line_height,
cx,
)
})
.collect()
}
})
.track_scroll(&self.handle)
.h_full()
.w_full();
div()
.id((id.clone(), "view"))
.relative()
.size_full()
.text_size(text_size)
.font_family(mono_font)
.text_color(colors.foreground)
.key_context(CODE_VIEW_CONTEXT)
.track_focus(&self.focus_handle)
.on_mouse_down(MouseButton::Left, {
let state = state.clone();
let bounds_cell = bounds_cell.clone();
move |event: &MouseDownEvent, window: &mut Window, cx: &mut App| {
window.focus(&state.read(cx).focus_handle.clone(), cx);
let bounds = bounds_cell.borrow();
let Some(bounds) = bounds.as_ref() else {
return;
};
let text_x = bounds.origin.x + gutter_width + root_font_size;
let point = {
let code = state.read(cx);
code.position_at(
*bounds,
event.position,
ScrollbarHandle::offset(&code.handle).y,
line_height,
char_width,
text_x,
)
};
state.update(cx, |state, cx| {
if event.modifiers.shift {
if let Some((anchor, _)) = state.selection {
state.selection = Some((anchor, point));
} else {
state.selection = Some((point, point));
}
} else {
state.selection = Some((point, point));
}
state.selecting = true;
cx.notify();
});
}
})
.on_mouse_move({
let state = state.clone();
let bounds_cell = bounds_cell.clone();
move |event: &MouseMoveEvent, _window: &mut Window, cx: &mut App| {
let bounds = bounds_cell.borrow();
let Some(bounds) = bounds.as_ref() else {
return;
};
let text_x = bounds.origin.x + gutter_width + root_font_size;
let point = {
let code = state.read(cx);
code.position_at(
*bounds,
event.position,
ScrollbarHandle::offset(&code.handle).y,
line_height,
char_width,
text_x,
)
};
let selecting = state.read(cx).selecting;
if selecting {
let changed = state
.read(cx)
.selection
.map(|(_, head)| head != point)
.unwrap_or(true);
if changed {
state.update(cx, |state, cx| {
if let Some((anchor, _)) = state.selection {
state.selection = Some((anchor, point));
}
cx.notify();
});
}
return;
}
let changed = state.read(cx).active_line != Some(point.row);
if changed {
state.update(cx, |state, cx| {
state.active_line = Some(point.row);
cx.notify();
});
}
}
})
.on_mouse_up(MouseButton::Left, {
let state = state.clone();
move |_: &MouseUpEvent, _window: &mut Window, cx: &mut App| {
if state.read(cx).selecting {
state.update(cx, |state, cx| {
state.selecting = false;
cx.notify();
});
}
}
})
.on_action({
let state = state.clone();
move |_: &Copy, _window, cx| {
if let Some(text) = state.read(cx).selected_text() {
cx.write_to_clipboard(ClipboardItem::new_string(text));
}
}
})
.child(
canvas(
{
let bounds_cell = bounds_cell.clone();
move |bounds, _window, _cx| {
*bounds_cell.borrow_mut() = Some(bounds);
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
.child(rows)
.child(
Scrollbar::vertical((self.id.clone(), "v-scrollbar"), self.handle.clone())
.visibility(ScrollbarVisibility::Platform),
)
.when_some(self.a11y_label.clone(), |view, label| {
view.aria_label(label)
})
}
}
#[allow(clippy::too_many_arguments)]
fn render_row(
code: &CodeViewState,
id: &ElementId,
line_ix: usize,
active: bool,
selection: Option<(SelectionPoint, SelectionPoint)>,
mono_font: &'static str,
colors: ColorTokens,
ramps: Ramps,
text_size: Pixels,
line_height: Pixels,
cx: &App,
) -> gpui::AnyElement {
let line = code.code().lines.get(line_ix);
let mut text = String::new();
for span in line.map_or(&[][..], |line| line.spans.as_slice()) {
text.push_str(&span.text);
}
let char_count = text.chars().count();
let mut roles = vec![Role::Text; char_count];
let mut offset = 0usize;
for span in line.map_or(&[][..], |line| line.spans.as_slice()) {
let chars = span.text.chars().count();
for slot in &mut roles[offset..offset + chars] {
*slot = span.role;
}
offset += chars;
}
let mut selected = vec![false; char_count];
if let Some((start, end)) = selection
&& line_ix >= start.row
&& line_ix <= end.row
{
let start_col = if line_ix == start.row {
start.col.min(char_count)
} else {
0
};
let end_col = if line_ix == end.row {
end.col.min(char_count)
} else {
char_count
};
for slot in &mut selected[start_col..end_col] {
*slot = true;
}
}
let mut highlights: Vec<(std::ops::Range<usize>, HighlightStyle)> = Vec::new();
let mut run_start = 0usize;
let mut run_end = 0usize;
let mut run_role = Role::Text;
let mut run_selected = false;
for (char_ix, (byte_ix, character)) in text.char_indices().enumerate() {
let fresh = char_ix == 0 || roles[char_ix] != run_role || selected[char_ix] != run_selected;
if fresh {
if char_ix > 0 {
highlights.push((
run_start..run_end,
run_role.run_style(run_selected, colors, ramps),
));
}
run_start = byte_ix;
run_role = roles[char_ix];
run_selected = selected[char_ix];
}
run_end = byte_ix + character.len_utf8();
}
if run_end > run_start || !text.is_empty() {
highlights.push((
run_start..run_end,
run_role.run_style(run_selected, colors, ramps),
));
}
let style = TextStyle {
color: colors.foreground,
font_family: SharedString::from(mono_font),
font_size: text_size.into(),
line_height: line_height.into(),
white_space: gpui::WhiteSpace::Nowrap,
..Default::default()
};
div()
.debug_selector(move || format!("{id}-row-{line_ix}"))
.id(("code-row", line_ix))
.w_full()
.h(line_height)
.flex()
.items_center()
.overflow_hidden()
.when(active, |row| {
row.bg(Hsla {
a: colors.muted.a * WASH_ALPHA_SOFT,
..colors.muted
})
})
.child(
gutter_cell(
cx,
if active {
colors.foreground
} else {
colors.muted_foreground
},
format!("{}", line_ix + 1),
)
.justify_end()
.pr_2()
.whitespace_nowrap(),
)
.child(
div()
.flex_1()
.min_w_0()
.ml_4()
.overflow_hidden()
.whitespace_nowrap()
.child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)),
)
.into_any_element()
}
+787
View File
@@ -0,0 +1,787 @@
//! Renders an editable field that filters its options while typing.
//!
//! 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<ComboboxState<&'static str>> {
//! 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 gpui::prelude::FluentBuilder;
use gpui::{
App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding,
MouseButton, MouseDownEvent, ParentElement as _, Pixels, Render, Role, ScrollHandle,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Task,
Window, actions, anchored, canvas, deferred, div, point, px,
};
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 _, COMBOBOX_MIN_WIDTH, COMBOBOX_WIDTH, POPUP_MAX_HEIGHT, Size};
actions!(
combobox,
[HighlightNext, HighlightPrevious, Choose, Dismiss]
);
/// The key context the combobox's wrapper declares.
pub const COMBOBOX_CONTEXT: &str = "Combobox";
/// Binds the combobox's four keys: down, up, enter, and escape.
pub fn bind_combobox_keys(cx: &mut App) {
let under_input = Some("Combobox > Input");
cx.bind_keys([
KeyBinding::new("down", HighlightNext, under_input),
KeyBinding::new("up", HighlightPrevious, under_input),
KeyBinding::new("enter", Choose, under_input),
KeyBinding::new("escape", Dismiss, under_input),
KeyBinding::new("down", HighlightNext, Some(COMBOBOX_CONTEXT)),
KeyBinding::new("up", HighlightPrevious, Some(COMBOBOX_CONTEXT)),
KeyBinding::new("enter", Choose, Some(COMBOBOX_CONTEXT)),
KeyBinding::new("escape", Dismiss, Some(COMBOBOX_CONTEXT)),
]);
}
/// What happens to text that matches no option when the field loses focus.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum UnmatchedText {
/// Restore the chosen option's label, or empty the field.
#[default]
Revert,
/// Leave the text and leave the value cleared.
Keep,
/// Hand the text to the `on_create` handler.
Create,
}
/// An option for a [`Combobox`]: a value and the label the filter matches on.
pub type ComboboxOption<T> = (T, SharedString);
/// Reports the value whenever it changes.
pub type ComboboxHandler<T> = Rc<dyn Fn(Option<T>, &mut Window, &mut App)>;
/// Receives unmatched text when the field loses focus in create mode.
pub type ComboboxCreateHandler = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
/// Decides which options survive a query: the query, the value, the label.
pub type ComboboxFilter<T> = Rc<dyn Fn(&str, &T, &SharedString) -> bool>;
/// Builder for a combobox, consumed by [`ComboboxState::new`].
#[must_use]
pub struct Combobox<T>
where
T: Clone + PartialEq + 'static,
{
id: ElementId,
name: SharedString,
options: Vec<ComboboxOption<T>>,
selected: Option<T>,
placeholder: SharedString,
on_change: Option<ComboboxHandler<T>>,
on_create: Option<ComboboxCreateHandler>,
filter: Option<ComboboxFilter<T>>,
unmatched: UnmatchedText,
size: Size,
style: StyleRefinement,
}
impl<T> Combobox<T>
where
T: Clone + PartialEq + 'static,
{
pub fn new<I, N>(id: I, name: N, options: Vec<ComboboxOption<T>>) -> Self
where
I: Into<ElementId>,
N: Into<SharedString>,
{
Self {
id: id.into(),
name: name.into(),
options,
selected: None,
placeholder: SharedString::from("Select..."),
on_change: None,
on_create: None,
filter: None,
unmatched: UnmatchedText::default(),
size: Size::default(),
style: StyleRefinement::default(),
}
}
/// Sets the initially selected value; its label seeds the field.
pub fn selected<S>(mut self, selected: S) -> Self
where
S: Into<Option<T>>,
{
self.selected = selected.into();
self
}
/// Sets the text shown while the field is empty.
pub fn placeholder<L>(mut self, placeholder: L) -> Self
where
L: Into<SharedString>,
{
self.placeholder = placeholder.into();
self
}
/// Reports the value whenever it changes.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(Option<T>, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Hands unmatched text to `handler` when the field loses focus.
pub fn on_create<F>(mut self, handler: F) -> Self
where
F: Fn(SharedString, &mut Window, &mut App) + 'static,
{
self.on_create = Some(Rc::new(handler));
self.unmatched = UnmatchedText::Create;
self
}
/// Sets the matcher that decides which options survive a query.
pub fn filter<F>(mut self, filter: F) -> Self
where
F: Fn(&str, &T, &SharedString) -> bool + 'static,
{
self.filter = Some(Rc::new(filter));
self
}
/// Leaves unmatched text in the field on blur.
pub fn keep_unmatched_text(mut self) -> Self {
self.unmatched = UnmatchedText::Keep;
self
}
/// Overrides the accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.name = label.into();
self
}
}
/// Style refinements set the combobox's width.
impl<T> Styled for Combobox<T>
where
T: Clone + PartialEq + 'static,
{
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
// Combobox is a data builder, not an element, adopt the combinators explicitly.
impl<T> FluentBuilder for Combobox<T> 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<ComboboxState<&'static str>> {
/// # 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<T>
where
T: Clone + PartialEq + 'static,
{
id: ElementId,
name: SharedString,
placeholder: SharedString,
options: Vec<ComboboxOption<T>>,
/// The chosen value. `None` while the text names nothing.
selected: Option<T>,
query: Entity<InputState>,
/// Indices into `options` that survived the filter, in popup row order.
visible: Vec<usize>,
/// The highlighted popup *row*, when the popup is open.
highlight: Option<usize>,
on_change: Option<ComboboxHandler<T>>,
on_create: Option<ComboboxCreateHandler>,
filter: ComboboxFilter<T>,
unmatched: UnmatchedText,
size: Size,
/// Width refinements from the builder, applied to the wrapper each render.
style: StyleRefinement,
/// Handler reports in flight; held so they die with the state.
tasks: Vec<Task<()>>,
/// Keeps the query-event subscription tied to the state's lifetime.
_subscription: Subscription,
}
impl<T> Sizable for ComboboxState<T>
where
T: Clone + PartialEq + 'static,
{
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl<T> ComboboxState<T>
where
T: Clone + PartialEq + 'static,
{
/// Builds the state, its query field, and the subscription tying them.
pub fn new(combobox: Combobox<T>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let query = InputState::new(cx);
// The field starts showing the label of whatever was chosen,
// so text and value agree from the first frame.
if let Some(selected) = &combobox.selected
&& let Some((_, label)) = combobox.options.iter().find(|(value, _)| value == selected)
{
let label = label.to_string();
query.update(cx, |query, cx| query.set_value_silent(label, window, cx));
}
let subscription =
cx.subscribe_in(&query, window, |state, _, event, window, cx| match event {
InputStateEvent::Focused => state.query_focused(window, cx),
InputStateEvent::TextChanged => state.text_changed(window, cx),
InputStateEvent::Blurred => state.blurred(window, cx),
_ => {}
});
let visible = (0..combobox.options.len()).collect();
Self {
id: combobox.id,
name: combobox.name,
placeholder: combobox.placeholder,
options: combobox.options,
selected: combobox.selected,
query,
visible,
highlight: None,
on_change: combobox.on_change,
on_create: combobox.on_create,
filter: combobox.filter.unwrap_or_else(|| {
Rc::new(|query, _value, label| label.to_lowercase().contains(&query.to_lowercase()))
}),
unmatched: combobox.unmatched,
size: combobox.size,
style: combobox.style,
tasks: Vec::new(),
_subscription: subscription,
}
}
/// The text currently in the field.
pub fn text(&self, cx: &App) -> String {
self.query.read(cx).value().to_string()
}
/// Focuses the query field.
pub fn focus(&self, window: &mut Window, cx: &mut App) {
window.focus(&self.query.read(cx).focus_handle(), cx);
}
/// Whether the option list is showing.
pub fn is_open(&self) -> bool {
self.highlight.is_some()
}
/// The chosen value.
pub fn selected(&self) -> Option<&T> {
self.selected.as_ref()
}
/// Replaces the value; reports it when it actually changed.
pub fn set_selected(&mut self, value: Option<T>, window: &mut Window, cx: &mut Context<Self>) {
self.set_value(value, window, cx);
}
/// Replaces the choice list and re-runs the current filter.
pub fn set_options(&mut self, options: Vec<ComboboxOption<T>>, cx: &mut Context<Self>) {
self.options = options;
let query = self.query.read(cx).value().to_string();
self.refilter(&query);
cx.notify();
}
/// A copy of the current choice list.
pub fn options_snapshot(&self) -> Vec<ComboboxOption<T>> {
self.options.clone()
}
/// The label of the chosen option, if there is one.
fn selected_label(&self) -> Option<SharedString> {
let selected = self.selected.as_ref()?;
self.options
.iter()
.find(|(value, _)| value == selected)
.map(|(_, label)| label.clone())
}
/// Recomputes `visible` for `query` and clamps the highlight onto it.
fn refilter(&mut self, query: &str) {
let filter = self.filter.clone();
self.visible = self
.options
.iter()
.enumerate()
.filter(|(_, (value, label))| filter(query, value, label))
.map(|(index, _)| index)
.collect();
self.highlight = self.highlight.filter(|row| *row < self.visible.len());
}
fn query_text(&self, cx: &Context<Self>) -> String {
self.query.read(cx).value().trim().to_string()
}
/// Sets the value and reports it, including when it is `None`.
fn set_value(&mut self, value: Option<T>, window: &mut Window, cx: &mut Context<Self>) {
if self.selected == value {
return;
}
self.selected = value.clone();
if let Some(on_change) = self.on_change.clone() {
let value = value.clone();
let task = window.spawn(cx, async move |cx| {
cx.update(|window, cx| on_change(value, window, cx))
.log_err();
});
self.tasks.push(task);
}
cx.notify();
}
/// Commits the option at popup *row*.
fn choose_row(&mut self, row: usize, window: &mut Window, cx: &mut Context<Self>) {
let Some(option_index) = self.visible.get(row).copied() else {
return;
};
let Some((value, label)) = self.options.get(option_index).cloned() else {
return;
};
self.query.update(cx, |query, cx| {
query.set_value_silent(label.to_string(), window, cx)
});
self.highlight = None;
self.refilter("");
self.set_value(Some(value), window, cx);
}
/// Typing: re-filter, open, reset the highlight, and clear the value.
fn text_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let query = self.query_text(cx);
self.refilter(&query);
self.highlight = Some(0);
self.set_value(None, window, cx);
cx.notify();
}
/// Gaining focus.
fn query_focused(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
if self.selected.is_some() {
return;
}
self.refilter("");
self.highlight = Some(0);
cx.notify();
}
/// Losing focus. [`UnmatchedText`] decides what the text becomes.
fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.highlight = None;
let text = self.query_text(cx);
if self.selected_label().as_deref() == Some(text.as_str()) {
cx.notify();
return;
}
match self.unmatched {
UnmatchedText::Revert => {
let restored = self.selected_label().unwrap_or_default().to_string();
self.query
.update(cx, |query, cx| query.set_value_silent(restored, window, cx));
}
UnmatchedText::Keep => {}
UnmatchedText::Create => {
if !text.is_empty()
&& let Some(on_create) = self.on_create.clone()
{
let text = SharedString::from(text);
let task = window.spawn(cx, async move |cx| {
cx.update(|window, cx| on_create(text, window, cx))
.log_err();
});
self.tasks.push(task);
}
}
}
cx.notify();
}
/// Down and Up over the visible rows.
fn move_highlight(&mut self, delta: i32, cx: &mut Context<Self>) {
if self.visible.is_empty() {
return;
}
let count = self.visible.len();
let current = self.highlight.filter(|row| *row < count);
let next = match current {
Some(row) => match row.checked_add_signed(isize::try_from(delta).unwrap_or(0)) {
Some(next) if next < count => next,
Some(_) => 0,
None => count - 1,
},
None => {
if delta > 0 {
0
} else {
count - 1
}
}
};
self.highlight = Some(next);
cx.notify();
}
/// Enter. Commits the highlighted row.
fn choose(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(row) = self.highlight else {
cx.propagate();
return;
};
self.choose_row(row, window, cx);
}
/// Escape. Closes the picker.
fn dismiss(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
if self.highlight.is_none() {
cx.propagate();
return;
}
self.highlight = None;
cx.notify();
}
}
impl<T> Render for ComboboxState<T>
where
T: Clone + PartialEq + 'static,
{
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (metrics, colors, radius, panel_border, shadows) = {
let theme = cx.theme();
let metrics = theme.sizes.resolve(self.size);
(
metrics,
theme.colors,
theme.radius,
theme.colors.border,
theme.elevations.popover.shadows(),
)
};
let icon_size = metrics.dense_icon_size;
let id = self.id.clone();
let state = cx.entity();
let open = self.highlight.is_some();
let chevron = h_flex()
.id((id.clone(), "chevron"))
.cursor_pointer()
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click({
let state = state.clone();
move |_, window, cx| {
let focus = state.read(cx).query.read(cx).focus_handle();
window.focus(&focus, cx);
state.update(cx, |state, cx| {
if state.highlight.is_some() {
state.highlight = None;
} else {
if state.selected.is_some() {
state.refilter("");
} else {
let query = state.query.read(cx).value().to_string();
state.refilter(&query);
}
state.highlight = Some(0);
}
cx.notify();
});
}
})
.child(
icon(IconRole::ChevronDown)
.size(icon_size)
.color(colors.muted_foreground),
);
let wrapper_bounds: Rc<RefCell<Option<Bounds<Pixels>>>> = Rc::new(RefCell::new(None));
div()
.id(id.clone())
.key_context(COMBOBOX_CONTEXT)
.relative()
.w(COMBOBOX_WIDTH)
.min_w(COMBOBOX_MIN_WIDTH)
.refine_style(&self.style)
.role(Role::ComboBox)
.aria_expanded(open)
.aria_label(self.name.clone())
.on_action({
let state = state.clone();
move |_: &HighlightNext, _window, cx| {
state.update(cx, |state, cx| state.move_highlight(1, cx));
}
})
.on_action({
let state = state.clone();
move |_: &HighlightPrevious, _window, cx| {
state.update(cx, |state, cx| state.move_highlight(-1, cx));
}
})
.on_action({
let state = state.clone();
move |_: &Choose, window, cx| {
state.update(cx, |state, cx| state.choose(window, cx));
}
})
.on_action({
let state = state.clone();
move |_: &Dismiss, _window, cx| {
state.update(cx, |state, cx| state.dismiss(_window, cx));
}
})
.child(
canvas(
{
let cell = wrapper_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
|_, _, _window, _cx| {},
)
.absolute()
.inset_0(),
)
.child(
Input::new((id.clone(), "query"), self.query.clone())
.placeholder(self.placeholder.clone())
.placeholder_when_focused(true)
.with_size(self.size),
)
.child(
h_flex()
.absolute()
.right(metrics.dense_padding_x)
.top((metrics.input_height - icon_size) / 2.)
.child(chevron),
)
.when(open, |wrapper| {
let rows: Vec<gpui::AnyElement> = self
.visible
.iter()
.enumerate()
.map(|(row, option_index)| {
let Some((value, label)) = self.options.get(*option_index) else {
return div().into_any_element();
};
let highlighted = self.highlight == Some(row);
let checked = self.selected.as_ref() == Some(value);
let state = state.clone();
let row_index = row;
div()
.id(("option", *option_index))
.debug_selector({
let id = id.clone();
move || format!("{id}-option-{row}")
})
.role(Role::ListBoxOption)
.aria_label(label.clone())
.flex()
.items_center()
.gap_2()
.px_2()
.py_1()
.min_h(metrics.control_height)
.rounded(radius.sm)
.when(highlighted, |row| row.bg(colors.muted))
.when(!highlighted, |row| row.hover(|row| row.bg(colors.muted)))
.on_mouse_move({
let state = state.clone();
move |_, _window, cx| {
if state.read(cx).highlight != Some(row_index) {
state.update(cx, |state, cx| {
state.highlight = Some(row_index);
cx.notify();
});
}
}
})
.on_click({
let state = state.clone();
move |_, window, cx| {
state.update(cx, |state, cx| {
state.choose_row(row_index, window, cx)
});
}
})
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label.clone()),
)
.when(checked, |row| {
row.child(
icon(IconRole::Check)
.size(icon_size)
.color(colors.foreground),
)
})
.into_any_element()
})
.collect();
let rows: gpui::AnyElement = if rows.is_empty() {
div()
.px_2()
.py_1()
.text_size(metrics.caption_size)
.text_color(colors.muted_foreground)
.child("No matches")
.into_any_element()
} else {
let scroll = window.use_keyed_state((id.clone(), "rows-scroll"), cx, |_, _| {
ScrollHandle::new()
});
ScrollArea::new((id.clone(), "rows"))
.handle(scroll.read(cx).clone())
.axes(crate::components::scroll_area::ScrollAxes::Vertical)
.max_h(POPUP_MAX_HEIGHT)
.children(rows)
.into_any_element()
};
let panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>> = Rc::new(RefCell::new(None));
let popup_width = wrapper_bounds
.borrow()
.map(|bounds| bounds.size.width)
.unwrap_or(COMBOBOX_WIDTH);
let panel = v_flex()
.id((id.clone(), "panel"))
.debug_selector({
let id = id.clone();
move || format!("{id}-panel")
})
.w(popup_width)
.p_1()
.bg(colors.surface)
.text_color(colors.foreground)
.rounded(radius.overlay)
.border_1()
.border_color(panel_border)
.shadow(shadows)
.overflow_hidden()
.child(rows)
.child(
canvas(
{
let cell = panel_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
{
let state = state.clone();
let panel_bounds = panel_bounds.clone();
let wrapper_bounds = wrapper_bounds.clone();
move |_, _, window, _cx| {
window.on_mouse_event({
let state = state.clone();
let panel_bounds = panel_bounds.clone();
let wrapper_bounds = wrapper_bounds.clone();
move |event: &MouseDownEvent, phase, _window, cx| {
if phase != gpui::DispatchPhase::Bubble {
return;
}
let on_panel =
panel_bounds.borrow().is_some_and(|bounds| {
bounds.contains(&event.position)
});
let on_wrapper =
wrapper_bounds.borrow().is_some_and(|bounds| {
bounds.contains(&event.position)
});
if on_panel || on_wrapper {
return;
}
state.update(cx, |state, cx| {
state.highlight = None;
cx.notify();
});
}
});
}
},
)
.absolute()
.inset_0(),
);
wrapper.child(
deferred(anchored().offset(point(px(0.), px(4.))).child(panel))
.with_priority(OVERLAY_LAYER),
)
})
}
}
+569
View File
@@ -0,0 +1,569 @@
//! 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<CommandPaletteState> {
//! # 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 gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, App, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding,
MouseButton, ParentElement as _, Render, Role, ScrollHandle, SharedString,
StatefulInteractiveElement as _, StyleRefinement, Styled as _, Subscription, Window, actions,
canvas, deferred, div, relative,
};
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,
[HighlightNext, HighlightPrevious, Choose, Dismiss]
);
/// The key context the palette's panel declares.
pub const COMMAND_PALETTE_CONTEXT: &str = "CommandPalette";
/// Binds the palette's four keys: down, up, enter, and escape.
pub fn bind_command_palette_keys(cx: &mut App) {
let under_input = Some("CommandPalette > Input");
cx.bind_keys([
KeyBinding::new("down", HighlightNext, under_input),
KeyBinding::new("up", HighlightPrevious, under_input),
KeyBinding::new("enter", Choose, under_input),
KeyBinding::new("escape", Dismiss, under_input),
KeyBinding::new("down", HighlightNext, Some(COMMAND_PALETTE_CONTEXT)),
KeyBinding::new("up", HighlightPrevious, Some(COMMAND_PALETTE_CONTEXT)),
KeyBinding::new("enter", Choose, Some(COMMAND_PALETTE_CONTEXT)),
KeyBinding::new("escape", Dismiss, Some(COMMAND_PALETTE_CONTEXT)),
]);
}
/// A command the palette can run: a stable id and the label the matcher sees.
#[derive(Clone)]
#[must_use]
pub struct Command {
/// The stable domain id handed to `on_execute`.
pub id: SharedString,
/// What the matcher matches and the row shows.
pub label: SharedString,
/// Gray text on the row's right edge, e.g. the keybinding.
pub hint: Option<SharedString>,
/// Leading glyph shown before the label.
pub icon: Option<Icon>,
}
impl Command {
/// Creates a command without a hint or icon.
pub fn new<I, L>(id: I, label: L) -> Self
where
I: Into<SharedString>,
L: Into<SharedString>,
{
Self {
id: id.into(),
label: label.into(),
hint: None,
icon: None,
}
}
/// Shows an icon before the label.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Sets the row's right-edge hint.
pub fn hint<H>(mut self, hint: H) -> Self
where
H: Into<SharedString>,
{
self.hint = Some(hint.into());
self
}
}
// Command is a data builder, not an element, adopt the combinators explicitly.
impl FluentBuilder for Command {}
/// Filters and ranks the commands for a query.
pub type CommandMatcher = Rc<dyn Fn(&str, &[Command]) -> Vec<Command>>;
/// Runs the chosen command.
pub type CommandHandler = Rc<dyn Fn(&Command, &mut Window, &mut App)>;
/// Builder for a command palette, consumed by [`CommandPaletteState::new`].
#[must_use]
pub struct CommandPalette {
id: ElementId,
name: SharedString,
placeholder: SharedString,
commands: Vec<Command>,
matcher: CommandMatcher,
on_execute: Option<CommandHandler>,
style: StyleRefinement,
}
impl CommandPalette {
/// Creates the builder with a caller-owned matcher that decides what matches.
pub fn new<I, M>(id: I, commands: Vec<Command>, matcher: M) -> Self
where
I: Into<ElementId>,
M: Fn(&str, &[Command]) -> Vec<Command> + 'static,
{
Self {
id: id.into(),
name: SharedString::from("Command palette"),
placeholder: SharedString::from("Type a command..."),
commands,
matcher: Rc::new(matcher),
on_execute: None,
style: StyleRefinement::default(),
}
}
/// Sets the text shown while the query is empty.
pub fn placeholder<L>(mut self, placeholder: L) -> Self
where
L: Into<SharedString>,
{
self.placeholder = placeholder.into();
self
}
/// Runs `handler` with the chosen command, then closes the palette.
pub fn on_execute<F>(mut self, handler: F) -> Self
where
F: Fn(&Command, &mut Window, &mut App) + 'static,
{
self.on_execute = Some(Rc::new(handler));
self
}
/// Overrides the accessibility label of the panel.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.name = label.into();
self
}
}
// CommandPalette is a data builder, not an element, adopt the combinators explicitly.
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<CommandPaletteState> {
/// # 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,
placeholder: SharedString,
commands: Vec<Command>,
matcher: CommandMatcher,
on_execute: Option<CommandHandler>,
style: StyleRefinement,
query: Entity<InputState>,
/// The commands the matcher returned for the query, in display order.
matches: Vec<Command>,
/// The highlighted row, when the palette is open.
highlight: Option<usize>,
open: bool,
/// Keeps the query-event subscription tied to the state's lifetime.
_subscription: Subscription,
}
impl CommandPaletteState {
/// Builds the state, its query field, and the subscription tying them.
pub fn new(palette: CommandPalette, window: &mut Window, cx: &mut Context<Self>) -> Self {
let query = InputState::new(cx);
let subscription = cx.subscribe_in(&query, window, |state, _, event, window, cx| {
if event == &InputStateEvent::TextChanged {
state.text_changed(window, cx);
}
});
let matches = (palette.matcher)("", &palette.commands);
Self {
id: palette.id,
name: palette.name,
placeholder: palette.placeholder,
commands: palette.commands,
matcher: palette.matcher,
on_execute: palette.on_execute,
style: palette.style,
query,
matches,
highlight: None,
open: false,
_subscription: subscription,
}
}
/// Opens the palette: fresh query, fresh matches, focus in the field.
pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.open {
self.focus(window, cx);
return;
}
self.open = true;
self.query.update(cx, |query, cx| {
query.set_value_silent("", window, cx);
});
self.refilter("");
self.highlight = (!self.matches.is_empty()).then_some(0);
self.focus(window, cx);
cx.notify();
}
/// Closes the palette.
pub fn close(&mut self, cx: &mut Context<Self>) {
if !self.open {
return;
}
self.open = false;
self.highlight = None;
cx.notify();
}
/// Opens the palette when closed, closes it when open.
pub fn toggle(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.open {
self.close(cx);
} else {
self.open(window, cx);
}
}
/// Whether the palette is showing.
pub fn is_open(&self) -> bool {
self.open
}
/// Replaces the command list and re-runs the current query's matches.
pub fn set_commands(&mut self, commands: Vec<Command>, cx: &mut Context<Self>) {
self.commands = commands;
let query = self.query.read(cx).value().to_string();
self.refilter(&query);
cx.notify();
}
/// Focuses the query field.
pub fn focus(&self, window: &mut Window, cx: &mut App) {
window.focus(&self.query.read(cx).focus_handle(), cx);
}
/// Asks the caller's matcher who matches, and clamps the highlight.
fn refilter(&mut self, query: &str) {
self.matches = (self.matcher)(query, &self.commands);
if let Some(highlight) = self.highlight {
self.highlight = (highlight < self.matches.len()).then_some(highlight);
}
}
/// Typing: fresh matches, highlight the first row.
fn text_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
let query = self.query.read(cx).value().to_string();
self.refilter(&query);
self.highlight = (!self.matches.is_empty()).then_some(0);
cx.notify();
}
/// Down and Up over the matched rows, wrapping at the ends.
fn move_highlight(&mut self, delta: i32, cx: &mut Context<Self>) {
if self.matches.is_empty() {
return;
}
let count = self.matches.len();
let next = match self.highlight {
Some(row) => match row.checked_add_signed(isize::try_from(delta).unwrap_or(0)) {
Some(next) if next < count => next,
Some(_) => 0,
None => count - 1,
},
None if delta > 0 => 0,
None => count - 1,
};
self.highlight = Some(next);
cx.notify();
}
/// Enter. Runs the highlighted command and closes.
fn choose(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(row) = self.highlight else {
cx.propagate();
return;
};
self.choose_row(row, window, cx);
}
/// Runs the command at a row and closes.
fn choose_row(&mut self, row: usize, window: &mut Window, cx: &mut Context<Self>) {
let Some(command) = self.matches.get(row) else {
return;
};
let command = command.clone();
if let Some(on_execute) = self.on_execute.clone() {
on_execute(&command, window, cx);
}
self.close(cx);
}
/// Escape. Closes the palette.
fn dismiss(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
if !self.open {
cx.propagate();
return;
}
self.close(cx);
}
}
impl Render for CommandPaletteState {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
if !self.open {
return div().into_any_element();
}
let (colors, radius, metrics, panel_border, shadows, titlebar_height) = {
let theme = cx.theme();
(
theme.colors,
theme.radius,
theme.sizes.resolve(Size::default()),
theme.colors.border,
theme.elevations.dialog.shadows(),
theme.titlebar_height,
)
};
let id = self.id.clone();
let state = cx.entity();
let query_focus = self.query.read(cx).focus_handle();
let rows: Vec<AnyElement> = self
.matches
.iter()
.enumerate()
.map(|(row, command)| {
let highlighted = self.highlight == Some(row);
let state = state.clone();
let row_index = row;
h_flex()
.id((ElementId::from(command.id.clone()), "command"))
.debug_selector({
let id = id.clone();
move || format!("{id}-command-{row}")
})
.role(Role::ListBoxOption)
.aria_label(command.label.clone())
.gap_2()
.px_2()
.py_1()
.min_h(metrics.control_height)
.text_size(metrics.text_size)
.line_height(relative(1.0))
.rounded(radius.sm)
.when(highlighted, |row| row.bg(colors.muted))
.when(!highlighted, |row| row.hover(|row| row.bg(colors.muted)))
.on_mouse_move({
let state = state.clone();
move |_, _window, cx| {
if state.read(cx).highlight != Some(row_index) {
state.update(cx, |state, cx| {
state.highlight = Some(row_index);
cx.notify();
});
}
}
})
.on_click({
let state = state.clone();
move |_, window, cx| {
state.update(cx, |state, cx| state.choose_row(row_index, window, cx));
}
})
.when_some(command.icon.clone(), |row, icon| {
row.child(icon.size(metrics.icon_size).color(colors.foreground))
})
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(command.label.clone()),
)
.when_some(command.hint.clone(), |row, hint| {
row.child(
div()
.flex_shrink_0()
.text_size(metrics.caption_size)
.text_color(colors.muted_foreground)
.child(hint),
)
})
.into_any_element()
})
.collect();
let rows: AnyElement = if rows.is_empty() {
div()
.px_2()
.py_1()
.text_size(metrics.caption_size)
.text_color(colors.muted_foreground)
.child("No matches")
.into_any_element()
} else {
let scroll =
window.use_keyed_state((id.clone(), "rows-scroll"), cx, |_, _| ScrollHandle::new());
ScrollArea::new((id.clone(), "rows"))
.handle(scroll.read(cx).clone())
.axes(ScrollAxes::Vertical)
.max_h(POPUP_MAX_HEIGHT)
.children(rows)
.into_any_element()
};
let panel = v_flex()
.id((id.clone(), "panel"))
.debug_selector({
let id = id.clone();
move || format!("{id}-panel")
})
.key_context(COMMAND_PALETTE_CONTEXT)
.role(Role::Dialog)
.aria_label(self.name.clone())
.w_full()
.max_w(relative(0.6))
.p_2()
.gap_2()
.bg(colors.surface)
.text_color(colors.foreground)
.rounded(radius.overlay)
.border_1()
.border_color(panel_border)
.shadow(shadows)
.overflow_hidden()
.refine_style(&self.style)
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_action({
let state = state.clone();
move |_: &HighlightNext, _window, cx| {
state.update(cx, |state, cx| state.move_highlight(1, cx));
}
})
.on_action({
let state = state.clone();
move |_: &HighlightPrevious, _window, cx| {
state.update(cx, |state, cx| state.move_highlight(-1, cx));
}
})
.on_action({
let state = state.clone();
move |_: &Choose, window, cx| {
state.update(cx, |state, cx| state.choose(window, cx));
}
})
.on_action({
let state = state.clone();
move |_: &Dismiss, window, cx| {
state.update(cx, |state, cx| state.dismiss(window, cx));
}
})
.child(
Input::new((id.clone(), "query"), self.query.clone())
.placeholder(self.placeholder.clone()),
)
.child(rows)
.child(
canvas(|_, _, _| {}, {
let focus = query_focus.clone();
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
let scrim = div()
.absolute()
.inset_0()
.bg(colors.overlay)
.occlude()
.on_mouse_down(MouseButton::Left, {
let state = state.clone();
move |_, _window, cx| {
state.update(cx, |state, cx| state.close(cx));
cx.stop_propagation();
}
});
deferred(
div()
.absolute()
.inset_0()
.flex()
.justify_center()
.items_start()
.pt(titlebar_height)
.child(scrim)
.child(panel),
)
.with_priority(DIALOG_LAYER)
.into_any_element()
}
}
+232
View File
@@ -0,0 +1,232 @@
//! 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 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,
};
pub use crate::theme::Size;
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<T> {
/// Logs the error and yields the success value, if any.
fn log_err(self) -> Option<T>;
}
impl<T, E: std::fmt::Display> ResultLogErr<T> for Result<T, E> {
fn log_err(self) -> Option<T> {
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<E: Styled> 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<Pixels>>);
impl Global for AnchorBoundsRegistry {}
impl AnchorBoundsRegistry {
fn record(&mut self, window: WindowId, id: ElementId, bounds: Bounds<Pixels>) {
self.0.insert((window, id), bounds);
}
fn get(&self, window: WindowId, id: &ElementId) -> Option<Bounds<Pixels>> {
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<Bounds<Pixels>> {
cx.try_global::<AnchorBoundsRegistry>()
.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<Pixels>, &mut Window, &mut App) + 'static {
move |bounds, window, cx| {
let window_id = window.window_handle().window_id();
cx.default_global::<AnchorBoundsRegistry>()
.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<BoxShadow> {
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<usize>,
forward: bool,
) -> Option<usize> {
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<S>(selectable: &[usize], selected: Option<usize>, key: &str, select: S) -> bool
where
S: FnOnce(Option<usize>),
{
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<R>(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<dyn Fn(&mut gpui::App)>;
/// Deferred draw priority of window-modal surfaces; default layer 0 stays for in-flow chrome like resize handles.
pub const DIALOG_LAYER: usize = 1;
/// Deferred draw priority of floating panels, so controls inside a dialog open above it.
pub const OVERLAY_LAYER: usize = 2;
/// Deferred draw priority of passive notifications, so they stay visible over dialogs.
pub const TOAST_LAYER: usize = 3;
/// A component that can be told which size to render at.
pub trait Sizable: Sized {
/// Sets the size.
fn with_size(mut self, size: Size) -> Self {
self.apply_size(size);
self
}
/// Applies the size to the component's fields.
fn apply_size(&mut self, size: Size);
/// Sets `Size::XSmall`.
fn xsmall(self) -> Self
where
Self: Sized,
{
self.with_size(Size::XSmall)
}
/// Sets `Size::Small`.
fn small(self) -> Self
where
Self: Sized,
{
self.with_size(Size::Small)
}
/// Sets `Size::Large`.
fn large(self) -> Self
where
Self: Sized,
{
self.with_size(Size::Large)
}
}
+145
View File
@@ -0,0 +1,145 @@
//! 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,
ParentElement as _, RenderOnce, SharedString, StyleRefinement, Window, div,
};
use crate::components::common::StyledExt as _;
use crate::components::menu::{Menu, MenuItem};
/// Builds the element that opens the menu on right-click.
type TargetFn = Box<dyn Fn(&mut Window, &mut App) -> gpui::AnyElement>;
/// Builds the menu's items fresh each render.
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<MenuItem>>;
/// A menu that opens at the pointer when its target is right-clicked.
///
/// Open state is owned internally by design, unlike the controlled [`Menu`].
#[derive(IntoElement)]
#[must_use]
pub struct ContextMenu {
id: ElementId,
target: Option<TargetFn>,
items: Option<ItemsFn>,
a11y_label: Option<SharedString>,
style: StyleRefinement,
}
impl ContextMenu {
/// Creates a context menu over a target set with [`ContextMenu::target`].
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
target: None,
items: None,
a11y_label: None,
style: StyleRefinement::default(),
}
}
/// Sets the element that opens the menu on right-click.
pub fn target<F>(mut self, target: F) -> Self
where
F: Fn(&mut Window, &mut App) -> gpui::AnyElement + 'static,
{
self.target = Some(Box::new(target));
self
}
/// Sets the menu's items, built fresh each render.
pub fn items<F>(mut self, items: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<MenuItem> + 'static,
{
self.items = Some(Box::new(items));
self
}
/// Overrides the menu's accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl RenderOnce for ContextMenu {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let open = window.with_element_namespace(self.id.clone(), |window| {
window
.use_keyed_state("context-open", cx, |_, _| false)
.clone()
});
let at = window.with_element_namespace(self.id.clone(), |window| {
window
.use_keyed_state("context-position", cx, |_, _| None)
.clone()
});
let is_open = *open.read(cx);
let position = *at.read(cx);
let target = self.target;
let at_for_target = at.clone();
let trigger = move |window: &mut Window, cx: &mut App| {
let base = target
.as_ref()
.map(|build| build(window, cx))
.unwrap_or_else(|| div().into_any_element());
div()
.on_mouse_down(MouseButton::Right, {
let at = at_for_target.clone();
move |event: &MouseDownEvent, _window, cx| {
at.update(cx, |at, _| *at = Some(event.position));
}
})
.child(base)
.into_any_element()
};
let items = move |window: &mut Window, cx: &mut App| {
self.items
.as_ref()
.map(|build| build(window, cx))
.unwrap_or_default()
};
Menu::new(self.id)
.open(is_open)
.on_change(move |next, _window, cx| open.update(cx, |open, _| *open = next))
.open_at(position)
.trigger_button(MouseButton::Right)
.trigger(trigger)
.items(items)
.refine_style(&self.style)
.when_some(self.a11y_label.clone(), |menu, label| {
menu.accessibility_label(label)
})
}
}
+444
View File
@@ -0,0 +1,444 @@
//! Renders a centred panel over a dim scrim: the platform's modal.
//!
//! Give the dialog a [`DialogHandle`] to share its open state: dismissal
//! through escape, the scrim, or the close button updates every holder of a
//! clone, and they can open or close it in turn.
//!
//! # 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 std::cell::Cell;
use std::rc::Rc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
Animation, AnimationExt as _, AnyElement, App, DefiniteLength, ElementId,
InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, ParentElement as _,
RenderOnce, Role, ScrollHandle, SharedString, StatefulInteractiveElement as _, StyleRefinement,
Styled as _, Window, canvas, deferred, div, ease_out_quint, relative,
};
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::layout::h_flex;
use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH, TextRole, Typeset as _};
/// Requests the dialog's close: `false` closes.
pub type ChangeHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
type ContentFn = Box<dyn Fn(&mut Window, &mut App) -> AnyElement>;
type ActionsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<AnyElement>>;
/// The shared open state of a dialog; clone it to open or close from anywhere.
#[derive(Clone, Default)]
pub struct DialogHandle {
open: Rc<Cell<bool>>,
}
impl DialogHandle {
/// Creates a handle with the given open state.
pub fn new(open: bool) -> Self {
Self {
open: Rc::new(Cell::new(open)),
}
}
/// Whether the dialog is open.
pub fn is_open(&self) -> bool {
self.open.get()
}
/// Opens the dialog.
pub fn open(&self, cx: &mut App) {
self.set_open(true, cx);
}
/// Closes the dialog.
pub fn close(&self, cx: &mut App) {
self.set_open(false, cx);
}
fn set_open(&self, open: bool, cx: &mut App) {
if self.open.replace(open) != open {
cx.refresh_windows();
}
}
}
/// A centred panel over a dim scrim: the platform's modal.
#[derive(IntoElement)]
#[must_use]
pub struct Dialog {
id: ElementId,
open: bool,
alert: bool,
grain: bool,
title: Option<SharedString>,
a11y_label: Option<SharedString>,
handle: Option<DialogHandle>,
on_change: Option<ChangeHandler>,
close_on_escape: bool,
close_on_backdrop: bool,
content: Option<ContentFn>,
actions: Option<ActionsFn>,
min_width: Option<DefiniteLength>,
height: Option<DefiniteLength>,
style: StyleRefinement,
}
impl Dialog {
/// Creates a closed dialog.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
open: false,
alert: false,
grain: false,
title: None,
a11y_label: None,
handle: None,
on_change: None,
close_on_escape: true,
close_on_backdrop: true,
content: None,
actions: None,
min_width: None,
height: None,
style: StyleRefinement::default(),
}
}
/// Sets the initial open state; a handle overrides it.
pub fn open(mut self, open: bool) -> Self {
self.open = open;
self
}
/// Sets the alert mode.
pub fn alert(mut self, alert: bool) -> Self {
self.alert = alert;
self
}
/// Textures the scrim with a film-grain overlay.
pub fn grain(mut self, grain: bool) -> Self {
self.grain = grain;
self
}
/// Shares the dialog's open state.
pub fn handle(mut self, handle: DialogHandle) -> Self {
self.handle = Some(handle);
self
}
/// Sets whether escape dismisses the dialog.
pub fn close_on_escape(mut self, close: bool) -> Self {
self.close_on_escape = close;
self
}
/// Sets whether clicking the scrim dismisses the dialog.
pub fn close_on_backdrop(mut self, close: bool) -> Self {
self.close_on_backdrop = close;
self
}
/// Requests close through `on_change` on escape, scrim clicks, and the close button.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(bool, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Sets the dialog's title.
pub fn title<L>(mut self, title: L) -> Self
where
L: Into<SharedString>,
{
self.title = Some(title.into());
self
}
/// Sets the body content between the title and the actions.
pub fn content<F>(mut self, content: F) -> Self
where
F: Fn(&mut Window, &mut App) -> AnyElement + 'static,
{
self.content = Some(Box::new(content));
self
}
/// Sets the footer actions, laid out right-aligned in the given order.
pub fn actions<F>(mut self, actions: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<AnyElement> + 'static,
{
self.actions = Some(Box::new(actions));
self
}
/// Overrides the accessibility label of the panel.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Sets the panel's minimum width, defaults to the standard dialog width.
pub fn min_width<W>(mut self, width: W) -> Self
where
W: Into<DefiniteLength>,
{
self.min_width = Some(width.into());
self
}
/// Sets the panel's height, body content taller than the panel scrolls.
pub fn height<H>(mut self, height: H) -> Self
where
H: Into<DefiniteLength>,
{
self.height = Some(height.into());
self
}
}
impl gpui::Styled for Dialog {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Dialog {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let root = div().absolute().inset_0();
let open = self
.handle
.as_ref()
.map_or(self.open, DialogHandle::is_open);
if !open {
return root.into_any_element();
}
// A handle routes dismissal through the shared state
let on_change = self.on_change.clone().or_else(|| {
self.handle.clone().map(|handle| {
Rc::new(move |open: bool, _window: &mut Window, cx: &mut App| {
handle.set_open(open, cx);
}) as ChangeHandler
})
});
let (scrim_color, border, foreground, surface, radius, shadows, enter_duration) = {
let theme = cx.theme();
(
theme.colors.overlay,
theme.colors.border,
theme.colors.foreground,
theme.colors.surface,
theme.radius.overlay,
theme.elevations.dialog.shadows(),
theme.motion.overlay,
)
};
let role = if self.alert {
Role::AlertDialog
} else {
Role::Dialog
};
let label = self
.a11y_label
.clone()
.or_else(|| self.title.clone())
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
let alert = self.alert;
let close_on_escape = self.close_on_escape;
let close_on_backdrop = self.close_on_backdrop;
let show_close = !alert && on_change.is_some() && (close_on_escape || close_on_backdrop);
// Keyboard focus rides the panel across frames.
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));
let height = self.height;
let scroll = window
.use_keyed_state("dialog-content-scroll", cx, |_, _| ScrollHandle::new())
.read(cx)
.clone();
let panel = v_flex()
.id("dialog-panel")
.track_focus(&focus)
.role(role)
.aria_label(label)
.when_some(self.min_width, |panel, width| panel.min_w(width))
.when(self.min_width.is_none(), |panel| {
panel.min_w(DIALOG_MIN_WIDTH)
})
.max_w(relative(0.9))
.when_some(height, |panel, height| panel.h(height))
.bg(surface)
.text_color(foreground)
.rounded(radius)
.border_1()
.border_color(border)
.shadow(shadows)
.overflow_hidden()
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_key_down({
let on_change = on_change.clone();
move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "escape"
&& !alert
&& close_on_escape
&& let Some(on_change) = &on_change
{
on_change(false, window, cx);
}
cx.stop_propagation();
}
})
.when(self.title.is_some() || show_close, |panel| {
panel.child(
h_flex()
.h_12()
.px_2()
.gap_2()
.justify_between()
.child(div().size_5())
.when_some(self.title.clone(), |row, title| {
row.child(
div()
.flex_1()
.text_center()
.typeset(TextRole::Headline, cx)
.child(title),
)
})
.when(show_close, |row| {
row.child(
Button::new("dialog-close")
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.small()
.debug_selector(|| "dialog-close".to_string())
.accessibility_label("Close")
.on_click({
let on_change = on_change.clone();
move |_, window, cx| {
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
}
}),
)
}),
)
})
.when_some(content, |panel, content| {
panel.map(|this| {
if height.is_some() {
this.child(
ScrollArea::new("dialog-content")
.handle(scroll)
.flex_1()
.min_h_0()
.child(div().p_2().child(content)),
)
} else {
this.child(div().p_2().child(content))
}
})
})
.when_some(actions, |panel, actions| {
panel.child(
h_flex()
.px_2()
.h_12()
.justify_end()
.gap_2()
.children(actions),
)
})
.child(
canvas(|_, _, _| {}, {
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
let scrim = div()
.absolute()
.inset_0()
.bg(scrim_color)
.occlude()
.when(self.grain, |scrim| scrim.child(grain()))
.when(!alert && close_on_backdrop, |scrim| {
scrim.on_mouse_down(MouseButton::Left, {
let on_change = on_change.clone();
move |_, _window, cx| {
if let Some(on_change) = &on_change {
on_change(false, _window, cx);
}
cx.stop_propagation();
}
})
});
deferred(
root.flex()
.items_center()
.justify_center()
.p_4()
.refine_style(&self.style)
.child(scrim.with_animation(
"dialog-scrim-enter",
Animation::new(enter_duration).with_easing(ease_out_quint()),
|scrim, delta| scrim.opacity(delta),
))
.child(panel.with_animation(
"dialog-enter",
Animation::new(enter_duration).with_easing(ease_out_quint()),
|panel, delta| panel.opacity(delta),
)),
)
.with_priority(DIALOG_LAYER)
.into_any_element()
}
}
+719
View File
@@ -0,0 +1,719 @@
//! 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<DiffViewState> {
//! 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 std::ops::Range;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, Context, ElementId, HighlightStyle, InteractiveElement as _, IntoElement,
ListHorizontalSizingBehavior, ParentElement as _, Pixels, Render, ScrollStrategy, SharedString,
StatefulInteractiveElement as _, Styled as _, TextStyle, UniformListScrollHandle, Window, div,
point, uniform_list,
};
use similar::{Change, ChangeTag, TextDiff};
use crate::components::highlight::{HighlightedCode, Language, Line, Role, highlight};
use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility};
use crate::components::utils::{gutter_cell, wash, wash_gutter, wash_strong};
use crate::theme::{ActiveTheme as _, BORDER_WIDTH, CODE_GUTTER_WIDTH, MONO_ADVANCE_RATIO};
/// What a diff row did to the file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DiffRowKind {
/// Present in both versions.
Context,
/// Only in the new version.
Added,
/// Only in the old version.
Removed,
/// A hunk separator introducing the rows after it.
Hunk,
}
/// One row of a unified diff: a diff line or a hunk separator.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DiffRow {
pub kind: DiffRowKind,
/// The highlighted line content; empty for hunk separators.
pub content: Line,
/// 1-based line number in the old version, when the row exists there.
pub old_number: Option<usize>,
/// 1-based line number in the new version, when the row exists there.
pub new_number: Option<usize>,
/// Byte ranges of intra-line word changes, tinted on changed rows.
pub changed_ranges: Vec<Range<usize>>,
/// The `@@ -a,b +c,d @@` header, for hunk separator rows.
pub header: SharedString,
/// Unchanged lines collapsed into this separator row; zero elsewhere.
pub hidden_lines: usize,
}
/// How changed rows are marked.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DiffIndicators {
/// A two-pixel bar on the row's left edge.
#[default]
Bars,
/// Classic `+`/`-` glyphs in a marker column.
Classic,
/// Only the background washes.
None,
}
/// How collapsed regions between hunks render.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum HunkSeparator {
/// The collapsed unchanged line count, centered.
#[default]
LineInfo,
/// The patch-style `@@ -a,b +c,d @@` header.
Metadata,
/// A minimal `···` bar.
Simple,
}
/// 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,
}
impl Default for DiffViewOptions {
fn default() -> Self {
Self {
indicators: DiffIndicators::Bars,
separator: HunkSeparator::LineInfo,
line_numbers: true,
}
}
}
impl DiffRow {
/// Assembles a diff line row from a `similar` change.
pub(crate) fn from_change(
change: &Change<&str>,
code: &HighlightedCode,
changed_ranges: Vec<Range<usize>>,
) -> DiffRow {
let content = match change.tag() {
ChangeTag::Equal => change
.new_index()
.and_then(|ix| code.lines.get(ix))
.cloned()
.unwrap_or_default(),
ChangeTag::Delete => change
.old_index()
.and_then(|ix| code.lines.get(ix))
.cloned()
.unwrap_or_default(),
ChangeTag::Insert => change
.new_index()
.and_then(|ix| code.lines.get(ix))
.cloned()
.unwrap_or_default(),
};
let (old_number, new_number) = match change.tag() {
ChangeTag::Equal => (
change.old_index().map(|ix| ix + 1),
change.new_index().map(|ix| ix + 1),
),
ChangeTag::Delete => (change.old_index().map(|ix| ix + 1), None),
ChangeTag::Insert => (None, change.new_index().map(|ix| ix + 1)),
};
DiffRow {
kind: match change.tag() {
ChangeTag::Equal => DiffRowKind::Context,
ChangeTag::Delete => DiffRowKind::Removed,
ChangeTag::Insert => DiffRowKind::Added,
},
content,
old_number,
new_number,
changed_ranges,
header: Default::default(),
hidden_lines: 0,
}
}
/// The row's text length, in characters.
fn char_count(&self) -> usize {
self.content.text().chars().count()
}
/// Stable element id: the kind and line numbers packed into one integer.
fn element_id(&self, hunk_ordinal: usize) -> ElementId {
let kind = match self.kind {
DiffRowKind::Context => 0u64,
DiffRowKind::Added => 1,
DiffRowKind::Removed => 2,
DiffRowKind::Hunk => {
return ElementId::named_usize("diff-hunk", hunk_ordinal);
}
};
// Line numbers saturate at 2^31 so the two fields never overlap.
let old = self.old_number.unwrap_or(0).min((1 << 31) - 1) as u64;
let new = self.new_number.unwrap_or(0).min((1 << 31) - 1) as u64;
ElementId::named_usize("diff-row", ((kind << 62) | (old << 31) | new) as usize)
}
}
/// 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<DiffRow>,
/// Cached per-row id and text length, parallel to `rows`.
row_layouts: Vec<RowLayout>,
/// The row whose width drives horizontal scroll extent, `rows`-derived.
widest_row: Option<usize>,
options: DiffViewOptions,
/// Drives both scroll axes of the virtualized row list.
handle: UniformListScrollHandle,
a11y_label: Option<SharedString>,
}
/// Cached per-row render data, computed once when the rows are set.
struct RowLayout {
id: ElementId,
char_count: usize,
}
impl DiffViewState {
/// Builds the state, diffing `old` against `new`.
pub fn new<I, O, N>(id: I, old: O, new: N, language: Language) -> Self
where
I: Into<ElementId>,
O: AsRef<str>,
N: AsRef<str>,
{
let mut state = Self {
id: id.into(),
rows: Vec::new(),
row_layouts: Vec::new(),
widest_row: None,
options: DiffViewOptions::default(),
handle: UniformListScrollHandle::new(),
a11y_label: None,
};
state.set_rows(old, new, language);
state
}
/// Replaces the rows, recomputing the per-row layout cache with them.
fn set_rows<O, N>(&mut self, old: O, new: N, language: Language)
where
O: AsRef<str>,
N: AsRef<str>,
{
self.rows = Self::diff_rows(old.as_ref(), new.as_ref(), language);
let mut hunk_ordinal = 0usize;
self.row_layouts = self
.rows
.iter()
.map(|row| {
let ordinal = if row.kind == DiffRowKind::Hunk {
hunk_ordinal += 1;
hunk_ordinal
} else {
0
};
RowLayout {
id: row.element_id(ordinal),
char_count: row.char_count(),
}
})
.collect();
self.widest_row = self
.rows
.iter()
.zip(&self.row_layouts)
.enumerate()
.filter(|(_, (row, _))| row.kind != DiffRowKind::Hunk)
.max_by_key(|(_, (_, layout))| layout.char_count)
.map(|(widest, _)| widest);
}
/// 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<DiffRow> {
let old_code = highlight(old, language);
let new_code = highlight(new, language);
let diff = TextDiff::from_lines(old, new);
let mut rows = Vec::new();
let mut collapsed_before = 0usize;
for group in diff.grouped_ops(3) {
let (Some(first), Some(last)) = (group.first(), group.last()) else {
continue;
};
let old_range = first.old_range().start..last.old_range().end;
let new_range = first.new_range().start..last.new_range().end;
// git prints the line before a pure insertion when the count is zero.
let old_start = if old_range.is_empty() {
old_range.start
} else {
old_range.start + 1
};
let new_start = if new_range.is_empty() {
new_range.start
} else {
new_range.start + 1
};
let collapsed = first.old_range().start.saturating_sub(collapsed_before);
if collapsed > 0 {
rows.push(DiffRow {
kind: DiffRowKind::Hunk,
content: Line::default(),
old_number: None,
new_number: None,
changed_ranges: Vec::new(),
header: format!(
"@@ -{},{} +{},{} @@",
old_start,
old_range.len(),
new_start,
new_range.len()
)
.into(),
hidden_lines: collapsed,
});
}
collapsed_before = last.old_range().end;
for op in &group {
let changes: Vec<_> = diff.iter_changes(op).collect();
let mut index = 0;
while index < changes.len() {
if changes[index].tag() == ChangeTag::Equal {
rows.push(DiffRow::from_change(&changes[index], &new_code, Vec::new()));
index += 1;
continue;
}
let deletions = changes[index..]
.iter()
.take_while(|change| change.tag() == ChangeTag::Delete)
.count();
let insertions = changes[index + deletions..]
.iter()
.take_while(|change| change.tag() == ChangeTag::Insert)
.count();
let mut deletion_ranges = vec![Vec::new(); deletions];
let mut insertion_ranges = vec![Vec::new(); insertions];
for pair in 0..deletions.min(insertions) {
let old_text = changes[index + pair].value().trim_end_matches('\n');
let new_text = changes[index + deletions + pair]
.value()
.trim_end_matches('\n');
let words = TextDiff::from_words(old_text, new_text);
let (mut old_offset, mut new_offset) = (0usize, 0usize);
for word in words.iter_all_changes() {
let len = word.value().len();
match word.tag() {
ChangeTag::Delete => {
deletion_ranges[pair].push(old_offset..old_offset + len);
old_offset += len;
}
ChangeTag::Insert => {
insertion_ranges[pair].push(new_offset..new_offset + len);
new_offset += len;
}
ChangeTag::Equal => {
old_offset += len;
new_offset += len;
}
}
}
}
for pair in 0..deletions {
rows.push(DiffRow::from_change(
&changes[index + pair],
&old_code,
deletion_ranges[pair].clone(),
));
}
for pair in 0..insertions {
rows.push(DiffRow::from_change(
&changes[index + deletions + pair],
&new_code,
insertion_ranges[pair].clone(),
));
}
index += deletions + insertions;
}
}
}
rows
}
/// Sets how changed rows are marked.
pub fn indicators(mut self, indicators: DiffIndicators) -> Self {
self.options.indicators = indicators;
self
}
/// Sets how collapsed regions between hunks render.
pub fn hunk_separator(mut self, separator: HunkSeparator) -> Self {
self.options.separator = separator;
self
}
/// Shows or hides the line-number gutter.
pub fn line_numbers(mut self, show: bool) -> Self {
self.options.line_numbers = show;
self
}
/// Replaces the versions and re-diffs them.
pub fn set_versions<O, N>(&mut self, old: O, new: N, language: Language, cx: &mut Context<Self>)
where
O: AsRef<str>,
N: AsRef<str>,
{
self.set_rows(old, new, language);
self.handle.scroll_to_item(0, ScrollStrategy::Top);
// The replaced versions rarely share the old width; start at the left.
let offset = ScrollbarHandle::offset(&self.handle);
ScrollbarHandle::set_offset(&self.handle, point(Pixels::ZERO, offset.y));
cx.notify();
}
/// The diff rows.
pub fn rows(&self) -> &[DiffRow] {
&self.rows
}
/// Scrolls the first added or removed row to the top of the view.
pub fn scroll_to_first_change(&self) {
let Some(row) = self
.rows
.iter()
.position(|row| matches!(row.kind, DiffRowKind::Added | DiffRowKind::Removed))
else {
return;
};
self.handle.scroll_to_item(row, ScrollStrategy::Top);
}
/// Overrides the accessibility label of the view.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl Render for DiffViewState {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let text_size = theme.sizes.small.text_size;
let id = self.id.clone();
let state = cx.entity();
let row_count = self.rows.len();
let options = self.options;
let widest_row = self.widest_row;
let mut rows = uniform_list((id.clone(), "rows"), row_count, {
move |range, _window, cx| {
let diff = state.read(cx);
range
.map(|row_index| {
render_row(
&diff.rows[row_index],
&diff.row_layouts[row_index],
row_index,
options,
cx,
)
})
.collect()
}
})
.with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
.with_width_from_item(widest_row)
.track_scroll(&self.handle)
.h_full();
// Lock each gesture to its initial axis
rows.interactivity().base_style.restrict_scroll_to_axis = Some(true);
div()
.id((id.clone(), "view"))
.relative()
.size_full()
.text_size(text_size)
.when_some(self.a11y_label.clone(), |view, label| {
view.aria_label(label)
})
.child(rows)
.child(
Scrollbar::vertical((self.id.clone(), "v-scrollbar"), self.handle.clone())
.visibility(ScrollbarVisibility::Platform),
)
.child(
Scrollbar::horizontal((self.id.clone(), "h-scrollbar"), self.handle.clone())
.visibility(ScrollbarVisibility::Platform),
)
}
}
fn render_row(
row: &DiffRow,
layout: &RowLayout,
row_index: usize,
options: DiffViewOptions,
cx: &App,
) -> gpui::AnyElement {
let theme = cx.theme();
let mono_font = theme.mono_font;
let colors = theme.colors;
let ramps = theme.ramps;
let text_size = theme.sizes.small.text_size;
let line_height = text_size * 1.5;
let char_width = text_size * MONO_ADVANCE_RATIO;
let frame = div()
.debug_selector(move || format!("diff-row-{row_index}"))
.id(layout.id.clone())
.w_full()
.h(line_height)
.font_family(mono_font)
.text_size(text_size)
.overflow_hidden();
if row.kind == DiffRowKind::Hunk {
let content = match options.separator {
HunkSeparator::LineInfo => {
SharedString::from(format!("{} unchanged lines", row.hidden_lines))
}
HunkSeparator::Metadata => row.header.clone(),
HunkSeparator::Simple => SharedString::from("···"),
};
return frame
.flex()
.items_center()
.text_color(colors.muted_foreground)
.when(
options.indicators == DiffIndicators::Classic,
|row_element| row_element.child(div().w(CODE_GUTTER_WIDTH).flex_none()),
)
.when(options.line_numbers, |row_element| {
row_element.child(div().w(CODE_GUTTER_WIDTH).flex_none())
})
.when(
options.indicators == DiffIndicators::Bars && !options.line_numbers,
|row_element| {
row_element.child(
div()
.flex_none()
.border_l(BORDER_WIDTH * 4.0)
.border_color(gpui::transparent_black()),
)
},
)
.child(div().flex_none().ml_2().child(content))
.into_any_element();
}
let change_color = match row.kind {
DiffRowKind::Added => ramps.success.base,
DiffRowKind::Removed => ramps.destructive.base,
DiffRowKind::Context | DiffRowKind::Hunk => gpui::transparent_black(),
};
let wash = match row.kind {
DiffRowKind::Added => Some(wash(ramps.success.base)),
DiffRowKind::Removed => Some(wash(ramps.destructive.base)),
DiffRowKind::Context | DiffRowKind::Hunk => None,
};
let mut text = String::new();
let mut spans: Vec<(Range<usize>, Role)> = Vec::new();
for span in &row.content.spans {
let start = text.len();
text.push_str(&span.text);
if span.role != Role::Text {
spans.push((start..text.len(), span.role));
}
}
let mut boundaries: Vec<usize> = spans
.iter()
.flat_map(|(range, _)| [range.start, range.end])
.chain(
row.changed_ranges
.iter()
.flat_map(|range| [range.start, range.end]),
)
.collect();
boundaries.sort_unstable();
boundaries.dedup();
let mut highlights: Vec<(std::ops::Range<usize>, HighlightStyle)> = Vec::new();
let mut span_ix = 0;
for window in boundaries.windows(2) {
let (start, end) = (window[0], window[1]);
while span_ix < spans.len() && spans[span_ix].0.end <= start {
span_ix += 1;
}
let mut segment = HighlightStyle::default();
if let Some((range, role)) = spans.get(span_ix)
&& range.contains(&start)
&& *role != Role::Text
{
segment = segment.highlight(HighlightStyle {
color: Some(role.color(colors, ramps)),
..Default::default()
});
}
if row
.changed_ranges
.iter()
.any(|range| range.contains(&start))
{
segment = segment.highlight(HighlightStyle {
background_color: Some(wash_strong(change_color)),
..Default::default()
});
}
highlights.push((start..end, segment));
}
let style = TextStyle {
color: colors.foreground,
font_family: SharedString::from(mono_font),
font_size: text_size.into(),
line_height: line_height.into(),
..Default::default()
};
frame
.flex()
.items_center()
.when_some(wash, |row_element, tint| row_element.bg(tint))
.when(
options.indicators == DiffIndicators::Classic,
|row_element| {
row_element.child(gutter_cell(
cx,
if row.kind == DiffRowKind::Context {
gpui::transparent_black()
} else {
change_color
},
match row.kind {
DiffRowKind::Added => "+",
DiffRowKind::Removed => "-",
_ => "",
},
))
},
)
.when(options.line_numbers, |row_element| {
row_element.child(
gutter_cell(
cx,
colors.muted_foreground,
row.new_number
.or(row.old_number)
.map(|number| number.to_string())
.unwrap_or_default(),
)
.w(CODE_GUTTER_WIDTH)
.whitespace_nowrap()
.bg(match row.kind {
DiffRowKind::Context => wash_gutter(&colors),
_ => wash_strong(change_color),
})
.when(options.indicators == DiffIndicators::Bars, |number| {
number
.border_l(BORDER_WIDTH * 4.0)
.border_color(change_color)
}),
)
})
.when(
options.indicators == DiffIndicators::Bars && !options.line_numbers,
|row_element| {
row_element.child(
div()
.h_full()
.flex_none()
.border_l(BORDER_WIDTH * 4.0)
.border_color(change_color),
)
},
)
.child(
div()
.flex_none()
.ml_2()
.w(char_width * layout.char_count as f32)
.whitespace_nowrap()
.child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)),
)
.into_any_element()
}
+502
View File
@@ -0,0 +1,502 @@
//! 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 gpui::prelude::FluentBuilder as _;
use gpui::{
App, ClickEvent, DefiniteLength, DispatchPhase, ElementId, InteractiveElement as _,
IntoElement, KeyDownEvent, MouseButton, MouseDownEvent, ParentElement as _, RenderOnce, Role,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas,
div, relative,
};
use crate::components::button::ButtonVariant;
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};
/// The main zone's activation handler, shared by pointer, Enter, and Space.
type ClickHandler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<MenuItem>>;
/// A push button with an attached dropdown menu.
#[derive(IntoElement)]
#[must_use]
pub struct DropdownMenu {
id: ElementId,
label: Option<SharedString>,
icon: Option<Icon>,
variant: ButtonVariant,
size: Size,
disabled: bool,
loading: bool,
tab_stop: bool,
open: bool,
a11y_label: Option<SharedString>,
on_click: Option<ClickHandler>,
on_open_change: Option<ChangeHandler>,
items: Option<ItemsFn>,
min_width: Option<DefiniteLength>,
style: StyleRefinement,
}
impl DropdownMenu {
/// Creates a closed dropdown menu rendered as a primary button.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
label: None,
icon: None,
variant: ButtonVariant::default(),
size: Size::default(),
disabled: false,
loading: false,
tab_stop: true,
open: false,
a11y_label: None,
on_click: None,
on_open_change: None,
items: None,
min_width: None,
style: StyleRefinement::default(),
}
}
/// Sets the visible label.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Shows an icon. Omitting the label renders an icon-only trigger.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Sets the button's visual language.
pub fn variant(mut self, variant: ButtonVariant) -> Self {
self.variant = variant;
self
}
/// 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
}
/// Renders the trigger inert, unfocusable, and dimmed.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Shows the spinner in place of the content and suppresses activation.
pub fn loading(mut self, loading: bool) -> Self {
self.loading = loading;
self
}
/// Sets the current open state.
pub fn open(mut self, open: bool) -> Self {
self.open = open;
self
}
/// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Sets the main zone's action. Without one, activating the button opens the menu.
pub fn on_click<F>(mut self, handler: F) -> Self
where
F: Fn(&ClickEvent, &mut Window, &mut App) + 'static,
{
self.on_click = Some(Box::new(handler));
self
}
/// Reports the menu's next open state.
pub fn on_open_change<F>(mut self, handler: F) -> Self
where
F: Fn(bool, &mut Window, &mut App) + 'static,
{
self.on_open_change = Some(Rc::new(handler));
self
}
/// Sets the menu's items, built fresh each render.
pub fn items<F>(mut self, items: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<MenuItem> + 'static,
{
self.items = Some(Box::new(items));
self
}
/// Sets the panel's minimum width, defaults to the standard menu width.
pub fn min_width<W>(mut self, width: W) -> Self
where
W: Into<DefiniteLength>,
{
self.min_width = Some(width.into());
self
}
}
impl Sizable for DropdownMenu {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl gpui::Styled for DropdownMenu {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for DropdownMenu {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let metrics = theme.sizes.resolve(self.size);
let radius = theme.radius.control;
let ring = colors.ring;
let (panel_chrome, enter_duration) = MenuChrome::read(cx);
let (background, foreground, hover, pressed) = match self.variant {
ButtonVariant::Primary => (
Some(ramps.primary.base),
colors.primary_foreground,
ramps.primary.hover,
ramps.primary.pressed,
),
ButtonVariant::Secondary => (
Some(colors.surface),
colors.foreground,
colors.muted,
colors.muted_hover,
),
ButtonVariant::Ghost => (
None,
colors.foreground,
colors.muted_hover,
ramps.secondary.pressed,
),
ButtonVariant::Destructive => (
Some(ramps.destructive.base),
colors.destructive_foreground,
ramps.destructive.hover,
ramps.destructive.pressed,
),
};
let border = match self.variant {
ButtonVariant::Primary => ramps.primary.base,
ButtonVariant::Secondary => colors.border,
ButtonVariant::Ghost => gpui::transparent_black(),
ButtonVariant::Destructive => ramps.destructive.base,
};
let split = self.on_click.is_some();
let icon_only = self.icon.is_some() && self.label.is_none() && !split;
let inert = self.disabled || self.loading;
let label = self
.a11y_label
.clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
let a11y_label = self.a11y_label.or_else(|| self.label.clone());
let focus = focus_handle(&self.id, window, cx).tab_stop(self.tab_stop);
// How the menu was last opened, read by the frame that mounts the panel.
let keyboard_open =
window.use_keyed_state((self.id.clone(), "dropdown-open-origin"), cx, |_, _| false);
let on_open: ChangeHandler = {
let focus = focus.clone();
let on_open_change = self.on_open_change.clone();
let keyboard_open = keyboard_open.clone();
Rc::new(move |next, window, cx| {
if !next {
window.focus(&focus, cx);
keyboard_open.update(cx, |keyboard_open, _| *keyboard_open = false);
}
if let Some(on_open_change) = &on_open_change {
on_open_change(next, window, cx);
}
})
};
let trigger_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None));
let chevron_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None));
let main = h_flex()
.id(self.id.clone())
.debug_selector({
let id = self.id.clone();
move || id.to_string()
})
.justify_center()
.h_full()
.when(icon_only, |zone| zone.w_full())
.gap_2()
.line_height(relative(1.0))
.text_size(metrics.text_size)
.text_color(foreground)
.role(Role::Button)
.when_some(a11y_label, |zone, label| zone.aria_label(label))
.aria_expanded(self.open)
.px(if icon_only {
gpui::Pixels::ZERO
} else {
metrics.padding_x
})
.when(split, |zone| zone.rounded_l(radius))
.when(!split, |zone| {
zone.rounded(radius)
.when(self.open, |zone| zone.bg(pressed))
})
.when(!icon_only && !split, |zone| {
zone.child(
icon(IconRole::ChevronDown)
.size(metrics.dense_icon_size)
.color(foreground),
)
})
.child(
h_flex()
.gap_2()
.when(self.loading, |content| content.invisible())
.when_some(self.icon, |content, icon| {
content.child(icon.size(metrics.icon_size).color(foreground))
})
.when_some(self.label, |content, label| content.child(label)),
)
.when(self.loading, |zone| {
zone.child(
h_flex().absolute().inset_0().justify_center().child(
Spinner::new((self.id.clone(), "spinner"))
.with_size(self.size)
.variant(crate::components::spinner::SpinnerVariant::Icon)
.color(foreground),
),
)
});
let main = if inert {
main
} else {
main.track_focus(&focus)
.cursor_pointer()
.hover(move |style| style.bg(hover))
.active(move |style| style.bg(pressed))
.on_click({
let on_click = self.on_click;
let on_open = on_open.clone();
let keyboard_open = keyboard_open.clone();
let open = self.open;
move |event, window, cx| match (on_click.as_ref(), event) {
(Some(on_click), _) => on_click(event, window, cx),
(None, ClickEvent::Keyboard(_)) => {
keyboard_open.update(cx, |keyboard_open, _| *keyboard_open = true);
on_open(!open, window, cx);
}
(None, _) => {}
}
})
.on_key_down({
let on_open = on_open.clone();
let keyboard_open = keyboard_open.clone();
move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "down" {
keyboard_open.update(cx, |keyboard_open, _| *keyboard_open = true);
on_open(true, window, cx);
cx.stop_propagation();
}
}
})
};
let chevron_zone = h_flex()
.id((self.id.clone(), "chevron"))
.debug_selector({
let id = self.id.clone();
move || format!("{id}-chevron")
})
.relative()
.h_full()
.px(metrics.dense_padding_x)
.rounded_r(radius)
.rounded_l_none()
.border_l_1()
.border_color(border)
.when(self.open, |zone| zone.bg(pressed))
.when(!inert, |zone| {
zone.cursor_pointer()
.hover(move |style| style.bg(hover))
.active(move |style| style.bg(pressed))
})
.child(
icon(IconRole::ChevronDown)
.size(metrics.dense_icon_size)
.color(foreground),
)
.child(
canvas(
{
let cell = chevron_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
);
let trigger = h_flex()
.debug_selector({
let id = self.id.clone();
move || format!("{id}-trigger")
})
.h(metrics.control_height)
.when(icon_only, |trigger| trigger.w(metrics.control_height))
.rounded(radius)
.border_1()
.border_color(border)
.when_some(background, |trigger, background| trigger.bg(background))
.when(self.disabled, |trigger| trigger.opacity(DISABLED_OPACITY))
.when(!inert, |trigger| {
trigger
.track_focus(&focus)
.focus_visible(move |style| style.shadow(focus_ring(ring)))
})
.child(main);
let trigger = if split {
trigger.child(chevron_zone)
} else {
trigger
};
let items = if self.open {
self.items
.map(|build| Rc::from(build(window, cx)))
.unwrap_or_else(|| Rc::from([]))
} else {
Rc::from([])
};
let on_close = Some(on_open.clone());
let spec = MenuPanelSpec {
open: self.open,
items,
initial_selection: None,
preselect: *keyboard_open.read(cx),
min_width: self.min_width,
label,
position: None,
trigger_bounds: trigger_bounds.clone(),
on_dismiss: on_close.clone(),
on_activate: on_close,
};
div()
.relative()
.refine_style(&self.style)
.child(
canvas(
{
let cell = trigger_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
{
let on_open = on_open.clone();
let trigger_bounds = trigger_bounds.clone();
let chevron_bounds = chevron_bounds.clone();
let keyboard_open = keyboard_open.clone();
let open = self.open;
move |_, _, window, _cx| {
window.on_mouse_event({
let on_open = on_open.clone();
let keyboard_open = keyboard_open.clone();
move |event: &MouseDownEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble
|| event.button != MouseButton::Left
|| inert
{
return;
}
let in_trigger = trigger_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position));
if !in_trigger {
return;
}
let in_chevron = chevron_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position));
if !open && split && !in_chevron {
return;
}
keyboard_open
.update(cx, |keyboard_open, _| *keyboard_open = false);
on_open(!open, window, cx);
cx.stop_propagation();
}
});
}
},
)
.absolute()
.inset_0(),
)
.child(trigger)
.when_some(
anchored_menu_panel(window, cx, &self.id, spec, &panel_chrome, enter_duration),
|wrapper, panel| wrapper.child(panel),
)
}
}
+122
View File
@@ -0,0 +1,122 @@
//! 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 gpui::prelude::FluentBuilder as _;
use gpui::{
App, IntoElement, ParentElement as _, RenderOnce, SharedString, StyleRefinement, Styled as _,
Window, div,
};
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)]
#[must_use]
pub struct EmptyState {
icon: Option<Icon>,
headline: SharedString,
hint: Option<SharedString>,
action: Option<gpui::AnyElement>,
style: StyleRefinement,
}
impl EmptyState {
/// Creates an empty state whose headline is the primary statement.
pub fn new<L>(headline: L) -> Self
where
L: Into<SharedString>,
{
Self {
icon: None,
headline: headline.into(),
hint: None,
action: None,
style: StyleRefinement::default(),
}
}
/// Sets a large muted icon above the headline.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Sets a secondary line under the headline.
pub fn hint<L>(mut self, hint: L) -> Self
where
L: Into<SharedString>,
{
self.hint = Some(hint.into());
self
}
/// Sets an action element, usually a [`crate::components::button::Button`], under the hint.
pub fn action<E>(mut self, action: E) -> Self
where
E: IntoElement,
{
self.action = Some(action.into_any_element());
self
}
}
impl gpui::Styled for EmptyState {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for EmptyState {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let metrics = theme.sizes.resolve(Size::Medium);
let muted_foreground = theme.colors.muted_foreground;
let foreground = theme.colors.foreground;
let illustration = metrics.icon_size * 2.0;
v_flex()
.w_full()
.items_center()
.justify_center()
.text_center()
.p_4()
.when_some(self.icon, |state, icon| {
state.child(
div()
.mb_2()
.child(icon.size(illustration).color(muted_foreground)),
)
})
.child(
div()
.typeset(TextRole::Title3, cx)
.text_color(foreground)
.child(self.headline),
)
.when_some(self.hint, |state, hint| {
state.child(
div()
.typeset(TextRole::Subheadline, cx)
.text_color(muted_foreground)
.child(hint),
)
})
.when_some(self.action, |state, action| {
state.child(div().mt_3().child(action))
})
.refine_style(&self.style)
}
}
+193
View File
@@ -0,0 +1,193 @@
//! 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 gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce,
Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div,
};
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)]
pub enum FieldVariant {
/// The label block sits above the control, full width.
#[default]
Block,
/// The label block leads and the control trails, as in a settings row.
Row,
}
/// A control presented with a label, an optional description, and an error.
#[derive(IntoElement)]
#[must_use]
pub struct Field {
id: ElementId,
label: SharedString,
description: Option<SharedString>,
error: Option<SharedString>,
variant: FieldVariant,
control: Vec<AnyElement>,
style: StyleRefinement,
}
impl Field {
/// Creates a field naming its control.
pub fn new<I, L>(id: I, label: L) -> Self
where
I: Into<ElementId>,
L: Into<SharedString>,
{
Self {
id: id.into(),
label: label.into(),
description: None,
error: None,
variant: FieldVariant::default(),
control: Vec::new(),
style: StyleRefinement::default(),
}
}
/// Sets the helper text under the label.
pub fn description<D>(mut self, description: D) -> Self
where
D: Into<SharedString>,
{
self.description = Some(description.into());
self
}
/// Sets the error under the control; `None` clears it.
pub fn error<E>(mut self, error: Option<E>) -> Self
where
E: Into<SharedString>,
{
self.error = error.map(Into::into);
self
}
/// Sets the field's arrangement.
pub fn variant(mut self, variant: FieldVariant) -> Self {
self.variant = variant;
self
}
}
impl ParentElement for Field {
fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
self.control.extend(children);
}
}
impl Styled for Field {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Field {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let metrics = theme.sizes.medium;
let error_color = theme.ramps.destructive.base;
let id = self.id.clone();
let title = div()
.debug_selector({
let id = id.clone();
move || format!("{id}-label")
})
.when(self.description.is_some(), |title| {
title.typeset(TextRole::Headline, cx)
})
.when(self.description.is_none(), |title| {
title.typeset(TextRole::Callout, cx)
})
.child(self.label.clone());
let control = h_flex()
.items_center()
.gap_2()
.debug_selector({
let id = id.clone();
move || format!("{id}-control")
})
.children(self.control);
let error = self.error.map(|error| {
div()
.debug_selector({
let id = id.clone();
move || format!("{id}-error")
})
.text_size(metrics.caption_size)
.text_color(error_color)
.child(error)
});
let description_text = |cx: &App| {
div()
.text_size(metrics.caption_size)
.text_color(cx.theme().colors.muted_foreground)
};
let content = if self.variant == FieldVariant::Row {
div()
.flex()
.flex_col()
.gap_1()
.child(
h_flex()
.items_center()
.justify_between()
.gap_4()
.child(title.flex_1().min_w_0())
.child(control.flex_none()),
)
.when_some(self.description.clone(), |field, description| {
field.child(description_text(cx).child(description))
})
.when_some(error, |field, error| field.child(error))
} else {
div()
.flex()
.flex_col()
.gap_2()
.child(
v_flex()
.gap_0p5()
.child(title)
.when_some(self.description.clone(), |slot, description| {
slot.child(description_text(cx).child(description))
}),
)
.child(control)
.when_some(error, |field, error| field.child(error))
};
div()
.id(self.id)
.w_full()
.role(Role::Group)
.aria_label(self.label.clone())
.when_some(self.description, |field, description| {
field.aria_description(description)
})
.refine_style(&self.style)
.child(content)
}
}
+101
View File
@@ -0,0 +1,101 @@
//! 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 gpui::{
App, Bounds, Corners, IntoElement, RenderImage, RenderOnce, Styled as _, Window, canvas, point,
px, size,
};
use image::{Frame, ImageBuffer, Rgba};
use crate::components::common::ResultLogErr as _;
use crate::theme::GRAIN_ALPHA;
/// The side of one noise tile, in device pixels.
const TILE_PX: u32 = 256;
/// A film-grain overlay that tiles monochrome noise at [`GRAIN_ALPHA`] strength.
#[derive(IntoElement)]
#[must_use]
pub struct Grain;
/// Creates a grain overlay.
pub fn grain() -> Grain {
Grain
}
impl RenderOnce for Grain {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
let texture = texture();
canvas(
|_, _, _| (),
move |bounds, (), window, _| {
let tile = px(TILE_PX as f32);
let columns = (bounds.size.width / tile).ceil() as u32;
let rows = (bounds.size.height / tile).ceil() as u32;
for row in 0..rows {
for column in 0..columns {
let x = bounds.origin.x + column as f32 * tile;
let y = bounds.origin.y + row as f32 * tile;
let tile_bounds = Bounds {
origin: point(x, y),
size: size(
tile.min(bounds.origin.x + bounds.size.width - x),
tile.min(bounds.origin.y + bounds.size.height - y),
),
};
window
.paint_image(
tile_bounds,
tile_bounds,
Corners::default(),
texture.clone(),
0,
false,
)
.log_err();
}
}
},
)
.absolute()
.inset_0()
}
}
/// Returns the shared noise tile so every tile reuses one atlas entry.
fn texture() -> Arc<RenderImage> {
static TEXTURE: OnceLock<Arc<RenderImage>> = OnceLock::new();
TEXTURE
.get_or_init(|| {
// An LCG keeps the grain deterministic across launches.
let mut state = 0x9E37_79B9_u32;
let mut noise = move || {
state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
(state >> 24) as u8
};
// The grays are noise samples, not palette colors.
let alpha = (GRAIN_ALPHA * 255.0) as u8;
Arc::new(RenderImage::new([Frame::new(ImageBuffer::from_fn(
TILE_PX,
TILE_PX,
|_, _| {
let gray = noise();
Rgba([gray, gray, gray, alpha])
},
))]))
})
.clone()
}
+285
View File
@@ -0,0 +1,285 @@
//! 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 std::cell::RefCell;
use std::collections::HashMap;
use gpui::SharedString;
#[cfg(not(target_arch = "wasm32"))]
use tree_sitter::StreamingIterator as _;
use crate::components::common::ResultLogErr;
#[cfg(not(target_arch = "wasm32"))]
thread_local! {
static HIGHLIGHTERS: RefCell<HashMap<Language, Option<Highlighter>>> =
RefCell::new(HashMap::new());
}
/// A grammar's parser and compiled highlight query.
#[cfg(not(target_arch = "wasm32"))]
struct Highlighter {
parser: tree_sitter::Parser,
query: tree_sitter::Query,
roles: Vec<Option<Role>>,
}
/// A language source can highlight as.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Language {
Plain,
Rust,
JavaScript,
TypeScript,
Python,
}
/// The semantic role a span plays.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Role {
Text,
Keyword,
String,
Comment,
Function,
Type,
Number,
Constant,
Property,
Operator,
Punctuation,
Tag,
Escape,
}
/// 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<Span>,
}
impl Line {
/// The line's flat text, in character order.
pub fn text(&self) -> String {
let mut text = String::new();
for span in &self.spans {
text.push_str(&span.text);
}
text
}
}
/// 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<Line>,
}
/// 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 {
return plain(source);
};
HIGHLIGHTERS.with(|cache| {
let mut cache = cache.borrow_mut();
let highlighter = cache
.entry(language)
.or_insert_with(|| {
let mut parser = tree_sitter::Parser::new();
parser.set_language(&grammar).log_err()?;
let query = tree_sitter::Query::new(&grammar, query_source).log_err()?;
let roles = query
.capture_names()
.iter()
.map(|name| role_for_capture(name))
.collect();
Some(Highlighter {
parser,
query,
roles,
})
})
.as_mut();
let Some(highlighter) = highlighter else {
return plain(source);
};
let Some(tree) = highlighter.parser.parse(source, None) else {
log::warn!("tree-sitter failed to parse {language:?}; rendering plain text");
return plain(source);
};
// One role per byte; matches arrive in query order
let mut role_at = vec![None; source.len()];
let mut cursor = tree_sitter::QueryCursor::new();
let mut matches = cursor.matches(&highlighter.query, tree.root_node(), source.as_bytes());
while let Some(matched) = matches.next() {
for capture in matched.captures {
let Some(role) = highlighter
.roles
.get(capture.index as usize)
.copied()
.flatten()
else {
continue;
};
for byte in capture.node.byte_range() {
if let Some(slot) = role_at.get_mut(byte) {
*slot = Some(role);
}
}
}
}
build_lines(source, &role_at)
})
}
/// 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)
}
/// Source rendered without any grammar: plain text roles.
pub(crate) fn plain(source: &str) -> HighlightedCode {
build_lines(source, &[])
}
/// The grammar and its highlight query for a language, when compiled in.
#[cfg(not(target_arch = "wasm32"))]
fn grammar_for(language: Language) -> Option<(tree_sitter::Language, &'static str)> {
match language {
Language::Rust => rust_grammar(),
Language::TypeScript => typescript_grammar(),
Language::JavaScript => javascript_grammar(),
Language::Python => python_grammar(),
Language::Plain => None,
}
}
/// The Rust grammar.
#[cfg(not(target_arch = "wasm32"))]
fn rust_grammar() -> Option<(tree_sitter::Language, &'static str)> {
Some((
tree_sitter_rust::LANGUAGE.into(),
tree_sitter_rust::HIGHLIGHTS_QUERY,
))
}
/// The TypeScript grammar.
#[cfg(not(target_arch = "wasm32"))]
fn typescript_grammar() -> Option<(tree_sitter::Language, &'static str)> {
Some((
tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
tree_sitter_typescript::HIGHLIGHTS_QUERY,
))
}
/// The JavaScript grammar.
#[cfg(not(target_arch = "wasm32"))]
fn javascript_grammar() -> Option<(tree_sitter::Language, &'static str)> {
Some((
tree_sitter_javascript::LANGUAGE.into(),
tree_sitter_javascript::HIGHLIGHT_QUERY,
))
}
/// The Python grammar.
#[cfg(not(target_arch = "wasm32"))]
fn python_grammar() -> Option<(tree_sitter::Language, &'static str)> {
Some((
tree_sitter_python::LANGUAGE.into(),
tree_sitter_python::HIGHLIGHTS_QUERY,
))
}
/// Maps a query capture name to a role; unmapped captures render as text.
fn role_for_capture(name: &str) -> Option<Role> {
match name.split('.').next()? {
"keyword" => Some(Role::Keyword),
"string" => Some(Role::String),
"escape" => Some(Role::Escape),
"comment" => Some(Role::Comment),
"function" | "method" => Some(Role::Function),
"type" | "attribute" => Some(Role::Type),
"number" => Some(Role::Number),
"constant" => Some(Role::Constant),
"property" => Some(Role::Property),
"operator" => Some(Role::Operator),
"punctuation" => Some(Role::Punctuation),
"tag" => Some(Role::Tag),
_ => None,
}
}
/// Splits `source` into lines, grouping consecutive bytes that share a role into one span.
fn build_lines(source: &str, role_at: &[Option<Role>]) -> HighlightedCode {
let role_of =
|byte: usize| -> Role { role_at.get(byte).copied().flatten().unwrap_or(Role::Text) };
let mut lines = Vec::new();
let mut spans: Vec<Span> = Vec::new();
let mut text = String::new();
let mut role = Role::Text;
for (byte, character) in source.char_indices() {
let byte_role = role_of(byte);
if character == '\n' {
flush_run(&mut text, role, &mut spans);
lines.push(Line {
spans: std::mem::take(&mut spans),
});
continue;
}
if byte_role != role && !text.is_empty() {
flush_run(&mut text, role, &mut spans);
}
role = byte_role;
text.push(character);
}
flush_run(&mut text, role, &mut spans);
lines.push(Line {
spans: std::mem::take(&mut spans),
});
HighlightedCode { lines }
}
fn flush_run(text: &mut String, role: Role, spans: &mut Vec<Span>) {
if !text.is_empty() {
spans.push(Span {
text: SharedString::from(std::mem::take(text)),
role,
});
}
}
File diff suppressed because it is too large Load Diff
+312
View File
@@ -0,0 +1,312 @@
//! Renders keyboard keys and shortcuts as small key caps.
//!
//! # Examples
//!
//! ```no_run
//! use gpui::{Keystroke, ParentElement as _};
//! use ui::kbd::{Kbd, KbdGroup};
//!
//! let save = Kbd::new(Keystroke::parse("cmd-s").unwrap());
//! let combo = KbdGroup::new()
//! .child(Kbd::new(Keystroke::parse("ctrl-b").unwrap()))
//! .child(Kbd::new(Keystroke::parse("ctrl-k").unwrap()));
//! ```
use gpui::prelude::FluentBuilder as _;
use gpui::{
Action, AnyElement, App, FocusHandle, FontWeight, InteractiveElement as _, IntoElement,
KeyBinding, KeyContext, Keystroke, OperatingSystem, ParentElement as _, RenderOnce,
SharedString, StyleRefinement, Styled as _, Window, div, relative,
};
use crate::components::common::{StyledExt as _, h_flex};
use crate::theme::ActiveTheme as _;
/// A key or shortcut shown as a small key cap, like `⌘S` or `Ctrl+S`.
#[derive(IntoElement, Clone, Debug)]
#[must_use]
pub struct Kbd {
stroke: Keystroke,
appearance: bool,
style: StyleRefinement,
}
impl From<Keystroke> for Kbd {
fn from(stroke: Keystroke) -> Self {
Self::new(stroke)
}
}
impl Kbd {
/// Creates a key cap showing `stroke`.
pub fn new(stroke: Keystroke) -> Self {
Self {
stroke,
appearance: true,
style: StyleRefinement::default(),
}
}
/// The keystroke this key cap shows.
pub fn keystroke(&self) -> &Keystroke {
&self.stroke
}
/// When false, paints the formatted shortcut as plain text without the key cap.
pub fn appearance(mut self, appearance: bool) -> Self {
self.appearance = appearance;
self
}
/// Returns a key cap for the highest-precedence binding of `action`.
pub fn binding_for_action(
action: &dyn Action,
context: Option<&str>,
window: &Window,
) -> Option<Self> {
let binding = match context.and_then(|context| KeyContext::parse(context).ok()) {
Some(context) => {
window.highest_precedence_binding_for_action_in_context(action, context)
}
None => window.highest_precedence_binding_for_action(action),
}?;
Self::from_binding(&binding)
}
/// Returns a key cap for the binding of `action`.
pub fn binding_for_action_in(
action: &dyn Action,
focus_handle: &FocusHandle,
window: &Window,
) -> Option<Self> {
let binding = window.highest_precedence_binding_for_action_in(action, focus_handle)?;
Self::from_binding(&binding)
}
/// Returns a key cap for the binding of `action` registered without a key context.
pub fn global_binding_for_action(action: &dyn Action, window: &Window) -> Option<Self> {
let binding = window
.highest_precedence_binding_for_action_in_context(action, KeyContext::default())?;
Self::from_binding(&binding)
}
/// Shows the binding's keystroke as the keymap holds it.
fn from_binding(binding: &KeyBinding) -> Option<Self> {
binding.keystrokes().first().map(|stroke| {
Self::new(Keystroke {
modifiers: *stroke.modifiers(),
key: stroke.key().into(),
key_char: None,
})
})
}
/// Formats `stroke` for `os`: modifier symbols on macOS, `Ctrl+` words elsewhere.
pub fn format(stroke: &Keystroke, os: OperatingSystem) -> String {
let mac = os == OperatingSystem::Mac;
let separator = if mac { "" } else { "+" };
let mut parts: Vec<&str> = Vec::new();
// macOS reads ⌃⌥⇧⌘; other platforms read Ctrl+Alt+Shift+Win.
if stroke.modifiers.control {
parts.push(if mac { "⌃" } else { "Ctrl" });
}
if stroke.modifiers.alt {
parts.push(if mac { "⌥" } else { "Alt" });
}
if stroke.modifiers.shift {
parts.push(if mac { "⇧" } else { "Shift" });
}
if stroke.modifiers.platform {
parts.push(match os {
OperatingSystem::Mac => "⌘",
OperatingSystem::Windows => "Win",
_ => "Super",
});
}
let key = Self::key_label(&stroke.key, os);
parts.push(&key);
parts.join(separator)
}
/// The label for a key, with modifier glyphs on macOS and words elsewhere.
fn key_label(key: &str, os: OperatingSystem) -> String {
let mac = os == OperatingSystem::Mac;
let label: &str = match key {
"cmd" | "platform" => {
if mac {
"⌘"
} else {
"Win"
}
}
"ctrl" | "control" => {
if mac {
"⌃"
} else {
"Ctrl"
}
}
"alt" => {
if mac {
"⌥"
} else {
"Alt"
}
}
"shift" => {
if mac {
"⇧"
} else {
"Shift"
}
}
"function" => "Fn",
"backspace" => {
if mac {
"⌫"
} else {
"Backspace"
}
}
"delete" => {
if mac {
"⌦"
} else {
"Delete"
}
}
"enter" | "return" => {
if mac {
"⏎"
} else {
"Enter"
}
}
"escape" => {
if mac {
"⎋"
} else {
"Esc"
}
}
"tab" => {
if mac {
"⇥"
} else {
"Tab"
}
}
"space" => "Space",
"pageup" => "Page Up",
"pagedown" => "Page Down",
"left" => {
if mac {
"←"
} else {
"Left"
}
}
"right" => {
if mac {
"→"
} else {
"Right"
}
}
"up" => {
if mac {
"↑"
} else {
"Up"
}
}
"down" => {
if mac {
"↓"
} else {
"Down"
}
}
key => key,
};
let mut chars = label.chars();
match chars.next() {
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
None => String::new(),
}
}
}
impl gpui::Styled for Kbd {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Kbd {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let os = cx.platform_info().os;
let selector = format!("kbd:{}", self.stroke.unparse(os));
let label = SharedString::from(Self::format(&self.stroke, os));
div()
// Lets a test ask whether this shortcut hint was painted this frame.
.debug_selector(move || selector)
.when(self.appearance, |key| {
key.flex_none()
.border_1()
.border_color(theme.colors.border)
.bg(theme.colors.muted)
.text_color(theme.colors.muted_foreground)
.py_0p5()
.px_1()
.min_w_5()
.rounded(theme.radius.sm)
.text_center()
.line_height(relative(1.))
.text_size(theme.typography.caption.size)
})
.refine_style(&self.style)
.child(label)
}
}
/// A row of key caps, grouping the keys of a multi-key hint.
#[derive(IntoElement, Default)]
#[must_use]
pub struct KbdGroup {
style: StyleRefinement,
children: Vec<AnyElement>,
}
impl KbdGroup {
/// Creates an empty group.
pub fn new() -> Self {
Self::default()
}
}
impl gpui::ParentElement for KbdGroup {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl gpui::Styled for KbdGroup {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for KbdGroup {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
h_flex()
.flex_none()
.gap_1()
.refine_style(&self.style)
.children(self.children)
}
}
+154
View File
@@ -0,0 +1,154 @@
//! 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 gpui::prelude::FluentBuilder as _;
use gpui::{
App, ClickEvent, ElementId, InteractiveElement as _, IntoElement, ParentElement as _,
RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
Window,
};
use crate::components::common::{Sizable, StyledExt as _, focus_ring, h_flex};
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
/// The handler called with the [`gpui::ClickEvent`], replacing the default `href` opening.
type ClickHandler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
/// A hyperlink that opens a URL or fires a click handler.
#[derive(IntoElement)]
#[must_use]
pub struct Link {
id: ElementId,
label: Option<SharedString>,
href: Option<SharedString>,
size: Size,
disabled: bool,
a11y_label: Option<SharedString>,
on_click: Option<ClickHandler>,
style: StyleRefinement,
}
impl Link {
/// Creates a link without a label or target.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
label: None,
href: None,
size: Size::default(),
disabled: false,
a11y_label: None,
on_click: None,
style: StyleRefinement::default(),
}
}
/// Sets the visible label.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Sets the URL the link opens through the platform.
pub fn href<U>(mut self, href: U) -> Self
where
U: Into<SharedString>,
{
self.href = Some(href.into());
self
}
/// Renders the link inert, unfocusable, and dimmed; disabled always wins.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Replaces the default `href` opening with this handler.
pub fn on_click<F>(mut self, handler: F) -> Self
where
F: Fn(&ClickEvent, &mut Window, &mut App) + 'static,
{
self.on_click = Some(Box::new(handler));
self
}
}
impl gpui::Styled for Link {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Link {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Link {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let metrics = theme.sizes.resolve(self.size);
let on_click = self.on_click;
let href = self.href;
let a11y_label = self.a11y_label.or_else(|| self.label.clone());
h_flex()
.id(self.id)
.text_size(metrics.text_size)
.text_color(ramps.primary.base)
.underline()
.refine_style(&self.style)
.role(Role::Link)
.when_some(a11y_label, |link, label| link.aria_label(label))
.when(self.disabled, |link| link.opacity(DISABLED_OPACITY))
.when(!self.disabled, |link| {
link.cursor_pointer()
.focusable()
.tab_stop(true)
.hover(move |style| style.text_color(ramps.primary.hover))
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.on_click(move |event, window, cx| match on_click.as_ref() {
Some(on_click) => on_click(event, window, cx),
None => {
if let Some(href) = href.as_ref() {
cx.open_url(href);
}
}
})
})
.when_some(self.label, |link, label| link.child(label))
}
}
+292
View File
@@ -0,0 +1,292 @@
//! 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 gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent,
ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Window, div,
};
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 _};
/// The change reporter, fired with the next selection by pointer and keys.
type ChangeHandler = Rc<dyn Fn(Option<usize>, &mut Window, &mut App)>;
/// The row builder, run during render.
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<ListItem>>;
/// One row of a [`List`].
#[must_use]
pub struct ListItem {
key: ElementId,
label: SharedString,
icon: Option<Icon>,
detail: Option<SharedString>,
disabled: bool,
}
impl ListItem {
/// Creates a row shown as `label`, identified by `key`.
pub fn new<K, L>(key: K, label: L) -> Self
where
K: Into<ElementId>,
L: Into<SharedString>,
{
Self {
key: key.into(),
label: label.into(),
icon: None,
detail: None,
disabled: false,
}
}
/// Shows an icon leading the label, a role or any custom [`crate::icons::IconNamed`].
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Shows muted trailing text.
pub fn detail<D>(mut self, detail: D) -> Self
where
D: Into<SharedString>,
{
self.detail = Some(detail.into());
self
}
/// Renders the row dimmed; clicks and keyboard skip it.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
// ListItem is a data builder, not an element, adopt the combinators explicitly.
impl FluentBuilder for ListItem {}
/// A single-selection list of [`ListItem`] rows.
#[derive(IntoElement)]
#[must_use]
pub struct List {
id: ElementId,
selected: Option<usize>,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
items: Option<ItemsFn>,
style: StyleRefinement,
}
impl List {
/// Creates a list with nothing selected.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
selected: None,
a11y_label: None,
on_change: None,
items: None,
style: StyleRefinement::default(),
}
}
/// Sets the current selection.
pub fn selected(mut self, selected: Option<usize>) -> Self {
self.selected = selected;
self
}
/// Reports the next selection, from clicks and keys alike.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(Option<usize>, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Sets the rows; the closure runs during render and must not mutate entities or notify.
pub fn items<F>(mut self, items: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<ListItem> + 'static,
{
self.items = Some(Box::new(items));
self
}
/// Overrides the accessibility label, which defaults to the id.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl gpui::Styled for List {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for List {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let items = match self.items {
Some(build) => build(window, cx),
None => Vec::new(),
};
let selectable: Vec<usize> = items
.iter()
.enumerate()
.filter(|(_, item)| !item.disabled)
.map(|(index, _)| index)
.collect();
let focus = crate::components::common::focus_handle(&self.id, window, cx);
let theme = cx.theme();
let label = self
.a11y_label
.clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
let rows: Vec<AnyElement> = items
.iter()
.enumerate()
.map(|(index, item)| {
item.render_row(
cx,
index,
items.len(),
self.selected == Some(index),
&self.on_change,
&focus,
)
})
.collect();
div()
.id(self.id)
.flex()
.flex_col()
.gap_0p5()
.text_size(theme.sizes.medium.text_size)
.refine_style(&self.style)
.track_focus(&focus)
.focusable()
.tab_stop(true)
.role(Role::List)
.aria_label(label)
.on_key_down({
let selected = self.selected;
let on_change = self.on_change.clone();
move |event: &KeyDownEvent, window, cx| {
if nav_key(&selectable, selected, &event.keystroke.key, |next| {
if let Some(on_change) = &on_change {
on_change(next, window, cx);
}
}) {
cx.stop_propagation();
}
}
})
.children(rows)
}
}
impl ListItem {
fn render_row(
&self,
cx: &App,
index: usize,
count: usize,
selected: bool,
on_change: &Option<ChangeHandler>,
focus: &FocusHandle,
) -> AnyElement {
let theme = cx.theme();
let label_color = selectable_label_color(cx, selected, self.disabled);
let disabled = self.disabled;
div()
.id((self.key.clone(), "list-item"))
.flex()
.items_center()
.gap_2()
.px_2()
.py_1()
.min_h(theme.sizes.medium.control_height)
.rounded(theme.radius.sm)
.role(Role::ListItem)
.aria_selected(selected)
.aria_position_in_set(index + 1)
.aria_size_of_set(count)
.map(|row| paint_selectable_row(cx, row, selected, disabled))
.when(!disabled, |row| {
row.cursor_pointer().on_click({
let on_change = on_change.clone();
let focus = focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if let Some(on_change) = &on_change {
on_change(Some(index), window, cx);
}
}
})
})
.when_some(self.icon.clone(), |row, icon| {
row.child(icon.size(theme.sizes.medium.icon_size).color(label_color))
})
.child(
div()
.flex_1()
.text_color(label_color)
.child(self.label.clone()),
)
.when_some(self.detail.clone(), |row, detail| {
row.child(
div()
.flex_none()
.typeset(TextRole::Subheadline, cx)
.text_color(if selected {
theme.colors.primary_foreground
} else {
theme.colors.muted_foreground
})
.child(detail),
)
})
.into_any_element()
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+47
View File
@@ -0,0 +1,47 @@
//! The components every application needs.
pub mod alert;
pub mod avatar;
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 kbd;
pub mod link;
pub mod list;
pub mod markdown;
pub mod menu;
pub mod popover;
pub mod progress;
pub mod radio;
pub mod scroll_area;
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;
+267
View File
@@ -0,0 +1,267 @@
//! 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 gpui::prelude::FluentBuilder as _;
use gpui::{
Animation, AnimationExt as _, AnyElement, App, Bounds, DispatchPhase, ElementId,
InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent,
ParentElement as _, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Window, anchored, canvas, deferred, div, ease_out_quint, point,
px,
};
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<dyn Fn(bool, &mut Window, &mut App)>;
/// The element the panel anchors below, built during render.
type TriggerFn = Box<dyn FnOnce(&mut Window, &mut App) -> AnyElement>;
/// The panel's contents, built when it opens.
type ContentFn = Box<dyn FnOnce(&mut Window, &mut App) -> AnyElement>;
/// Bounds captured during the last paint, shared with the dismissal listener.
type BoundsCell = Rc<RefCell<Option<Bounds<Pixels>>>>;
/// A floating panel anchored below its trigger.
#[derive(IntoElement)]
#[must_use]
pub struct Popover {
id: ElementId,
open: bool,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
trigger: Option<TriggerFn>,
content: Option<ContentFn>,
style: StyleRefinement,
}
impl Popover {
/// Creates a closed popover.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
open: false,
a11y_label: None,
on_change: None,
trigger: None,
content: None,
style: StyleRefinement::default(),
}
}
/// Sets the current open state.
pub fn open(mut self, open: bool) -> Self {
self.open = open;
self
}
/// Reports the next open state, from dismissals and app changes alike.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(bool, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Sets the element the panel anchors below, rendered in place.
pub fn trigger<F>(mut self, trigger: F) -> Self
where
F: FnOnce(&mut Window, &mut App) -> AnyElement + 'static,
{
self.trigger = Some(Box::new(trigger));
self
}
/// Sets the panel's contents.
pub fn content<F>(mut self, content: F) -> Self
where
F: FnOnce(&mut Window, &mut App) -> AnyElement + 'static,
{
self.content = Some(Box::new(content));
self
}
/// Overrides the accessibility label of the panel.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl gpui::Styled for Popover {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Popover {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let (colors, radius, shadows, enter_duration, panel_border) = {
let theme = cx.theme();
(
theme.colors,
theme.radius,
theme.elevations.popover.shadows(),
theme.motion.overlay,
theme.colors.border,
)
};
let trigger_bounds: BoundsCell = Rc::new(RefCell::new(None));
let fallback_label = self
.a11y_label
.clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
div()
.relative()
.refine_style(&self.style)
.child(
canvas(
{
let cell = trigger_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
{
let on_change = self.on_change.clone();
let open = self.open;
let cell = trigger_bounds.clone();
move |_, _, window, _cx| {
window.on_mouse_event({
let on_change = on_change.clone();
let trigger_bounds = cell;
move |event: &MouseDownEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble
|| event.button != MouseButton::Left
{
return;
}
let on_trigger = trigger_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position));
if !on_trigger {
return;
}
if let Some(on_change) = &on_change {
on_change(!open, window, cx);
}
cx.stop_propagation();
}
});
}
},
)
.absolute()
.inset_0(),
)
.when_some(self.trigger, |wrapper, trigger| {
wrapper.child(trigger(window, cx))
})
.when(self.open, |wrapper| {
let on_change = self.on_change;
let label = fallback_label.clone();
let focus = crate::components::common::focus_handle(&self.id, window, cx);
let content = self.content.map(|content| content(window, cx));
let panel = v_flex()
.id("popover-panel")
.debug_selector(|| "popover-panel".to_string())
.occlude()
.track_focus(&focus)
.role(Role::Dialog)
.aria_label(label)
.min_w(POPOVER_MIN_WIDTH)
.bg(colors.surface)
.text_color(colors.surface_foreground)
.rounded(radius.overlay)
.border_1()
.border_color(panel_border)
.shadow(shadows)
.overflow_hidden()
.on_mouse_down_out({
let on_change = on_change.clone();
let trigger_bounds = trigger_bounds.clone();
move |event, window, cx| {
if trigger_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position))
{
return;
}
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
}
})
.on_key_down({
let on_change = on_change.clone();
move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "escape" {
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
cx.stop_propagation();
}
}
})
.when_some(content, |panel, content| panel.child(content))
.child(
canvas(|_, _, _| {}, {
let focus = focus;
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
wrapper.child(
deferred(anchored().offset(point(Pixels::ZERO, px(4.))).child(
panel.with_animation(
"popover-enter",
Animation::new(enter_duration).with_easing(ease_out_quint()),
|panel, delta| panel.opacity(delta),
),
))
.with_priority(OVERLAY_LAYER),
)
})
}
}
+133
View File
@@ -0,0 +1,133 @@
//! 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 gpui::prelude::FluentBuilder as _;
use gpui::{
Animation, AnimationExt as _, App, ElementId, InteractiveElement as _, IntoElement,
ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Window, div, relative,
};
use crate::components::common::{Sizable, StyledExt as _};
use crate::theme::{ActiveTheme as _, PROGRESS_ANIMATION_PERIOD, Size};
/// A bar that paints a determinate fill from its `value`, or an indeterminate sweep.
#[derive(IntoElement)]
#[must_use]
pub struct Progress {
id: ElementId,
value: f32,
indeterminate: bool,
size: Size,
a11y_label: Option<SharedString>,
style: StyleRefinement,
}
impl Progress {
/// Creates a determinate progress bar at `value` (`0..=1`).
pub fn new<I>(id: I, value: f32) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
value,
indeterminate: false,
size: Size::default(),
a11y_label: None,
style: StyleRefinement::default(),
}
}
/// Sweeps instead of painting a fill, for work of unknown length.
pub fn indeterminate(mut self, indeterminate: bool) -> Self {
self.indeterminate = indeterminate;
self
}
/// Sets the accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl gpui::Styled for Progress {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Progress {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Progress {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let radius = theme.radius;
let metrics = theme.sizes.resolve(self.size);
let track_height = metrics.icon_size / 4.0;
let value = self.value.clamp(0.0, 1.0);
div()
.id(self.id)
.w_full()
.refine_style(&self.style)
.role(Role::ProgressIndicator)
.when_some(self.a11y_label, |progress, label| {
progress.aria_label(label)
})
.when(!self.indeterminate, |progress| {
progress
.aria_numeric_value(f64::from(value))
.aria_min_numeric_value(0.0)
.aria_max_numeric_value(1.0)
})
.child(
div()
.w_full()
.h(track_height)
.rounded(radius.full)
.bg(colors.border)
.child(if self.indeterminate {
div()
.h_full()
.w(relative(0.3))
.rounded(radius.full)
.bg(ramps.primary.base)
.with_animation(
"indeterminate",
Animation::new(PROGRESS_ANIMATION_PERIOD)
.repeat()
.with_max_fps(30.),
|pill, delta| pill.ml(relative(delta * 0.7)),
)
.into_any_element()
} else {
div()
.h_full()
.w(relative(value))
.rounded(radius.full)
.bg(ramps.primary.base)
.into_any_element()
}),
)
}
}
+255
View File
@@ -0,0 +1,255 @@
//! 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 gpui::prelude::FluentBuilder;
use gpui::{
App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window,
div,
};
use crate::components::common::{Sizable, StyledExt as _, focus_ring, h_flex, v_flex};
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
/// The group's change reporter, fired with the clicked radio's value.
type ChangeHandler<V> = std::rc::Rc<dyn Fn(V, &mut Window, &mut App)>;
/// 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.
#[must_use]
pub struct Radio<V> {
id: ElementId,
value: V,
label: Option<SharedString>,
disabled: bool,
a11y_label: Option<SharedString>,
}
impl<V> Radio<V>
where
V: Clone + PartialEq + 'static,
{
/// Creates a radio representing `value`.
pub fn new<I>(id: I, value: V) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
value,
label: None,
disabled: false,
a11y_label: None,
}
}
/// Sets the visible label; clicking it selects the radio too.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Renders the radio inert, unfocusable, and dimmed.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
// Radio is a data builder, not an element, adopt the combinators explicitly.
impl<V> FluentBuilder for Radio<V> {}
/// A set of [`Radio`] choices that reports clicks through [`RadioGroup::on_change`].
#[derive(IntoElement)]
#[must_use]
pub struct RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
id: ElementId,
selected: Option<V>,
children: Vec<Radio<V>>,
size: Size,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler<V>>,
style: StyleRefinement,
}
impl<V> RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
/// Creates an empty group with nothing selected.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
selected: None,
children: Vec::new(),
size: Size::default(),
a11y_label: None,
on_change: None,
style: StyleRefinement::default(),
}
}
/// Sets the currently selected value.
pub fn selected(mut self, selected: Option<V>) -> Self {
self.selected = selected;
self
}
/// Adds a radio to the group.
pub fn child(mut self, radio: Radio<V>) -> Self {
self.children.push(radio);
self
}
/// Sets the group's accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Sets the handler fired with the clicked radio's value.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(V, &mut Window, &mut App) + 'static,
{
self.on_change = Some(std::rc::Rc::new(handler));
self
}
}
impl<V> Sizable for RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl<V> gpui::Styled for RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl<V> RenderOnce for RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let radius = theme.radius;
let metrics = theme.sizes.resolve(self.size);
let selected = self.selected;
let on_change = self.on_change;
let group_label = self.a11y_label;
v_flex()
.id(self.id)
.gap_2()
.text_size(metrics.text_size)
.refine_style(&self.style)
.role(Role::RadioGroup)
.when_some(group_label.clone(), |group, label| group.aria_label(label))
.children(self.children.into_iter().map(move |radio| {
let is_selected = selected.as_ref() == Some(&radio.value);
let disabled = radio.disabled;
let row_on_change = on_change.clone();
let a11y_label = radio
.a11y_label
.or(radio.label.clone())
.or_else(|| group_label.clone());
h_flex()
.id(radio.id)
.gap_2()
.role(Role::RadioButton)
.when_some(a11y_label, |row, label| row.aria_label(label))
.aria_toggled(Toggled::from(is_selected))
.when(disabled, |row| row.opacity(DISABLED_OPACITY))
.when(!disabled, move |row| {
let value = radio.value.clone();
row.cursor_pointer()
.focusable()
.tab_stop(true)
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.when_some(row_on_change, |row, on_change| {
row.on_click(move |_, window, cx| {
on_change(value.clone(), window, cx)
})
})
})
.child(
h_flex()
.justify_center()
.flex_none()
.size(metrics.indicator_size)
.rounded(radius.full)
.border_1()
.when(is_selected, |indicator| {
indicator
.bg(ramps.primary.base)
.border_color(ramps.primary.base)
.hover(|style| {
style
.bg(ramps.primary.hover)
.border_color(ramps.primary.hover)
})
.child(
div()
.size(metrics.indicator_size / 2.0)
.rounded(radius.full)
.bg(colors.primary_foreground),
)
})
.when(!is_selected, |indicator| {
indicator
.bg(colors.input)
.border_color(colors.border)
.hover(|style| style.border_color(colors.muted_foreground))
}),
)
.when_some(radio.label, |row, label| row.child(label))
}))
}
}
+156
View File
@@ -0,0 +1,156 @@
//! 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::{
App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce, ScrollHandle,
SharedString, StatefulInteractiveElement as _, Styled, Window, div,
};
use crate::components::common::StyledExt;
use crate::components::scrollbar::{Scrollbar, ScrollbarVisibility};
/// Which directions the content scrolls in.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ScrollAxes {
/// Vertical only; the default.
#[default]
Vertical,
/// Horizontal only.
Horizontal,
/// Both directions.
Both,
}
/// A scrollable container with an overlay scrollbar.
#[derive(IntoElement)]
#[must_use]
pub struct ScrollArea {
id: ElementId,
handle: Option<ScrollHandle>,
axes: ScrollAxes,
visibility: ScrollbarVisibility,
a11y_label: Option<SharedString>,
style: gpui::StyleRefinement,
children: Vec<gpui::AnyElement>,
}
impl ParentElement for ScrollArea {
fn extend(&mut self, children: impl IntoIterator<Item = gpui::AnyElement>) {
self.children.extend(children);
}
}
impl Styled for ScrollArea {
fn style(&mut self) -> &mut gpui::StyleRefinement {
&mut self.style
}
}
impl ScrollArea {
/// Creates a vertically scrolling area.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
handle: None,
axes: ScrollAxes::Vertical,
visibility: ScrollbarVisibility::default(),
a11y_label: None,
style: gpui::StyleRefinement::default(),
children: Vec::new(),
}
}
/// Sets which directions the content scrolls in.
pub fn axes(mut self, axes: ScrollAxes) -> Self {
self.axes = axes;
self
}
/// Overrides when the scrollbar shows, instead of the platform default.
pub fn visibility(mut self, visibility: ScrollbarVisibility) -> Self {
self.visibility = visibility;
self
}
/// Scrolls with a handle held on the owning view.
pub fn handle(mut self, handle: ScrollHandle) -> Self {
self.handle = Some(handle);
self
}
/// Overrides the accessibility label of the container.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl RenderOnce for ScrollArea {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
let mut pane_style = self.style.clone();
pane_style.padding = Default::default();
let pane = div()
.id(self.id.clone())
.h_full()
.overflow_hidden()
.when(self.axes != ScrollAxes::Horizontal, |area| {
area.overflow_y_scroll()
})
.when(self.axes != ScrollAxes::Vertical, |area| {
area.overflow_x_scroll()
})
.when_some(self.handle.clone(), |area, handle| {
area.track_scroll(&handle)
})
.when_some(self.a11y_label, |area, label| area.aria_label(label))
.on_scroll(|_, _, cx| {
// Keep wheel events from scrolling an outer scroll area too.
cx.stop_propagation();
})
.refine_style(&pane_style)
.children(self.children);
div()
.relative()
.refine_style(&self.style)
.child(pane.into_any_element())
.when_some(self.handle, |wrapper, handle| {
let id = self.id.clone();
wrapper
.when(self.axes != ScrollAxes::Horizontal, |wrapper| {
wrapper.child(
Scrollbar::vertical((id.clone(), "v-scrollbar"), handle.clone())
.visibility(self.visibility)
.into_any_element(),
)
})
.when(self.axes != ScrollAxes::Vertical, |wrapper| {
wrapper.child(
Scrollbar::horizontal((id, "h-scrollbar"), handle)
.visibility(self.visibility)
.into_any_element(),
)
})
})
}
}
+536
View File
@@ -0,0 +1,536 @@
//! 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 gpui::{
App, Bounds, DispatchPhase, ElementId, Entity, EntityId, IntoElement, ListState, MouseButton,
MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, RenderOnce, ScrollEvent,
ScrollHandle, SharedString, Styled as _, Task, UniformListScrollHandle, Window, canvas, fill,
point,
};
use crate::components::common::ResultLogErr as _;
use crate::theme::{ActiveTheme as _, SCROLLBAR_AUTOHIDE_DELAY, SCROLLBAR_FADE_DURATION};
/// 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,
}
/// How often the autohide fade repaints while it runs.
const FADE_STEP: Duration = Duration::from_millis(50);
/// The shared autohide timeline for an overlay scrollbar.
#[derive(Clone)]
struct Autohide {
view: EntityId,
state: Entity<AutohideState>,
}
struct AutohideState {
last_activity: Option<Instant>,
hide_task: Option<Task<()>>,
}
impl Autohide {
fn new(key: ElementId, window: &mut Window, cx: &mut App) -> Self {
let view = window.current_view();
let state = window.use_keyed_state(key, cx, |_, _| AutohideState {
last_activity: None,
hide_task: None,
});
Self { view, state }
}
/// Marks interaction.
fn touch(&self, window: &mut Window, cx: &mut App) {
let view = self.view;
let reduce_motion = cx.theme().accessibility.reduce_motion;
let task = window.spawn(cx, async move |cx| {
if reduce_motion {
cx.background_executor()
.timer(SCROLLBAR_AUTOHIDE_DELAY + SCROLLBAR_FADE_DURATION)
.await;
cx.update(|_, cx| cx.notify(view)).log_err();
return;
}
let steps = (SCROLLBAR_FADE_DURATION.as_millis() / FADE_STEP.as_millis()).max(1);
cx.background_executor()
.timer(SCROLLBAR_AUTOHIDE_DELAY)
.await;
for _ in 0..steps {
cx.update(|_, cx| cx.notify(view)).log_err();
cx.background_executor().timer(FADE_STEP).await;
}
cx.update(|_, cx| cx.notify(view)).log_err();
});
self.state.update(cx, |state, _| {
state.last_activity = Some(Instant::now());
state.hide_task = Some(task);
});
}
/// The thumb's opacity.
fn alpha(&self, cx: &App, dragging: bool) -> f32 {
if dragging {
return 1.0;
}
let Some(activity) = self.state.read(cx).last_activity else {
return 0.0;
};
let idle = activity.elapsed();
if idle <= SCROLLBAR_AUTOHIDE_DELAY {
return 1.0;
}
let fade = idle.saturating_sub(SCROLLBAR_AUTOHIDE_DELAY);
if fade >= SCROLLBAR_FADE_DURATION {
return 0.0;
}
1.0 - fade.as_secs_f32() / SCROLLBAR_FADE_DURATION.as_secs_f32()
}
}
/// The scroll state a scrollbar drives, implemented for gpui's scroll handles.
pub trait ScrollbarHandle: 'static {
/// How far the content can scroll, positive along each axis.
fn max_offset(&self) -> Point<Pixels>;
/// The current offset, non-positive along each axis.
fn offset(&self) -> Point<Pixels>;
/// Applies the offset along one axis, keeping the other.
fn set_offset(&self, offset: Point<Pixels>);
/// The bounds of the scrolled surface.
fn viewport(&self) -> Bounds<Pixels>;
/// A thumb drag began.
fn drag_started(&self) {}
/// A thumb drag ended.
fn drag_ended(&self) {}
}
impl ScrollbarHandle for ScrollHandle {
fn max_offset(&self) -> Point<Pixels> {
ScrollHandle::max_offset(self)
}
fn offset(&self) -> Point<Pixels> {
ScrollHandle::offset(self)
}
fn set_offset(&self, offset: Point<Pixels>) {
ScrollHandle::set_offset(self, offset);
}
fn viewport(&self) -> Bounds<Pixels> {
self.bounds()
}
}
impl ScrollbarHandle for UniformListScrollHandle {
fn max_offset(&self) -> Point<Pixels> {
self.0.borrow().base_handle.max_offset()
}
fn offset(&self) -> Point<Pixels> {
self.0.borrow().base_handle.offset()
}
fn set_offset(&self, offset: Point<Pixels>) {
self.0.borrow().base_handle.set_offset(offset);
}
fn viewport(&self) -> Bounds<Pixels> {
self.0.borrow().base_handle.bounds()
}
}
impl ScrollbarHandle for ListState {
fn max_offset(&self) -> Point<Pixels> {
ListState::max_offset_for_scrollbar(self)
}
fn offset(&self) -> Point<Pixels> {
ListState::scroll_px_offset_for_scrollbar(self)
}
fn set_offset(&self, offset: Point<Pixels>) {
ListState::set_offset_from_scrollbar(self, offset);
}
fn viewport(&self) -> Bounds<Pixels> {
self.viewport_bounds()
}
fn drag_started(&self) {
ListState::scrollbar_drag_started(self);
}
fn drag_ended(&self) {
ListState::scrollbar_drag_ended(self);
}
}
/// Which direction the scrollbar lies along.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Axis {
Vertical,
Horizontal,
}
impl Axis {
fn along(self, position: Point<Pixels>) -> Pixels {
match self {
Axis::Vertical => position.y,
Axis::Horizontal => position.x,
}
}
fn with_along(self, position: Point<Pixels>, along: Pixels) -> Point<Pixels> {
match self {
Axis::Vertical => point(position.x, along),
Axis::Horizontal => point(along, position.y),
}
}
fn viewport_along(self, viewport: &Bounds<Pixels>) -> Pixels {
match self {
Axis::Vertical => viewport.size.height,
Axis::Horizontal => viewport.size.width,
}
}
}
/// An overlay scrollbar, rendered over the scrolled surface.
#[derive(IntoElement)]
#[must_use]
pub struct Scrollbar {
axis: Axis,
handle: Rc<dyn ScrollbarHandle>,
visibility: ScrollbarVisibility,
id: ElementId,
}
impl Scrollbar {
/// Creates a vertical scrollbar named by `id`, driven by `handle`.
pub fn vertical<I, H>(id: I, handle: H) -> Self
where
I: Into<ElementId>,
H: ScrollbarHandle,
{
Self {
axis: Axis::Vertical,
handle: Rc::new(handle),
visibility: ScrollbarVisibility::default(),
id: id.into(),
}
}
/// Creates a horizontal scrollbar named by `id`, driven by `handle`.
pub fn horizontal<I, H>(id: I, handle: H) -> Self
where
I: Into<ElementId>,
H: ScrollbarHandle,
{
Self {
axis: Axis::Horizontal,
handle: Rc::new(handle),
visibility: ScrollbarVisibility::default(),
id: id.into(),
}
}
/// Overrides when the scrollbar shows, instead of the platform default.
pub fn visibility(mut self, visibility: ScrollbarVisibility) -> Self {
self.visibility = visibility;
self
}
fn state_key(name: &'static str, id: &ElementId) -> ElementId {
ElementId::NamedChild(Arc::new(id.clone()), SharedString::from(name))
}
/// Pure thumb geometry for an overlay scrollbar.
fn thumb_geometry(
viewport: Pixels,
content: Pixels,
offset: Pixels,
track: Pixels,
min_thumb: Pixels,
) -> (Pixels, Pixels) {
if content <= viewport || content <= Pixels::ZERO {
return (track, Pixels::ZERO);
}
let length = (viewport / content * track).max(min_thumb).min(track);
let overflow = content - viewport;
let progress = (-offset / overflow).clamp(0., 1.);
let travel = track - length;
(length, travel * progress)
}
/// An overlay scrollbar thumb's style for one paint: `None` hides it.
fn thumb_style(color: gpui::Hsla, alpha: f32) -> Option<gpui::Hsla> {
(alpha > 0.0).then_some(gpui::Hsla {
a: color.a * alpha,
..color
})
}
}
impl RenderOnce for Scrollbar {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
canvas(|_, _, _| {}, {
let handle = self.handle;
let axis = self.axis;
let visibility = self.visibility;
let id = self.id;
move |_, _, window, cx| Self::paint(&handle, axis, visibility, &id, window, cx)
})
.absolute()
.inset_0()
}
}
/// The drag state shared between the scrollbar's mouse handlers.
type Drag = Option<(Pixels, Pixels)>;
impl Scrollbar {
fn paint(
handle: &Rc<dyn ScrollbarHandle>,
axis: Axis,
visibility: ScrollbarVisibility,
id: &ElementId,
window: &mut Window,
cx: &mut App,
) {
let view = window.current_view();
let theme = cx.theme();
let color = theme.colors.scrollbar_thumb;
let width = theme.scrollbar.width;
let inset = theme.scrollbar.inset;
let min_thumb = theme.scrollbar.min_thumb;
let viewport = handle.viewport();
let viewport_along = axis.viewport_along(&viewport);
let max_offset = axis.along(handle.max_offset());
if max_offset <= Pixels::ZERO || viewport_along <= Pixels::ZERO {
return;
}
let autohide = match visibility {
ScrollbarVisibility::Platform => theme.scrollbar.autohide,
ScrollbarVisibility::Always => false,
ScrollbarVisibility::Autohide => true,
};
let autohide_state =
autohide.then(|| Autohide::new(Self::state_key("autohide", id), window, cx));
let track_length = viewport_along - inset * 2.0;
let (thumb_length, thumb_travel) = Self::thumb_geometry(
viewport_along,
viewport_along + max_offset,
axis.along(handle.offset()),
track_length,
min_thumb,
);
// The track strip is the thumb's rail plus the padding the thumb rides inside.
let (thumb_bounds, track_bounds) = match axis {
Axis::Vertical => {
let thumb_x = viewport.right() - width - inset;
(
Bounds::from_corners(
point(thumb_x, viewport.top() + inset + thumb_travel),
point(
thumb_x + width,
viewport.top() + inset + thumb_travel + thumb_length,
),
),
Bounds::from_corners(
point(viewport.right() - width, viewport.top() + inset),
point(viewport.right(), viewport.top() + inset + track_length),
),
)
}
Axis::Horizontal => {
let thumb_y = viewport.bottom() - width - inset;
(
Bounds::from_corners(
point(viewport.left() + inset + thumb_travel, thumb_y),
point(
viewport.left() + inset + thumb_travel + thumb_length,
thumb_y + width,
),
),
Bounds::from_corners(
point(viewport.left() + inset, viewport.bottom() - width),
point(viewport.left() + inset + track_length, viewport.bottom()),
),
)
}
};
let drag = window.use_keyed_state(Self::state_key("thumb-drag", id), cx, |_, _| Drag::None);
let dragging = drag.read(cx).is_some();
let alpha = match &autohide_state {
Some(state) => state.alpha(cx, dragging),
None => 1.0,
};
if let Some(color) = Self::thumb_style(color, alpha) {
window.paint_quad(fill(thumb_bounds, color).corner_radii(width / 2.0));
}
if let Some(state) = &autohide_state {
window.on_mouse_event({
let state = state.clone();
move |event: &ScrollEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble || !viewport.contains(&event.position) {
return;
}
state.touch(window, cx);
}
});
}
window.on_mouse_event({
let handle = handle.clone();
let drag = drag.clone();
let autohide_state = autohide_state.clone();
move |event: &MouseDownEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble || event.button != MouseButton::Left {
return;
}
let in_thumb = thumb_bounds.contains(&event.position);
let in_track = !in_thumb && track_bounds.contains(&event.position);
if !in_thumb && !in_track {
return;
}
let start_offset = if in_thumb {
axis.along(handle.offset())
} else if track_length > thumb_length {
let thumb_start = ((axis.along(event.position)
- axis.along(track_bounds.origin))
- thumb_length / 2.0)
.clamp(Pixels::ZERO, track_length - thumb_length);
let offset = -(thumb_start / (track_length - thumb_length)) * max_offset;
handle.set_offset(axis.with_along(handle.offset(), offset));
cx.notify(view);
offset
} else {
return;
};
drag.update(cx, |drag, _| {
*drag = Some((axis.along(event.position), start_offset));
});
handle.drag_started();
if let Some(state) = &autohide_state {
state.touch(window, cx);
}
cx.stop_propagation();
}
});
window.on_mouse_event({
let handle = handle.clone();
let drag = drag.clone();
let autohide_state = autohide_state.clone();
move |event: &MouseMoveEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble {
return;
}
if let Some(state) = &autohide_state
&& track_bounds.contains(&event.position)
&& drag.read(cx).is_none()
{
state.touch(window, cx);
}
if event.pressed_button != Some(MouseButton::Left) {
return;
}
let Some((start_position, start_offset)) = *drag.read(cx) else {
return;
};
if track_length <= thumb_length {
return;
}
let scale = max_offset / (track_length - thumb_length);
let offset = (start_offset - (axis.along(event.position) - start_position) * scale)
.clamp(-max_offset, Pixels::ZERO);
handle.set_offset(axis.with_along(handle.offset(), offset));
cx.notify(view);
}
});
window.on_mouse_event({
let handle = handle.clone();
let drag = drag.clone();
let autohide_state = autohide_state.clone();
move |event: &MouseUpEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble || event.button != MouseButton::Left {
return;
}
if drag.read(cx).is_none() {
return;
}
drag.update(cx, |drag, _| {
*drag = None;
});
handle.drag_ended();
// Unfreezing a ListState's height can change the thumb's geometry.
cx.notify(view);
if let Some(state) = &autohide_state {
state.touch(window, cx);
}
}
});
}
}
+374
View File
@@ -0,0 +1,374 @@
//! 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 gpui::prelude::FluentBuilder;
use gpui::{
AnimationExt as _, App, Bounds, ElementId, Entity, InteractiveElement as _, IntoElement,
KeyDownEvent, ParentElement as _, Point, RenderOnce, Role, SharedString, SpringAnimation,
StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window, canvas, div,
};
use crate::components::common::{Sizable, StyledExt, focus_handle, focus_ring, h_flex};
use crate::icons::Icon;
use crate::theme::{ActiveTheme as _, CONTROL_SPRING, Size};
/// Reports the segment the user chose.
type ChangeHandler<T> = Rc<dyn Fn(T, &mut Window, &mut App)>;
/// One choice in a [`Segmented`] strip.
#[derive(Clone)]
#[must_use]
pub struct SegmentedOption<T> {
value: T,
label: SharedString,
icon: Option<Icon>,
}
impl<T> SegmentedOption<T> {
/// Creates a choice showing `label`; picking it reports `value`.
pub fn new<L>(value: T, label: L) -> Self
where
L: Into<SharedString>,
{
Self {
value,
label: label.into(),
icon: None,
}
}
/// Sets a leading icon for the segment.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
}
/// Converts a `(value, label)` pair into an option.
impl<T, L> From<(T, L)> for SegmentedOption<T>
where
L: Into<SharedString>,
{
fn from((value, label): (T, L)) -> Self {
Self {
value,
label: label.into(),
icon: None,
}
}
}
// SegmentedOption is a data builder, not an element, adopt the combinators explicitly.
impl<T> FluentBuilder for SegmentedOption<T> {}
/// A pill strip of mutually exclusive choices.
#[derive(IntoElement)]
#[must_use]
pub struct Segmented<T>
where
T: Clone + PartialEq + 'static,
{
id: ElementId,
/// Shared with the per-segment and key handlers, so captures are bumps.
options: Rc<[SegmentedOption<T>]>,
selected: T,
a11y_label: Option<SharedString>,
size: Size,
style: StyleRefinement,
on_change: Option<ChangeHandler<T>>,
}
impl<T> Segmented<T>
where
T: Clone + PartialEq + 'static,
{
/// Creates a strip with `selected` chosen.
pub fn new<I>(id: I, selected: T) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
options: Rc::from([]),
selected,
a11y_label: None,
size: Size::Small,
style: StyleRefinement::default(),
on_change: None,
}
}
/// Sets the choices from [`SegmentedOption`]s or `(value, label)` pairs.
pub fn options<I>(mut self, options: I) -> Self
where
I: IntoIterator,
I::Item: Into<SegmentedOption<T>>,
{
self.options = options.into_iter().map(Into::into).collect();
self
}
/// Reports the segment chosen, by pointer or by arrow.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(T, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Overrides the strip's accessibility label, which defaults to the element id.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl<T> Sizable for Segmented<T>
where
T: Clone + PartialEq + 'static,
{
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl<T> gpui::Styled for Segmented<T>
where
T: Clone + PartialEq + 'static,
{
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl<T> RenderOnce for Segmented<T>
where
T: Clone + PartialEq + 'static,
{
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let metrics = theme.sizes.resolve(self.size);
let muted = theme.colors.muted;
let surface = theme.colors.surface;
let foreground = theme.colors.foreground;
let muted_foreground = theme.colors.muted_foreground;
let ring = theme.colors.ring;
let radius = theme.radius.full;
let plate_shadow = theme.elevations.control.shadows();
let track_height = metrics.strip_height;
let track_inset = metrics.plate_inset;
let horizontal_padding = metrics.dense_padding_x;
let text_size = metrics.text_size;
let icon_size = metrics.icon_size;
let selected_index = self
.options
.iter()
.position(|segment| segment.value == self.selected);
let option_count = self.options.len();
let on_change = self.on_change.clone();
let key_on_change = on_change.clone();
let key_options = self.options.clone();
let options = self.options.clone();
let label = self
.a11y_label
.clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
window.with_element_namespace(self.id.clone(), |window| {
let geometry: Entity<Vec<Option<Bounds<gpui::Pixels>>>> =
window.use_keyed_state("segmented-geometry", cx, |_, _| Vec::new());
let track_origin: Entity<Option<Point<gpui::Pixels>>> =
window.use_keyed_state("segmented-track-origin", cx, |_, _| None);
let focus = focus_handle(&self.id, window, cx);
let track_point = *track_origin.read(cx);
let plate_target = geometry
.read(cx)
.get(selected_index.unwrap_or(usize::MAX))
.copied()
.flatten()
.zip(track_point)
.map(|(bounds, track)| (bounds.origin.x - track.x, bounds.size.width));
let segments = self
.options
.iter()
.enumerate()
.map(move |(index, segment)| {
let is_selected = Some(index) == selected_index;
let on_change = on_change.clone();
let options = options.clone();
let content_color = if is_selected {
foreground
} else {
muted_foreground
};
h_flex()
.id((ElementId::from("segment"), segment.label.clone()))
.gap_2()
.justify_center()
.cursor_pointer()
.h_full()
.px(horizontal_padding)
.rounded(radius)
.text_size(text_size)
.text_color(content_color)
.when(!is_selected, |segment| {
segment.hover(|style| style.bg(surface))
})
.role(Role::RadioButton)
.aria_label(segment.label.clone())
.aria_toggled(Toggled::from(is_selected))
.when_some(segment.icon.clone(), |segment, icon| {
segment.child(icon.size(icon_size).color(content_color))
})
.child(segment.label.clone())
.child(
canvas(
{
let geometry = geometry.clone();
move |bounds, _, cx| {
geometry.update(cx, |geometry, _| {
if geometry.len() <= index {
geometry.resize(index + 1, None);
}
geometry[index] = Some(bounds);
});
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
.on_click({
move |_, window, cx| {
if Some(index) != selected_index
&& let Some(on_change) = &on_change
&& let Some(option) = options.get(index)
{
on_change(option.value.clone(), window, cx);
}
}
})
});
div().child(
div()
.id(self.id.clone())
.track_focus(&focus)
.focusable()
.tab_stop(true)
.focus_visible(|style| style.shadow(focus_ring(ring)))
.role(Role::RadioGroup)
.aria_label(label)
.flex()
.items_center()
.gap_1()
.relative()
.flex_none()
.h(track_height)
.p(track_inset)
.rounded(radius)
.bg(muted)
.text_size(metrics.text_size)
.child(
canvas(
{
let track_origin = track_origin.clone();
move |bounds, _, cx| {
track_origin
.update(cx, |origin, _| *origin = Some(bounds.origin));
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
.when_some(plate_target, |track, (x, width)| {
track.child(
div()
.id("segmented-plate")
.debug_selector(|| "segmented-plate".to_string())
.absolute()
.top(track_inset)
.bottom(track_inset)
.rounded(radius)
.bg(surface)
.shadow(plate_shadow.clone())
.with_spring(
"segmented-plate-x",
SpringAnimation::new(CONTROL_SPRING).to(x),
|plate, x| plate.left(x),
)
.with_spring(
"segmented-plate-w",
SpringAnimation::new(CONTROL_SPRING).to(width),
|spring_plate, width| {
spring_plate.map_element(move |plate| plate.w(width))
},
),
)
})
.on_key_down({
move |event: &KeyDownEvent, window, cx| {
let target = match event.keystroke.key.as_str() {
"right" => match selected_index {
Some(index) => {
index.checked_add(1).filter(|next| *next < option_count)
}
None => (option_count > 0).then_some(0),
},
"left" => selected_index.and_then(|index| index.checked_sub(1)),
"home" => (option_count > 0).then_some(0),
"end" => option_count.checked_sub(1),
_ => return,
};
if let Some(next) = target
&& Some(next) != selected_index
&& let Some(on_change) = &key_on_change
&& let Some(option) = key_options.get(next)
{
on_change(option.value.clone(), window, cx);
}
cx.stop_propagation();
}
})
.children(segments)
.refine_style(&self.style),
)
})
}
}
+363
View File
@@ -0,0 +1,363 @@
//! 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 gpui::prelude::FluentBuilder;
use gpui::{
App, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, ParentElement as _,
RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
Window, canvas,
};
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};
/// Reports the value the user chose. `None` means the select holds no value.
pub type SelectHandler<T> = Rc<dyn Fn(Option<T>, &mut Window, &mut App)>;
/// Select option for a [`Select`] control.
#[derive(Clone)]
#[must_use]
pub struct SelectOption<T> {
value: T,
label: SharedString,
icon: Option<Icon>,
}
impl<T> SelectOption<T> {
/// Creates a choice showing `label`; picking it reports `value`.
pub fn new<L>(value: T, label: L) -> Self
where
L: Into<SharedString>,
{
Self {
value,
label: label.into(),
icon: None,
}
}
/// Sets a leading icon for the option's row.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
}
impl<T, L> From<(T, L)> for SelectOption<T>
where
L: Into<SharedString>,
{
fn from((value, label): (T, L)) -> Self {
Self {
value,
label: label.into(),
icon: None,
}
}
}
// SelectOption is a data builder, not an element, adopt the combinators explicitly.
impl<T> FluentBuilder for SelectOption<T> {}
/// A control that shows the chosen value and opens a menu of the choices.
#[derive(IntoElement)]
#[must_use]
pub struct Select<T>
where
T: Clone + PartialEq + 'static,
{
id: ElementId,
options: Vec<SelectOption<T>>,
selected: Option<T>,
placeholder: SharedString,
a11y_label: Option<SharedString>,
size: Size,
style: StyleRefinement,
on_change: Option<SelectHandler<T>>,
}
impl<T> Select<T>
where
T: Clone + PartialEq + 'static,
{
/// Creates a closed select holding no value.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
options: Vec::new(),
selected: None,
placeholder: SharedString::from("Select..."),
a11y_label: None,
size: Size::default(),
style: StyleRefinement::default(),
on_change: None,
}
}
/// Sets the choice.
pub fn options<I>(mut self, options: I) -> Self
where
I: IntoIterator,
I::Item: Into<SelectOption<T>>,
{
self.options = options.into_iter().map(Into::into).collect();
self
}
/// Sets the current value. `None` shows the placeholder.
pub fn selected<S>(mut self, selected: S) -> Self
where
S: Into<Option<T>>,
{
self.selected = selected.into();
self
}
/// Sets the text shown while no value is chosen.
pub fn placeholder<L>(mut self, placeholder: L) -> Self
where
L: Into<SharedString>,
{
self.placeholder = placeholder.into();
self
}
/// Reports the chosen value, when the user activates an option.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(Option<T>, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Overrides the trigger's accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl<T> Sizable for Select<T>
where
T: Clone + PartialEq + 'static,
{
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl<T> gpui::Styled for Select<T>
where
T: Clone + PartialEq + 'static,
{
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl<T> RenderOnce for Select<T>
where
T: Clone + PartialEq + 'static,
{
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let metrics = theme.sizes.resolve(self.size);
let border = theme.colors.border;
let ring = theme.colors.ring;
let input = theme.colors.input;
let muted = theme.colors.muted;
let foreground = theme.colors.foreground;
let muted_foreground = theme.colors.muted_foreground;
let radius = theme.radius.control;
let icon_size = metrics.dense_icon_size;
let label = self
.a11y_label
.clone()
.unwrap_or_else(|| self.placeholder.clone());
let open = window.with_element_namespace(self.id.clone(), |window| {
window
.use_keyed_state("select-open", cx, |_, _| false)
.clone()
});
let focus = focus_handle(&self.id, window, cx);
// Set when the popup closes without an activation; the trigger claims
// focus at paint, leaving keyboard activations to drop focus in place.
let refocus_pending = window.with_element_namespace(self.id.clone(), |window| {
window
.use_keyed_state("select-refocus", cx, |_, _| false)
.clone()
});
let is_open = *open.read(cx);
let open_for_items = open.clone();
let rest_border = if is_open { ring } else { border };
let hover_border = rest_border;
let selected_index = self.selected.as_ref().and_then(|value| {
self.options
.iter()
.position(|option| &option.value == value)
});
// The trigger's text is fixed at render time; only it moves into the closure.
let trigger_text = selected_index
.and_then(|index| self.options.get(index))
.map(|option| option.label.clone())
.unwrap_or_else(|| self.placeholder.clone());
let trigger_has_value = self.selected.is_some();
let trigger_id = self.id.clone();
let trigger_label = label.clone();
let trigger_style = self.style;
let trigger = {
let open = open.clone();
let focus = focus.clone();
let refocus_for_trigger = refocus_pending.clone();
move |_window: &mut Window, _cx: &mut App| {
h_flex()
.id((trigger_id.clone(), "select-trigger"))
.debug_selector(|| "select-trigger".to_string())
.role(Role::ComboBox)
.aria_label(trigger_label.clone())
.aria_expanded(is_open)
.track_focus(&focus)
.tab_stop(true)
.focus_visible(move |style| style.border_color(ring))
.on_key_down({
let open = open.clone();
move |event: &KeyDownEvent, _window, cx| {
if !matches!(event.keystroke.key.as_str(), "enter" | "space") {
return;
}
open.update(cx, |open, _| *open = !*open);
cx.stop_propagation();
}
})
.cursor_pointer()
.justify_between()
.gap_3()
.w_full()
.h(metrics.input_height)
.pl(metrics.dense_padding_x)
.pr(metrics.plate_inset * 2.0)
.rounded(radius)
.border_1()
.border_color(rest_border)
.bg(input)
.text_size(metrics.text_size)
.text_color(if trigger_has_value {
foreground
} else {
muted_foreground
})
.hover(|style| style.bg(muted).border_color(hover_border))
.child(trigger_text.clone())
.child(
icon(IconRole::ChevronDown)
.size(icon_size)
.color(muted_foreground),
)
.child(
canvas(|_, _, _| {}, {
let focus = focus.clone();
let refocus_pending = refocus_for_trigger.clone();
move |_, _, window, cx| {
if *refocus_pending.read(cx) {
refocus_pending.update(cx, |pending, _| *pending = false);
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
)
.refine_style(&trigger_style)
.into_any_element()
}
};
let select_id = self.id.clone();
let refocus_for_items = refocus_pending.clone();
let items = move |_window: &mut Window, _cx: &mut App| {
self.options
.iter()
.enumerate()
.map(|(index, option)| {
let is_selected = self.selected.as_ref() == Some(&option.value);
let handler = {
let open = open_for_items.clone();
let refocus_pending = refocus_for_items.clone();
let value = option.value.clone();
let on_change = self.on_change.clone();
move |window: &mut Window, cx: &mut App| {
open.update(cx, |open, _| *open = false);
// Activations own the close, so no focus returns to the trigger.
refocus_pending.update(cx, |pending, _| *pending = false);
if let Some(on_change) = &on_change {
on_change(Some(value.clone()), window, cx);
}
}
};
MenuItem::new(option.label.clone())
.id((select_id.clone(), format!("option-{index}")))
.when_some(option.icon.clone(), |row, icon| row.icon(icon))
.checked(is_selected)
.handler(handler)
})
.collect()
};
let menu = Menu::new(self.id)
.open(is_open)
.on_change({
let open = open.clone();
let refocus_pending = refocus_pending.clone();
move |next, _window, cx| {
if !next {
refocus_pending.update(cx, |pending, _| *pending = true);
}
open.update(cx, |open, _| *open = next);
}
})
.trigger(trigger)
.items(items);
menu.when_some(selected_index, |menu, index| menu.initial_selection(index))
}
}
+102
View File
@@ -0,0 +1,102 @@
//! 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 gpui::prelude::FluentBuilder as _;
use gpui::{
App, InteractiveElement as _, IntoElement, RenderOnce, StyleRefinement, Styled as _, Window,
div,
};
use crate::components::common::StyledExt as _;
use crate::theme::{ActiveTheme as _, BORDER_WIDTH};
/// The axis a [`Separator`] rule runs along.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SeparatorOrientation {
/// A horizontal rule between stacked content.
#[default]
Horizontal,
/// A vertical rule between side-by-side content.
Vertical,
}
/// The debug-bounds selector, for headless tests.
type DebugSelector = Rc<dyn Fn() -> String>;
/// A hairline rule that divides sibling content.
#[derive(IntoElement)]
#[must_use]
pub struct Separator {
orientation: SeparatorOrientation,
debug_selector: Option<DebugSelector>,
style: StyleRefinement,
}
impl Separator {
/// Creates a horizontal rule.
pub fn horizontal() -> Self {
Self {
orientation: SeparatorOrientation::Horizontal,
debug_selector: None,
style: StyleRefinement::default(),
}
}
/// Creates a vertical rule.
pub fn vertical() -> Self {
Self {
orientation: SeparatorOrientation::Vertical,
debug_selector: None,
style: StyleRefinement::default(),
}
}
/// Sets which axis the rule runs along.
pub fn orientation(mut self, orientation: SeparatorOrientation) -> Self {
self.orientation = orientation;
self
}
/// Sets the debug-bounds selector, for headless tests.
pub fn debug_selector<F>(mut self, selector: F) -> Self
where
F: Fn() -> String + 'static,
{
self.debug_selector = Some(Rc::new(selector));
self
}
}
impl gpui::Styled for Separator {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Separator {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let border = cx.theme().colors.border;
div()
.flex_none()
.bg(border)
.when_some(self.debug_selector, |rule, selector| {
rule.debug_selector(move || selector())
})
.map(|rule| match self.orientation {
SeparatorOrientation::Horizontal => rule.w_full().h(BORDER_WIDTH),
SeparatorOrientation::Vertical => rule.self_stretch().w(BORDER_WIDTH),
})
.refine_style(&self.style)
}
}
+532
View File
@@ -0,0 +1,532 @@
//! 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 gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent,
ParentElement as _, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Window, div,
};
use crate::common::v_flex;
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 _};
/// The change reporter, fired with the next selected row by pointer and keys.
type ChangeHandler = Rc<dyn Fn(Option<usize>, &mut Window, &mut App)>;
/// The entries builder, run during render.
type EntriesFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<SidebarEntry>>;
/// One entry of a [`Sidebar`], a section header, a selectable row, or custom content.
#[must_use]
pub enum SidebarEntry {
/// A non-selectable section label.
Header {
label: SharedString,
prefix: Option<AnyElement>,
suffix: Option<AnyElement>,
},
/// A selectable row.
Row {
key: ElementId,
label: SharedString,
detail: Option<SharedString>,
prefix: Option<AnyElement>,
suffix: Option<AnyElement>,
disabled: bool,
},
/// Custom content occupying a slot in the list.
Custom(AnyElement),
}
impl SidebarEntry {
/// Creates a section header.
pub fn header<L>(label: L) -> Self
where
L: Into<SharedString>,
{
Self::Header {
label: label.into(),
prefix: None,
suffix: None,
}
}
/// Creates a selectable row shown as `label`, identified by `key`.
pub fn row<K, L>(key: K, label: L) -> Self
where
K: Into<ElementId>,
L: Into<SharedString>,
{
Self::Row {
key: key.into(),
label: label.into(),
detail: None,
prefix: None,
suffix: None,
disabled: false,
}
}
/// Wraps custom content occupying a slot in the list.
pub fn custom<E>(element: E) -> Self
where
E: IntoElement,
{
Self::Custom(element.into_any_element())
}
/// Shows muted trailing text.
pub fn detail<D>(mut self, detail: D) -> Self
where
D: Into<SharedString>,
{
if let Self::Row {
detail: row_detail, ..
} = &mut self
{
*row_detail = Some(detail.into());
}
self
}
/// Shows an element leading the entry.
pub fn prefix<E>(mut self, prefix: E) -> Self
where
E: IntoElement,
{
if let Self::Row { prefix: slot, .. } | Self::Header { prefix: slot, .. } = &mut self {
*slot = Some(prefix.into_any_element());
}
self
}
/// Shows an element trailing the entry.
pub fn suffix<E>(mut self, suffix: E) -> Self
where
E: IntoElement,
{
if let Self::Row { suffix: slot, .. } | Self::Header { suffix: slot, .. } = &mut self {
*slot = Some(suffix.into_any_element());
}
self
}
/// Renders the row dimmed; clicks and keyboard skip it.
pub fn disabled(mut self, disabled: bool) -> Self {
if let Self::Row {
disabled: row_disabled,
..
} = &mut self
{
*row_disabled = disabled;
}
self
}
}
// SidebarEntry is a data builder, not an element, adopt the combinators explicitly.
impl FluentBuilder for SidebarEntry {}
/// A sidebar of [`SidebarEntry`] rows grouped under section headers.
#[derive(IntoElement)]
#[must_use]
pub struct Sidebar {
id: ElementId,
selected: Option<usize>,
transparent: bool,
grain: bool,
border_right: bool,
padded: bool,
width: Pixels,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
entries: Option<EntriesFn>,
style: StyleRefinement,
}
impl Sidebar {
/// Creates a sidebar with nothing selected.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
selected: None,
transparent: false,
grain: false,
border_right: true,
padded: true,
width: SIDEBAR_DEFAULT_WIDTH,
a11y_label: None,
on_change: None,
entries: None,
style: StyleRefinement::default(),
}
}
/// Sets the current selection.
pub fn selected(mut self, selected: Option<usize>) -> Self {
self.selected = selected;
self
}
/// Paints translucent material fills so the window's native backdrop shows through.
pub fn transparent(mut self, transparent: bool) -> Self {
self.transparent = transparent;
self
}
/// Whether translucent material fills are painted.
pub fn is_transparent(&self) -> bool {
self.transparent
}
/// Textures the sidebar with a film-grain overlay.
pub fn grain(mut self, grain: bool) -> Self {
self.grain = grain;
self
}
/// Paints a hairline border on the sidebar's right edge.
pub fn border_right(mut self, border_right: bool) -> Self {
self.border_right = border_right;
self
}
/// Whether the right-edge border is painted.
pub fn has_border_right(&self) -> bool {
self.border_right
}
/// Insets the entry list from the sidebar's edges; the scrollbar stays on the edge.
pub fn padded(mut self, padded: bool) -> Self {
self.padded = padded;
self
}
/// Whether the entry list is inset from the sidebar's edges.
pub fn is_padded(&self) -> bool {
self.padded
}
/// Sets the sidebar's width, overriding the default.
pub fn width<W>(mut self, width: W) -> Self
where
W: Into<Pixels>,
{
self.width = width.into();
self
}
/// Reports the next selected row, from clicks and keys alike.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(Option<usize>, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Sets the entries; the closure runs during render and must not mutate entities or notify.
pub fn entries<F>(mut self, entries: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<SidebarEntry> + 'static,
{
self.entries = Some(Box::new(entries));
self
}
/// Overrides the accessibility label, which defaults to the id.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl gpui::Styled for Sidebar {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Sidebar {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let Self {
id,
selected,
transparent: material,
grain,
border_right,
padded,
width,
a11y_label,
on_change,
entries,
style,
} = self;
let label = a11y_label.unwrap_or_else(|| SharedString::from(id.to_string()));
let debug_id = id.clone();
let entries = match entries {
Some(build) => build(window, cx),
None => Vec::new(),
};
// Headers and custom entries are never selectable, only enabled rows are.
let selectable: Vec<usize> = entries
.iter()
.enumerate()
.filter(|(_, entry)| match entry {
SidebarEntry::Row { disabled, .. } => !disabled,
SidebarEntry::Header { .. } | SidebarEntry::Custom(_) => false,
})
.map(|(index, _)| index)
.collect();
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())
.clone()
});
let scroll_area_id = (id.clone(), "entries");
let row_count = entries
.iter()
.filter(|entry| matches!(entry, SidebarEntry::Row { .. }))
.count();
let mut row_position = 0usize;
let children: Vec<AnyElement> = entries
.into_iter()
.enumerate()
.map(|(index, entry)| {
let is_row = matches!(entry, SidebarEntry::Row { .. });
if is_row {
row_position += 1;
}
let (position_in_set, size_of_set) = if is_row {
(row_position, row_count)
} else {
(0, 0)
};
entry.render_entry(
cx,
index,
position_in_set,
size_of_set,
selected == Some(index),
material,
&on_change,
&focus,
)
})
.collect();
let body = div()
.id((id.clone(), "list"))
.flex_1()
.min_h_0()
.track_focus(&focus)
.focusable()
.tab_stop(true)
.role(Role::List)
.aria_label(label)
.on_key_down({
let on_change = on_change.clone();
move |event: &KeyDownEvent, window, cx| {
if nav_key(&selectable, selected, &event.keystroke.key, |next| {
if let Some(on_change) = &on_change {
on_change(next, window, cx);
}
}) {
cx.stop_propagation();
}
}
})
.child(
ScrollArea::new(scroll_area_id)
.handle(scroll.read(cx).clone())
.h_full()
.child(
div()
.flex()
.flex_col()
.gap_0p5()
.when(padded, |content| content.p_2())
.children(children),
),
)
.into_any_element();
let theme = cx.theme();
v_flex()
.id(id.clone())
.refine_style(&style)
.debug_selector(move || format!("sidebar-{debug_id}"))
.h_full()
.w(width)
.text_size(theme.sizes.medium.text_size)
.when(border_right, |sidebar| {
sidebar
.border_r(BORDER_WIDTH)
.border_color(theme.colors.border)
})
.child(body)
.when(material && grain, |sidebar| sidebar.child(grain_overlay()))
}
}
impl SidebarEntry {
#[allow(clippy::too_many_arguments)]
fn render_entry(
self,
cx: &App,
index: usize,
position_in_set: usize,
size_of_set: usize,
selected: bool,
material: bool,
on_change: &Option<ChangeHandler>,
focus: &FocusHandle,
) -> AnyElement {
let theme = cx.theme();
match self {
SidebarEntry::Header {
label,
prefix,
suffix,
} => {
// The id is required for the role to surface in the a11y tree.
div()
.id(("sidebar-header".into(), label.clone()))
.flex()
.items_center()
.gap_2()
.px_2()
.pt_2()
.pb_1()
.typeset(TextRole::Headline, cx)
.text_color(theme.colors.muted_foreground)
.role(Role::Heading)
.when_some(prefix, |header, prefix| header.child(prefix))
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label),
)
.when_some(suffix, |header, suffix| header.child(suffix))
.into_any_element()
}
SidebarEntry::Custom(element) => element,
SidebarEntry::Row {
key,
label,
detail,
prefix,
suffix,
disabled: row_disabled,
} => {
let label_color = selectable_label_color(cx, selected, row_disabled);
div()
.id((key.clone(), "sidebar-row"))
.flex()
.items_center()
.gap_2()
.px_2()
.py_1()
.min_h(theme.sizes.medium.control_height)
.rounded(theme.radius.sm)
.text_color(label_color)
.role(Role::ListItem)
.aria_selected(selected)
.aria_position_in_set(position_in_set)
.aria_size_of_set(size_of_set)
.map(|row| {
if material && !row_disabled {
if selected {
row.bg(theme.material.selection)
} else {
row.hover(|row| row.bg(theme.material.hover))
}
} else {
paint_selectable_row(cx, row, selected, row_disabled)
}
})
.when(!row_disabled, |row| {
row.cursor_pointer().on_click({
let on_change = on_change.clone();
let focus = focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if let Some(on_change) = &on_change {
on_change(Some(index), window, cx);
}
}
})
})
.when_some(prefix, |row, prefix| row.child(prefix))
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label),
)
.when_some(detail, |row, detail| {
row.child(
div()
.flex_none()
.typeset(TextRole::Subheadline, cx)
.text_color(if selected {
theme.colors.primary_foreground
} else {
theme.colors.muted_foreground
})
.child(detail),
)
})
.when_some(suffix, |row, suffix| row.child(suffix))
.into_any_element()
}
}
}
}
+323
View File
@@ -0,0 +1,323 @@
//! 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 gpui::prelude::FluentBuilder as _;
use gpui::{
App, Bounds, DispatchPhase, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent,
MouseButton, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, RenderOnce, Role,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas,
div, relative,
};
use crate::components::common::{Sizable, StyledExt as _, focus_ring, h_flex};
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
/// The change reporter, fired with the next value by click, drag, and arrows.
type ChangeHandler = Rc<dyn Fn(f32, &mut Window, &mut App)>;
/// The pointer→value setter shared by the click and drag listeners.
type ValueSetter = Rc<dyn Fn(Pixels, &mut Window, &mut App)>;
/// The arrow-key stride as a share of the range when the slider is continuous.
const FALLBACK_STEP_FRACTION: f32 = 0.05;
impl Slider {
/// Clamps `value` into `[min, max]` and snaps it to `step` when stepped.
fn constrain(min: f32, max: f32, step: f32, value: f32) -> f32 {
let clamped = value.clamp(min, max);
if step > 0.0 {
(min + ((clamped - min) / step).round() * step).clamp(min, max)
} else {
clamped
}
}
}
/// A controlled slider over `[min, max]`.
#[derive(IntoElement)]
#[must_use]
pub struct Slider {
id: ElementId,
min: f32,
max: f32,
step: f32,
value: f32,
size: Size,
disabled: bool,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
style: StyleRefinement,
}
impl Slider {
/// Creates a slider over `0..=1` with no stepping, at `value`.
pub fn new<I>(id: I, value: f32) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
min: 0.0,
max: 1.0,
step: 0.0,
value,
size: Size::default(),
disabled: false,
a11y_label: None,
on_change: None,
style: StyleRefinement::default(),
}
}
/// Sets the range's lower bound.
pub fn min(mut self, min: f32) -> Self {
self.min = min;
self
}
/// Sets the range's upper bound.
pub fn max(mut self, max: f32) -> Self {
self.max = max;
self
}
/// Sets the step; values snap to `min + n * step`. `0` is continuous.
pub fn step(mut self, step: f32) -> Self {
self.step = step;
self
}
/// Renders the slider inert, unfocusable, and dimmed; disabled always wins.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Sets the accessibility label, required for an unlabeled slider.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Sets the change handler, fired with the next value by click, drag, and arrows.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(f32, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
}
impl gpui::Styled for Slider {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Slider {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Slider {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let radius = theme.radius;
let metrics = theme.sizes.resolve(self.size);
let row_height = metrics.icon_size * 2.5;
let track_height = metrics.icon_size / 4.0;
let knob = metrics.indicator_size;
let value = self.value.clamp(self.min, self.max);
let fraction = if self.max > self.min {
(value - self.min) / (self.max - self.min)
} else {
0.0
};
let bounds_cell = Rc::new(Cell::new(None::<Bounds<Pixels>>));
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);
let set_value: ValueSetter = {
let bounds_cell = bounds_cell.clone();
let on_change = self.on_change.clone();
let (min, max, step) = (self.min, self.max, self.step);
Rc::new(move |x: Pixels, window: &mut Window, cx: &mut App| {
if let (Some(bounds), Some(on_change)) = (bounds_cell.get(), on_change.as_ref())
&& bounds.size.width > Pixels::ZERO
{
let fraction = ((x - bounds.origin.x) / bounds.size.width).clamp(0.0, 1.0);
on_change(
Self::constrain(min, max, step, min + fraction * (max - min)),
window,
cx,
);
}
})
};
let down_dragging = dragging.clone();
let down_set_value = set_value.clone();
let disabled = self.disabled;
h_flex()
.id(self.id)
.relative()
.w_full()
.h(row_height)
.refine_style(&self.style)
.role(Role::Slider)
.when_some(self.a11y_label.clone(), |slider, label| {
slider.aria_label(label)
})
.aria_numeric_value(f64::from(value))
.aria_min_numeric_value(f64::from(self.min))
.aria_max_numeric_value(f64::from(self.max))
.when(self.disabled, |slider| slider.opacity(DISABLED_OPACITY))
.when(!self.disabled, |slider| {
slider
.track_focus(&focus_handle)
.tab_stop(true)
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.on_mouse_down(MouseButton::Left, move |event, window, cx| {
down_dragging.update(cx, |dragging, _| *dragging = true);
down_set_value(event.position.x, window, cx);
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if !focus_handle.contains_focused(window, cx) {
return;
}
let single_step = if self.step > 0.0 {
self.step
} else {
(self.max - self.min) * FALLBACK_STEP_FRACTION
};
let next = match event.keystroke.key.as_str() {
"left" | "down" => Some(value - single_step),
"right" | "up" => Some(value + single_step),
"home" => Some(self.min),
"end" => Some(self.max),
_ => None,
};
if let Some(next) = next
&& let Some(on_change) = self.on_change.as_ref()
{
on_change(
Self::constrain(self.min, self.max, self.step, next),
window,
cx,
);
cx.stop_propagation();
}
})
})
.child(
canvas(
{
let bounds_cell = bounds_cell.clone();
move |bounds, _, _| bounds_cell.set(Some(bounds))
},
{
let dragging = dragging.clone();
let set_value = set_value.clone();
move |_, _, window, _cx| {
if disabled {
return;
}
window.on_mouse_event({
let dragging = dragging.clone();
let set_value = set_value.clone();
move |event: &MouseMoveEvent, phase, window, cx| {
if phase == DispatchPhase::Bubble
&& *dragging.read(cx)
&& event.pressed_button == Some(MouseButton::Left)
{
set_value(event.position.x, window, cx);
}
}
});
window.on_mouse_event({
let dragging = dragging.clone();
move |event: &MouseUpEvent, phase, _window, cx| {
if phase == DispatchPhase::Bubble
&& event.button == MouseButton::Left
{
dragging.update(cx, |dragging, _| *dragging = false);
}
}
});
}
},
)
.absolute()
.inset_0(),
)
.child(
div()
.absolute()
.left_0()
.top((row_height - track_height) / 2.0)
.h(track_height)
.w_full()
.rounded(radius.full)
.bg(colors.border),
)
.child(
div()
.absolute()
.left_0()
.top((row_height - track_height) / 2.0)
.h(track_height)
.w(relative(fraction))
.rounded(radius.full)
.bg(ramps.primary.base),
)
.child(
h_flex()
.absolute()
.left_0()
.top_0()
.h_full()
.w(relative(fraction))
.justify_end()
.items_center()
.child(
div()
.size(knob)
.flex_none()
.rounded(radius.full)
.bg(colors.primary_foreground)
.border_1()
.border_color(colors.border)
.mr(-knob / 2.0),
),
)
}
}
File diff suppressed because it is too large Load Diff
+274
View File
@@ -0,0 +1,274 @@
//! 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 gpui::prelude::FluentBuilder as _;
use gpui::{
Animation, AnimationElement, AnimationExt as _, App, Canvas, ElementId, Hsla,
InteractiveElement as _, IntoElement, ParentElement as _, Path, PathBuilder, Pixels, Point,
RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
Window, canvas, div, point, px,
};
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;
/// The ring stroke as a share of the side.
const RING_STROKE: f32 = 0.125;
/// The visual language of a [`Spinner`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SpinnerVariant {
/// The painted arc ring.
#[default]
Ring,
/// The platform loader glyph, rotated.
Icon,
}
/// A loading ring that spins for unknown work or paints a determinate arc.
#[derive(IntoElement)]
#[must_use]
pub struct Spinner {
id: ElementId,
value: Option<f32>,
variant: SpinnerVariant,
size: Size,
color: Option<Hsla>,
a11y_label: Option<SharedString>,
style: StyleRefinement,
}
impl Spinner {
/// Creates a spinning ring.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
value: None,
variant: SpinnerVariant::default(),
size: Size::default(),
color: None,
a11y_label: None,
style: StyleRefinement::default(),
}
}
/// Overrides the arc color, for accent-filled surfaces.
pub fn color(mut self, color: Hsla) -> Self {
self.color = Some(color);
self
}
/// Sets the spinner's visual language.
pub fn variant(mut self, variant: SpinnerVariant) -> Self {
self.variant = variant;
self
}
/// Paints a determinate arc at `value` (`0..=1`) instead of spinning.
pub fn value(mut self, value: f32) -> Self {
self.value = Some(value);
self
}
/// Sets the accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl gpui::Styled for Spinner {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Spinner {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Spinner {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let side = theme.sizes.resolve(self.size).icon_size;
let stroke = side * RING_STROKE;
let track = theme.colors.border;
let accent = self.color.unwrap_or(theme.ramps.primary.base);
let value = self.value.map(|value| value.clamp(0.0, 1.0));
div()
.id(self.id)
.flex_none()
.size(side)
.refine_style(&self.style)
.role(Role::ProgressIndicator)
.when_some(self.a11y_label, |spinner, label| spinner.aria_label(label))
.when_some(value, |spinner, value| {
spinner
.aria_numeric_value(f64::from(value))
.aria_min_numeric_value(0.0)
.aria_max_numeric_value(1.0)
})
.child(match (self.variant, value) {
(SpinnerVariant::Ring, Some(value)) => {
determinate_ring(side, stroke, track, accent, value).into_any_element()
}
(SpinnerVariant::Ring, None) => {
spinning_ring(side, stroke, accent).into_any_element()
}
(SpinnerVariant::Icon, Some(_)) => icon(IconRole::Loader)
.size(side)
.color(accent)
.into_any_element(),
(SpinnerVariant::Icon, None) => spinning_icon(side, accent).into_any_element(),
})
}
}
fn determinate_ring(
side: Pixels,
stroke: Pixels,
track: Hsla,
accent: Hsla,
value: f32,
) -> Canvas<()> {
canvas(
|_, _, _| (),
move |bounds, (), window, _| {
let center = bounds.center();
let radius = bounds.size.width / 2.0 - stroke / 2.0;
paint_circle(center, radius, stroke, track, window);
if value >= 1.0 {
paint_circle(center, radius, stroke, accent, window);
} else if value > 0.0
&& let Some(path) = arc_path(center, radius, stroke, 0.0, value * TAU)
{
window.paint_path(path, accent);
}
},
)
.size(side)
}
fn spinning_ring(side: Pixels, stroke: Pixels, accent: Hsla) -> AnimationElement<Canvas<()>> {
let angle = Rc::new(Cell::new(0.0));
let spun = angle.clone();
canvas(
|_, _, _| (),
move |bounds, (), window, _| {
let radius = bounds.size.width / 2.0 - stroke / 2.0;
if let Some(path) = arc_path(
bounds.center(),
radius,
stroke,
spun.get(),
SPIN_SWEEP * TAU,
) {
window.paint_path(path, accent);
}
},
)
.size(side)
.with_animation(
"spin",
Animation::new(SPINNER_PERIOD).repeat().with_max_fps(60.),
move |ring, delta| {
angle.set(delta * TAU);
ring
},
)
}
fn spinning_icon(side: Pixels, accent: Hsla) -> Icon {
icon(IconRole::Loader)
.size(side)
.color(accent)
.with_rotation_animation(SPINNER_PERIOD)
}
/// Paints a stroked circle into the window.
fn paint_circle(
center: Point<Pixels>,
radius: Pixels,
stroke: Pixels,
color: Hsla,
window: &mut Window,
) {
if let Some(path) = circle_path(center, radius, stroke) {
window.paint_path(path, color);
}
}
/// A point on the ring at `angle`, clockwise from 12 o'clock.
fn ring_point(center: Point<Pixels>, radius: Pixels, angle: f32) -> Point<Pixels> {
point(
center.x + radius * angle.sin(),
center.y - radius * angle.cos(),
)
}
/// A stroked arc from `start`, sweeping clockwise by `sweep` radians.
fn arc_path(
center: Point<Pixels>,
radius: Pixels,
stroke: Pixels,
start: f32,
sweep: f32,
) -> Option<Path> {
let mut builder = PathBuilder::stroke(stroke);
builder.move_to(ring_point(center, radius, start));
builder.arc_to(
point(radius, radius),
px(0.),
sweep > PI,
true,
ring_point(center, radius, start + sweep),
);
builder.build().ok()
}
/// A stroked full circle; `None` on degenerate geometry.
fn circle_path(center: Point<Pixels>, radius: Pixels, stroke: Pixels) -> Option<Path> {
let mut builder = PathBuilder::stroke(stroke);
builder.move_to(ring_point(center, radius, 0.0));
builder.arc_to(
point(radius, radius),
px(0.),
false,
true,
ring_point(center, radius, PI),
);
builder.arc_to(
point(radius, radius),
px(0.),
false,
true,
ring_point(center, radius, TAU),
);
builder.build().ok()
}
+123
View File
@@ -0,0 +1,123 @@
//! 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 gpui::prelude::FluentBuilder as _;
use gpui::{
App, ElementId, Hsla, InteractiveElement as _, IntoElement, RenderOnce, Role, SharedString,
StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div,
};
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,
}
impl StatusDotVariant {
fn color(self, theme: &Theme) -> Hsla {
match self {
Self::Neutral => theme.colors.muted_foreground,
Self::Accent => theme.ramps.primary.base,
Self::Success => theme.ramps.success.base,
Self::Warning => theme.ramps.warning.base,
Self::Danger => theme.ramps.destructive.base,
}
}
}
/// A small circular bead marking a row's state.
#[derive(IntoElement)]
#[must_use]
pub struct StatusDot {
id: ElementId,
variant: StatusDotVariant,
size: Size,
label: Option<SharedString>,
style: StyleRefinement,
}
impl StatusDot {
/// Creates an idle dot.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
variant: StatusDotVariant::default(),
size: Size::default(),
label: None,
style: StyleRefinement::default(),
}
}
/// Sets how loud the dot is.
pub fn variant(mut self, variant: StatusDotVariant) -> Self {
self.variant = variant;
self
}
/// Sets the state the dot announces to screen readers.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
}
impl Sizable for StatusDot {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl Styled for StatusDot {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for StatusDot {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let metrics = theme.sizes.resolve(self.size);
let side = metrics.icon_size / 2.;
let color = self.variant.color(theme);
div()
.id(self.id.clone())
.debug_selector(move || self.id.to_string())
.flex_none()
.size(side)
.rounded(theme.radius.full)
.bg(color)
.when_some(self.label, |dot, label| {
dot.role(Role::Status).aria_label(label)
})
.refine_style(&self.style)
}
}
+190
View File
@@ -0,0 +1,190 @@
//! 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 gpui::prelude::FluentBuilder as _;
use gpui::{
AnimationExt as _, App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _,
RenderOnce, Role, SharedString, SpringAnimation, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Toggled, Window, div, px,
};
use crate::components::common::{Sizable, StyledExt as _, focus_ring, h_flex};
use crate::theme::{ActiveTheme as _, BORDER_WIDTH, CONTROL_SPRING, DISABLED_OPACITY, Size};
/// The change reporter, fired with the next value by pointer, Enter, and Space.
type ChangeHandler = Box<dyn Fn(bool, &mut Window, &mut App)>;
/// A controlled on/off switch that fires [`Switch::on_change`] on toggle.
#[derive(IntoElement)]
#[must_use]
pub struct Switch {
id: ElementId,
label: Option<SharedString>,
checked: bool,
size: Size,
disabled: bool,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
style: StyleRefinement,
}
impl Switch {
/// Creates an unchecked switch.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
label: None,
checked: false,
size: Size::default(),
disabled: false,
a11y_label: None,
on_change: None,
style: StyleRefinement::default(),
}
}
/// Sets the visible label; clicking it toggles too.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Sets the current value; the switch never owns it.
pub fn checked(mut self, checked: bool) -> Self {
self.checked = checked;
self
}
/// Renders the switch inert, unfocusable, and dimmed.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Sets the change handler, fired with the next value by pointer, Enter, and Space.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(bool, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Box::new(handler));
self
}
}
impl gpui::Styled for Switch {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Switch {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Switch {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let metrics = theme.sizes.resolve(self.size);
let track_height = metrics.switch_height;
let track_width = metrics.switch_width;
let knob = metrics.switch_knob;
// Absolute children sit inside the track's border, so remove it from the inset.
let inset = (track_height - knob) / 2. - BORDER_WIDTH;
let travel = track_width - BORDER_WIDTH * 2. - knob - inset * 2.;
let next = !self.checked;
let on_change = self.on_change;
let a11y_label = self.a11y_label.or_else(|| self.label.clone());
let id = self.id.clone();
let anim =
SpringAnimation::new(CONTROL_SPRING).to(if self.checked { travel } else { px(0.) });
h_flex()
.id(self.id)
.gap_2()
.text_size(metrics.text_size)
.refine_style(&self.style)
.role(Role::Switch)
.when_some(a11y_label, |switch, label| switch.aria_label(label))
.aria_toggled(Toggled::from(self.checked))
.when(self.disabled, |switch| switch.opacity(DISABLED_OPACITY))
.when(!self.disabled, |switch| {
switch
.cursor_pointer()
.focusable()
.tab_stop(true)
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.when_some(on_change, |switch, on_change| {
switch.on_click(move |_, window, cx| on_change(next, window, cx))
})
})
.child(
div()
.flex_none()
.relative()
.debug_selector(move || format!("{id}-track"))
.w(track_width)
.h(track_height)
.rounded(theme.radius.full)
.border_1()
.when(self.checked, |track| {
track
.bg(ramps.primary.base)
.border_color(ramps.primary.base)
.hover(|style| {
style
.bg(ramps.primary.hover)
.border_color(ramps.primary.hover)
})
})
.when(!self.checked, |track| {
track.bg(colors.input).border_color(colors.border)
})
.child(
div()
.absolute()
.top(inset)
.left(inset)
.size(knob)
.rounded(theme.radius.full)
.bg(colors.primary_foreground)
.with_spring("switch-thumb", anim, move |thumb, offset| {
thumb.left(inset + offset)
}),
),
)
.when_some(self.label, |switch, label| switch.child(label))
}
}
File diff suppressed because it is too large Load Diff
+367
View File
@@ -0,0 +1,367 @@
//! 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 gpui::prelude::FluentBuilder;
use gpui::{
Animation, AnimationExt as _, App, Context, ElementId, Entity, InteractiveElement as _,
IntoElement, ParentElement as _, RenderOnce, Role, SharedString,
StatefulInteractiveElement as _, StyleRefinement, Styled as _, Task, Window, deferred, div,
ease_out_quint, px,
};
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};
/// The action handler of a [`Toast`].
pub type ActionHandler = Rc<dyn Fn(&mut App)>;
/// One user action offered by a toast.
#[derive(Clone)]
pub struct ToastAction {
label: SharedString,
handler: ActionHandler,
}
impl ToastAction {
/// Creates an action with this label.
pub fn new<L, F>(label: L, handler: F) -> Self
where
L: Into<SharedString>,
F: Fn(&mut App) + 'static,
{
Self {
label: label.into(),
handler: Rc::new(handler),
}
}
}
/// A toast notification.
#[derive(Clone)]
#[must_use]
pub struct Toast {
message: SharedString,
icon: Option<Icon>,
action: Option<ToastAction>,
duration: Option<Duration>,
on_dismiss: Option<DismissHandler>,
style: StyleRefinement,
}
impl Toast {
/// How long a toast stays up by default.
pub const DURATION: Duration = Duration::from_secs(5);
/// Creates a toast with this one-line content.
pub fn new<L>(message: L) -> Self
where
L: Into<SharedString>,
{
Self {
message: message.into(),
icon: None,
action: None,
duration: Some(Self::DURATION),
on_dismiss: None,
style: StyleRefinement::default(),
}
}
/// Shows this glyph before the content.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Offers the user this action.
pub fn action(mut self, action: ToastAction) -> Self {
self.action = Some(action);
self
}
/// Sets the time before the toast dismisses itself.
pub fn duration(mut self, duration: Duration) -> Self {
self.duration = Some(duration);
self
}
/// Runs when the toast is dismissed by any means, once it is fully gone.
pub fn on_dismiss<F>(mut self, handler: F) -> Self
where
F: Fn(&mut App) + 'static,
{
self.on_dismiss = Some(Rc::new(handler));
self
}
}
// Toast is a data builder, not an element, adopt the combinators explicitly.
impl FluentBuilder for Toast {}
/// One raised toast, with its identity in the store.
#[derive(Clone)]
pub struct ToastEntry {
pub id: usize,
pub toast: Toast,
}
/// The store of raised toasts.
#[derive(Default)]
pub struct Toasts {
current: Option<ToastEntry>,
exiting: Option<ToastEntry>,
next_id: usize,
/// Pending dismiss and fade timers; held so they die with the store.
tasks: Vec<Task<()>>,
}
impl Toasts {
/// Raises a toast, replacing the one on screen. Returns its id.
pub fn push(&mut self, toast: Toast, cx: &mut Context<Self>) -> usize {
let id = self.next_id;
self.next_id += 1;
let duration = toast.duration;
if let Some(previous) = self.current.take() {
self.start_exit(previous, cx);
}
self.current = Some(ToastEntry { id, toast });
cx.notify();
if let Some(duration) = duration.filter(|duration| !duration.is_zero()) {
let task = cx.spawn(async move |this, cx| {
cx.background_executor().timer(duration).await;
this.update(cx, |toasts, cx| toasts.dismiss(id, cx))
.log_err();
});
self.tasks.push(task);
}
id
}
/// Dismisses one toast by id.
pub fn dismiss(&mut self, id: usize, cx: &mut Context<Self>) {
if self.exiting.as_ref().is_some_and(|entry| entry.id == id) {
self.finish_exit(cx);
return;
}
if let Some(entry) = self.current.take_if(|entry| entry.id == id) {
self.start_exit(entry, cx);
}
}
/// Dismisses the toast on screen.
pub fn clear(&mut self, cx: &mut Context<Self>) {
if let Some(entry) = self.current.take() {
self.start_exit(entry, cx);
} else {
self.finish_exit(cx);
}
}
/// The toast now showing, if any.
pub fn current(&self) -> Option<&ToastEntry> {
self.current.as_ref()
}
/// How many toasts are on screen, including one fading out.
pub fn count(&self) -> usize {
usize::from(self.current.is_some()) + usize::from(self.exiting.is_some())
}
/// Moves a toast into the fade-out phase.
fn start_exit(&mut self, entry: ToastEntry, cx: &mut Context<Self>) {
if let Some(previous) = self.exiting.take()
&& let Some(on_dismiss) = &previous.toast.on_dismiss
{
on_dismiss(cx);
}
self.exiting = Some(entry);
cx.notify();
let fade = cx.theme().motion.overlay;
let task = cx.spawn(async move |this, cx| {
cx.background_executor().timer(fade).await;
this.update(cx, |toasts, cx| toasts.finish_exit(cx))
.log_err();
});
self.tasks.push(task);
}
fn finish_exit(&mut self, cx: &mut Context<Self>) {
if let Some(entry) = self.exiting.take() {
cx.notify();
if let Some(on_dismiss) = &entry.toast.on_dismiss {
on_dismiss(cx);
}
}
}
}
/// The floating stack of toasts, bottom center.
#[derive(IntoElement)]
#[must_use]
pub struct ToastsView {
toasts: Entity<Toasts>,
id: ElementId,
}
impl ToastsView {
/// Binds the view to a toast store.
pub fn new<I>(id: I, toasts: Entity<Toasts>) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
toasts,
}
}
}
impl RenderOnce for ToastsView {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let fade = cx.theme().motion.overlay;
let exiting = self.toasts.read(cx).exiting.clone();
let current = self.toasts.read(cx).current.clone();
deferred(
div()
.id(self.id)
.absolute()
.left_0()
.bottom_4()
.w_full()
.flex()
.flex_col()
.items_center()
.when_some(exiting, |column, entry| {
let id = entry.id;
column.child(entry.pill(&self.toasts, cx).with_animation(
("toast-exit", id),
Animation::new(fade),
|pill, delta| pill.opacity(1. - delta),
))
})
.when_some(current, |column, entry| {
let id = entry.id;
column.child(entry.pill(&self.toasts, cx).with_animation(
("toast-enter", id),
Animation::new(fade).with_easing(ease_out_quint()),
|pill, delta| pill.opacity(delta),
))
}),
)
.with_priority(TOAST_LAYER)
}
}
impl ToastEntry {
/// The rendered pill for this toast.
fn pill(&self, toasts: &Entity<Toasts>, cx: &App) -> gpui::Stateful<gpui::Div> {
let theme = cx.theme();
let surface = theme.colors.surface;
let border = theme.colors.border;
let foreground = theme.colors.foreground;
let radius = theme.radius.full;
let shadows = theme.elevations.popover.shadows();
let icon_size = theme.sizes.medium.icon_size;
let text_size = theme.sizes.medium.text_size;
let toast = &self.toast;
let toasts = toasts.clone();
let id = self.id;
div()
.id(("toast", id))
.debug_selector(|| "toast-pill".to_string())
.role(Role::Alert)
.aria_label(toast.message.clone())
.max_w(TOAST_MAX_WIDTH)
.flex()
.items_center()
.gap_2()
.py_1p5()
.px_3()
.bg(surface)
.border_1()
.border_color(border)
.rounded(radius)
.shadow(shadows.clone())
.refine_style(&toast.style)
.when_some(toast.icon.clone(), |pill, icon| {
pill.child(
div()
.flex_none()
.flex()
.items_center()
.child(icon.size(icon_size).color(foreground)),
)
})
.child(
div()
.flex_1()
.min_w(px(0.))
.truncate()
.text_size(text_size)
.text_color(foreground)
.child(toast.message.clone()),
)
.when_some(toast.action.clone(), |pill, action| {
let toasts = toasts.clone();
pill.child(
div().flex_none().child(
Button::new(("toast-action", id))
.label(action.label.clone())
.variant(ButtonVariant::Primary)
.small()
.on_click(move |_, _window, cx| {
(action.handler)(cx);
toasts.update(cx, |toasts, cx| {
toasts.dismiss(id, cx);
});
}),
),
)
})
.child(
div().flex_none().child(
Button::new(("toast-close", id))
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.small()
.accessibility_label("Dismiss")
.on_click(move |_, _window, cx| {
toasts.update(cx, |toasts, cx| {
toasts.dismiss(id, cx);
});
}),
),
)
}
}
+178
View File
@@ -0,0 +1,178 @@
//! 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 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 _, focus_ring, h_flex};
use crate::icons::Icon;
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
/// The change handler, fired with the next pressed state.
type ChangeHandler = Box<dyn Fn(bool, &mut Window, &mut App)>;
/// A two-state control that reports the next pressed state on click.
#[derive(IntoElement)]
#[must_use]
pub struct Toggle {
id: ElementId,
label: Option<SharedString>,
icon: Option<Icon>,
pressed: bool,
size: Size,
disabled: bool,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
style: StyleRefinement,
}
impl Toggle {
/// Creates an unpressed toggle.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
label: None,
icon: None,
pressed: false,
size: Size::default(),
disabled: false,
a11y_label: None,
on_change: None,
style: StyleRefinement::default(),
}
}
/// Sets the visible label.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Shows an icon. Omitting the label renders an icon-only toggle.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Sets the current pressed state; the toggle never owns it.
pub fn pressed(mut self, pressed: bool) -> Self {
self.pressed = pressed;
self
}
/// Renders the toggle inert, unfocusable, and dimmed; disabled always wins.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Sets the change handler, fired with the next pressed state.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(bool, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Box::new(handler));
self
}
}
impl gpui::Styled for Toggle {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Toggle {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Toggle {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let metrics = theme.sizes.resolve(self.size);
let on_change = self.on_change;
let next = !self.pressed;
let a11y_label = self.a11y_label.or_else(|| self.label.clone());
let icon_only = self.icon.is_some() && self.label.is_none();
h_flex()
.id(self.id)
.justify_center()
.h(metrics.control_height)
.when(icon_only, |toggle| {
toggle.w(metrics.control_height).px(gpui::Pixels::ZERO)
})
.when(!icon_only, |toggle| toggle.px(metrics.dense_padding_x))
.rounded(theme.radius.control)
.text_size(metrics.text_size)
.text_color(colors.foreground)
.role(Role::Button)
.when_some(a11y_label, |toggle, label| toggle.aria_label(label))
.aria_toggled(Toggled::from(self.pressed))
.when(self.pressed, |toggle| {
toggle
.bg(ramps.secondary.hover)
.hover(|style| style.bg(ramps.secondary.pressed))
})
.when(!self.pressed, |toggle| {
toggle
.hover(|style| style.bg(colors.muted))
.active(|style| style.bg(ramps.secondary.hover))
})
.refine_style(&self.style)
.when(self.disabled, |toggle| toggle.opacity(DISABLED_OPACITY))
.when(!self.disabled, |toggle| {
toggle
.cursor_pointer()
.focusable()
.tab_stop(true)
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.when_some(on_change, |toggle, on_change| {
toggle.on_click(move |_, window, cx| on_change(next, window, cx))
})
})
.child(
h_flex()
.gap_2()
.when_some(self.icon, |content, icon| {
content.child(icon.size(metrics.icon_size))
})
.when_some(self.label, |content, label| content.child(label)),
)
}
}
+156
View File
@@ -0,0 +1,156 @@
//! 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 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, px,
};
use crate::components::common::{anchor_bounds, record_anchor_bounds};
use crate::theme::{ActiveTheme as _, BORDER_WIDTH, TOOLTIP_MAX_WIDTH, TOOLTIP_OFFSET};
const PANEL_BOUNDS_ID: &str = "tooltip-panel-bounds";
/// A small text panel gpui shows next to a hovered element.
pub struct Tooltip {
text: SharedString,
anchor: Option<Bounds<Pixels>>,
}
impl Tooltip {
/// Creates the tooltip view.
pub fn new<L>(text: L, cx: &mut App) -> Entity<Self>
where
L: Into<SharedString>,
{
cx.new(|_| Self {
text: text.into(),
anchor: None,
})
}
/// Returns the `.tooltip(...)` closure that pins the panel next to the
/// element identified by `anchor_id`.
///
/// [`Tooltip::text`] places the panel at the pointer instead.
pub fn anchored<L, I>(
text: L,
anchor_id: I,
) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static
where
L: Into<SharedString>,
I: Into<ElementId>,
{
let text = text.into();
let anchor_id = anchor_id.into();
move |window, cx| {
let anchor = anchor_bounds(window.window_handle().window_id(), &anchor_id, cx);
cx.new(|_| Self {
text: text.clone(),
anchor,
})
.into()
}
}
/// Returns the `.tooltip(...)` closure for a plain text tooltip.
pub fn text<L>(text: L) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static
where
L: Into<SharedString>,
{
let text = text.into();
move |_, cx| Tooltip::new(text.clone(), cx).into()
}
}
impl Render for Tooltip {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// Copied out: the mutable reads below need `cx` free of this borrow.
let theme = cx.theme();
let text_size = theme.sizes.medium.text_size;
let line_height = theme.typography.callout.line_height;
let surface = theme.colors.surface;
let surface_foreground = theme.colors.surface_foreground;
let radius_sm = theme.radius.sm;
let shadows = theme.elevations.popover.shadows();
let border = theme.colors.border;
let build_panel = || {
div()
.id("tooltip-panel")
.role(Role::Tooltip)
.debug_selector(|| "tooltip-panel".to_string())
.px_2()
.py_1()
.max_w(TOOLTIP_MAX_WIDTH)
.bg(surface)
.border_1()
.border_color(border)
.rounded(radius_sm)
.shadow(shadows.clone())
.text_size(text_size)
.line_height(line_height)
.text_color(surface_foreground)
.child(self.text.clone())
};
let (wrapper, panel) = match self.anchor {
Some(parent) => {
let origin = window.mouse_position() + point(TOOLTIP_OFFSET, TOOLTIP_OFFSET);
let viewport_height = window.viewport_size().height;
let height = anchor_bounds(
window.window_handle().window_id(),
&ElementId::from(PANEL_BOUNDS_ID),
cx,
)
.map(|bounds| bounds.size.height)
.unwrap_or_else(|| line_height + px(8.) + BORDER_WIDTH * 2.0);
let below = viewport_height - px(4.) - parent.bottom();
let above = parent.top() - px(4.);
let hang_below = below >= height || below >= above;
let panel = build_panel()
.ml(parent.left() - origin.x)
.mt(if hang_below {
parent.bottom() + px(4.) - origin.y
} else {
parent.top() - px(4.) - height - origin.y
})
.child(
canvas(
record_anchor_bounds(ElementId::from(PANEL_BOUNDS_ID)),
|_, _, _, _| {},
)
.absolute()
.inset_0(),
);
(div().debug_selector(|| "tooltip-anchor".to_string()), panel)
}
None => {
let wrapper = div()
.debug_selector(|| "tooltip-anchor".to_string())
.pl_2()
.pt_2();
(wrapper, build_panel())
}
};
wrapper.child(panel)
}
}
+460
View File
@@ -0,0 +1,460 @@
//! 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 gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent,
ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Window, div,
};
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 _;
/// The change reporter, fired with the next selection by pointer and keys.
type ChangeHandler = Rc<dyn Fn(Option<usize>, &mut Window, &mut App)>;
/// The disclosure reporter, fired with the toggled row's index.
type DisclosureHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
/// The visible row builder, run during render.
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<TreeItem>>;
/// One row of a [`Tree`].
#[derive(Clone)]
#[must_use]
pub struct TreeItem {
key: ElementId,
label: SharedString,
icon: Option<Icon>,
depth: usize,
expandable: bool,
expanded: bool,
disabled: bool,
}
impl TreeItem {
/// Creates a leaf row shown as `label` at the root depth, identified by `key`.
pub fn new<K, L>(key: K, label: L) -> Self
where
K: Into<ElementId>,
L: Into<SharedString>,
{
Self {
key: key.into(),
label: label.into(),
icon: None,
depth: 0,
expandable: false,
expanded: false,
disabled: false,
}
}
/// Shows a custom icon leading the label.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Nests the row one level per count.
pub fn depth(mut self, depth: usize) -> Self {
self.depth = depth;
self
}
/// Marks the row as having children.
pub fn expandable(mut self, expandable: bool) -> Self {
self.expandable = expandable;
self
}
/// Sets the row's disclosure state.
pub fn expanded(mut self, expanded: bool) -> Self {
self.expanded = expanded;
self
}
/// Renders the row dimmed; clicks and keyboard skip it.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
// TreeItem is a data builder, not an element, adopt the combinators explicitly.
impl FluentBuilder for TreeItem {}
/// A tree of [`TreeItem`] rows with single selection and disclosure handling.
#[derive(IntoElement)]
#[must_use]
pub struct Tree {
id: ElementId,
selected: Option<usize>,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
on_disclosure: Option<DisclosureHandler>,
items: Option<ItemsFn>,
style: StyleRefinement,
}
impl Tree {
/// Creates a tree with nothing selected.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
selected: None,
a11y_label: None,
on_change: None,
on_disclosure: None,
items: None,
style: StyleRefinement::default(),
}
}
/// Sets the current selection.
pub fn selected(mut self, selected: Option<usize>) -> Self {
self.selected = selected;
self
}
/// Reports the next selection, from clicks and keys alike.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(Option<usize>, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Reports the row whose disclosure the user toggled.
pub fn on_disclosure<F>(mut self, handler: F) -> Self
where
F: Fn(usize, &mut Window, &mut App) + 'static,
{
self.on_disclosure = Some(Rc::new(handler));
self
}
/// Sets the visible rows; the closure runs during render and must not mutate entities or notify.
pub fn items<F>(mut self, items: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<TreeItem> + 'static,
{
self.items = Some(Box::new(items));
self
}
/// Overrides the accessibility label, which defaults to the id.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Maps each visible row to its 1-based position-in-set and set size among its siblings.
fn sibling_sets(items: &[TreeItem]) -> Vec<(usize, usize)> {
let mut sets = vec![(0usize, 0usize); items.len()];
// Open sibling runs along the ancestry path, deeper runs above shallower ones.
let mut runs: Vec<(usize, Vec<usize>)> = Vec::new();
for (index, item) in items.iter().enumerate() {
while runs
.last()
.is_some_and(|(run_depth, _)| *run_depth > item.depth)
{
if let Some((_, pending)) = runs.pop() {
Self::stamp_sibling_run(&mut sets, pending);
}
}
match runs.last_mut() {
// A row at the running depth extends the open sibling run.
Some((run_depth, pending)) if *run_depth == item.depth => pending.push(index),
_ => runs.push((item.depth, vec![index])),
}
}
for (_, pending) in runs {
Self::stamp_sibling_run(&mut sets, pending);
}
sets
}
fn stamp_sibling_run(sets: &mut [(usize, usize)], pending: Vec<usize>) {
let size_of_set = pending.len();
for (position, index) in pending.into_iter().enumerate() {
if let Some(set) = sets.get_mut(index) {
*set = (position + 1, size_of_set);
}
}
}
/// The nearest row above `index` with a smaller depth.
fn parent_of(items: &[TreeItem], index: usize) -> Option<usize> {
let depth = items.get(index)?.depth;
items[..index]
.iter()
.rposition(|candidate| candidate.depth < depth)
}
/// The first selectable row deeper than `index`, when its branch is open.
fn first_descendant(items: &[TreeItem], selectable: &[usize], index: usize) -> Option<usize> {
let depth = items.get(index)?.depth;
selectable.iter().copied().find(|candidate| {
*candidate > index && items.get(*candidate).is_some_and(|row| row.depth > depth)
})
}
}
impl gpui::Styled for Tree {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Tree {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let items = match self.items {
Some(build) => build(window, cx),
None => Vec::new(),
};
let selectable: Vec<usize> = items
.iter()
.enumerate()
.filter(|(_, item)| !item.disabled)
.map(|(index, _)| index)
.collect();
let focus = crate::components::common::focus_handle(&self.id, window, cx);
let theme = cx.theme();
let label = self
.a11y_label
.clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
let sibling_sets = Self::sibling_sets(&items);
let rows: Vec<AnyElement> = items
.iter()
.enumerate()
.map(|(index, item)| {
let (position_in_set, size_of_set) = sibling_sets[index];
item.render_row(
cx,
index,
position_in_set,
size_of_set,
self.selected == Some(index),
&self.on_change,
&self.on_disclosure,
&focus,
)
})
.collect();
div()
.id(self.id)
.flex()
.flex_col()
.gap_0p5()
.text_size(theme.sizes.medium.text_size)
.refine_style(&self.style)
.track_focus(&focus)
.focusable()
.tab_stop(true)
.role(Role::Tree)
.aria_label(label)
.on_key_down({
let selected = self.selected;
let on_change = self.on_change.clone();
let on_disclosure = self.on_disclosure.clone();
move |event: &KeyDownEvent, window, cx| {
if nav_key(&selectable, selected, &event.keystroke.key, |next| {
if let Some(on_change) = &on_change {
on_change(next, window, cx);
}
}) {
cx.stop_propagation();
return;
}
match event.keystroke.key.as_str() {
"left" | "right" => {
let expanding = event.keystroke.key == "right";
let mut disclose = None;
let mut target = None;
if let Some(index) = selected
&& let Some(item) = items.get(index)
&& !item.disabled
{
if item.expandable && item.expanded != expanding {
disclose = Some(index);
} else if expanding {
target = Self::first_descendant(&items, &selectable, index);
} else {
target = Self::parent_of(&items, index)
.filter(|parent| selectable.contains(parent));
}
}
if let Some(index) = disclose
&& let Some(on_disclosure) = &on_disclosure
{
on_disclosure(index, window, cx);
} else if let Some(next) = target
&& let Some(on_change) = &on_change
{
on_change(Some(next), window, cx);
}
}
_ => return,
}
cx.stop_propagation();
}
})
.children(rows)
}
}
impl TreeItem {
#[allow(clippy::too_many_arguments)]
fn render_row(
&self,
cx: &App,
index: usize,
position_in_set: usize,
size_of_set: usize,
selected: bool,
on_change: &Option<ChangeHandler>,
on_disclosure: &Option<DisclosureHandler>,
focus: &FocusHandle,
) -> AnyElement {
let theme = cx.theme();
let label_color = selectable_label_color(cx, selected, self.disabled);
let disabled = self.disabled;
let depth = u32::try_from(self.depth).unwrap_or(u32::MAX) as f32;
let indent = theme.sizes.medium.padding_x * if self.depth == 0 { 0.5 } else { depth + 1.0 };
div()
.id((self.key.clone(), "tree-item"))
.relative()
.flex()
.items_center()
.gap_2()
.pl(indent)
.pr_2()
.py_1()
.min_h(theme.sizes.medium.control_height)
.rounded(theme.radius.sm)
.role(Role::TreeItem)
.aria_selected(selected)
.aria_level(self.depth + 1)
.aria_position_in_set(position_in_set)
.aria_size_of_set(size_of_set)
.when(self.expandable, |row| row.aria_expanded(self.expanded))
.map(|row| paint_selectable_row(cx, row, selected, disabled))
.when(!disabled, |row| {
row.cursor_pointer().on_click({
let on_change = on_change.clone();
let on_disclosure = on_disclosure.clone();
let expandable = self.expandable;
let focus = focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if let Some(on_change) = &on_change {
on_change(Some(index), window, cx);
}
// A folder row toggles with its own click, not just its chevron.
if expandable && let Some(on_disclosure) = &on_disclosure {
on_disclosure(index, window, cx);
}
}
})
})
.children((0..self.depth).map(|level| {
let step = u32::try_from(level).unwrap_or(u32::MAX) as f32;
div()
.absolute()
.left(theme.sizes.medium.padding_x * (step + 0.5))
.top_0()
.bottom_0()
.border_l_1()
.border_color(theme.colors.border)
}))
.child(self.render_disclosure(cx, selected))
.when_some(
self.icon
.clone()
.or_else(|| (!self.expandable).then(|| icon(IconRole::File))),
|row, icon| row.child(icon.size(theme.sizes.medium.icon_size).color(label_color)),
)
.child(
div()
.flex_1()
.text_color(label_color)
.child(self.label.clone()),
)
.into_any_element()
}
fn render_disclosure(&self, cx: &App, selected: bool) -> AnyElement {
let theme = cx.theme();
let glyph_color = if self.disabled || !selected {
theme.colors.muted_foreground
} else {
theme.colors.primary_foreground
};
// Only expandable rows draw a chevron; the empty cell keeps labels aligned with folders.
div()
.flex_none()
.size(theme.sizes.medium.icon_size)
.flex()
.items_center()
.justify_center()
.when(self.expandable, |cell| {
cell.child(
icon(if self.expanded {
IconRole::ChevronDown
} else {
IconRole::ChevronRight
})
.size(theme.sizes.medium.dense_icon_size)
.color(glyph_color),
)
})
.into_any_element()
}
}
+125
View File
@@ -0,0 +1,125 @@
//! Shared helpers for the editor's views: gutter cells, role colors and run
//! styles, code line text, language mapping and change washes.
use std::ops::Range;
use gpui::{
App, HighlightStyle, Hsla, IntoElement, ParentElement as _, Styled as _, StyledText, div,
};
use crate::components::highlight::{Language, Line, Role};
use crate::theme::{
ActiveTheme as _, CODE_GUTTER_WIDTH, ColorTokens, Ramps, WASH_ALPHA, WASH_ALPHA_GUTTER,
WASH_ALPHA_STRONG,
};
impl Role {
/// Maps the role to the theme's semantic palette.
pub(crate) fn color(self, colors: ColorTokens, ramps: Ramps) -> Hsla {
match self {
Role::Text => colors.foreground,
Role::Keyword => ramps.primary.base,
Role::String | Role::Escape => ramps.success.base,
Role::Comment | Role::Punctuation => colors.muted_foreground,
Role::Function | Role::Property => ramps.info.base,
Role::Type => ramps.warning.base,
Role::Number | Role::Constant => ramps.secondary.base,
Role::Operator => colors.foreground,
Role::Tag => ramps.destructive.base,
}
}
/// Builds the highlight style for one run of a code view row.
pub(crate) fn run_style(
self,
selected: bool,
colors: ColorTokens,
ramps: Ramps,
) -> HighlightStyle {
HighlightStyle {
color: Some(self.color(colors, ramps)),
background_color: selected.then_some(colors.selection),
..Default::default()
}
}
}
impl Language {
/// Maps a fence info string to a language.
pub(crate) fn from_fence_info(info: &str) -> Option<Language> {
match info.to_ascii_lowercase().as_str() {
"plain" | "text" | "txt" => Some(Language::Plain),
"rust" | "rs" => Some(Language::Rust),
"typescript" | "ts" => Some(Language::TypeScript),
"javascript" | "js" => Some(Language::JavaScript),
"python" | "py" => Some(Language::Python),
_ => None,
}
}
}
/// A gutter cell sized to the whole row.
pub(crate) fn gutter_cell<E>(cx: &App, color: Hsla, content: E) -> gpui::Div
where
E: IntoElement,
{
let theme = cx.theme();
div()
.size(CODE_GUTTER_WIDTH)
.flex()
.items_center()
.justify_center()
.flex_none()
.font_family(theme.mono_font)
.text_size(theme.sizes.small.text_size)
.line_height(gpui::relative(1.0))
.text_color(color)
.child(content)
}
/// A change wash: the ramp color at the alpha rows tint with.
pub(crate) fn wash(color: Hsla) -> Hsla {
Hsla {
a: color.a * WASH_ALPHA,
..color
}
}
/// The stronger wash under number gutters and intra-line word changes.
pub(crate) fn wash_strong(color: Hsla) -> Hsla {
Hsla {
a: color.a * WASH_ALPHA_STRONG,
..color
}
}
/// The subtle wash that sets the number gutter off from the code.
pub(crate) fn wash_gutter(colors: &ColorTokens) -> Hsla {
Hsla {
a: colors.muted.a * WASH_ALPHA_GUTTER,
..colors.muted
}
}
/// One highlighted code line as styled text, roles resolved from the theme.
pub(crate) fn code_line(line: &Line, colors: ColorTokens, ramps: Ramps) -> StyledText {
let mut highlights: Vec<(Range<usize>, HighlightStyle)> = Vec::new();
let mut offset = 0usize;
for span in &line.spans {
let end = offset + span.text.len();
if span.role != Role::Text {
highlights.push((
offset..end,
HighlightStyle {
color: Some(span.role.color(colors, ramps)),
..Default::default()
},
));
}
offset = end;
}
StyledText::new(line.text()).with_highlights(highlights)
}