new layout (wip) (#34)
Reviewed-on: #34
@@ -0,0 +1,71 @@
|
||||
[package]
|
||||
name = "ui"
|
||||
description = "Signed's native GPUI theme, icons, and components."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
gpui.workspace = true
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
serde.workspace = true
|
||||
rust-embed.workspace = true
|
||||
flume.workspace = true
|
||||
unicode-segmentation = "1.12"
|
||||
image = { version = "0.25.1", default-features = false }
|
||||
similar = "2"
|
||||
pulldown-cmark = { version = "0.13", default-features = false }
|
||||
tree-sitter-rust = "0.24"
|
||||
tree-sitter-typescript = "0.23"
|
||||
tree-sitter-javascript = "0.23"
|
||||
tree-sitter-python = "0.23"
|
||||
toml = "0.8"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
cpal = "0.18"
|
||||
tree-sitter = "0.25"
|
||||
|
||||
[target.'cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))'.dependencies]
|
||||
async-channel = "2"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
notify = "8"
|
||||
zbus = "5"
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
windows = { version = "0.62", features = [
|
||||
"Foundation",
|
||||
"UI",
|
||||
"UI_ViewManagement",
|
||||
"Win32_Foundation",
|
||||
"Win32_System_Com",
|
||||
] }
|
||||
windows-registry = "0.6"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = "0.6"
|
||||
objc2 = "0.6"
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = [
|
||||
"NSAccessibility",
|
||||
"NSAppearance",
|
||||
"NSColor",
|
||||
"NSColorSpace",
|
||||
"NSWorkspace",
|
||||
"block2",
|
||||
"objc2-core-foundation",
|
||||
] }
|
||||
objc2-foundation = { version = "=0.3.2", default-features = false, features = [
|
||||
"NSDictionary",
|
||||
"NSDistributedNotificationCenter",
|
||||
"NSNotification",
|
||||
"NSKeyValueObserving",
|
||||
"NSOperation",
|
||||
"NSUserDefaults",
|
||||
"NSString",
|
||||
"block2",
|
||||
"std",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
gpui = { workspace = true, features = ["test-support"] }
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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)),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M12 20.25V4.5" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M5.75 10L12 3.75L18.25 10" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 305 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M6 14.15L10.0321 18L18 7" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 198 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M5.75 9.5L12 15.75L18.25 9.5" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 202 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M9.5 18.25L15.75 12L9.5 5.75" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 202 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M16.2426 12.0005H7.75736M12 16.2431V7.75781M21.25 12C21.25 17.1086 17.1086 21.25 12 21.25C6.89137 21.25 2.75 17.1086 2.75 12C2.75 6.89137 6.89137 2.75 12 2.75C17.1086 2.75 21.25 6.89137 21.25 12Z" stroke="black" stroke-width="1.5" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 345 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M12 6.75V12H16.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="12" cy="12" r="9.25" stroke="black" stroke-width="1.5"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 259 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M6.25 6.25L17.75 17.75M17.75 6.25L6.25 17.75" stroke="black" stroke-width="1.5" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 194 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M7.75 7.75V6.75C7.75 5.09315 9.09315 3.75 10.75 3.75H17.25C18.9069 3.75 20.25 5.09315 20.25 6.75V13.26C20.25 14.9169 18.9069 16.26 17.25 16.26H16.25M3.75 10.75V17.25C3.75 18.9069 5.09315 20.25 6.75 20.25H13.25C14.9069 20.25 16.25 18.9069 16.25 17.25V10.75C16.25 9.09315 14.9069 7.75 13.25 7.75H6.75C5.09315 7.75 3.75 9.09315 3.75 10.75Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 510 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<rect x="10" y="3" width="4" height="4" rx="2" fill="black"/><rect x="10" y="10" width="4" height="4" rx="2" fill="black"/><rect x="10" y="17" width="4" height="4" rx="2" fill="black"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 266 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M3.75 13.0199C8.54029 18.1132 15.4597 18.1132 20.25 13.0199" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M3.75 7.62257C6.14516 5.07587 9.0726 3.80251 12 3.80249C14.9274 3.80247 17.8549 5.07576 20.25 7.62238" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 17V20.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M8.25 16.5L6.75 18.9821" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M15.5 16.5L17.25 18.9821" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 765 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M21.2742 10.685C16.4537 2.77174 7.54646 2.77164 2.72595 10.6849C2.23523 11.4904 2.23523 12.5094 2.72595 13.3149C7.54646 21.2282 16.4537 21.2283 21.2742 13.3151C21.7649 12.5095 21.7649 11.4905 21.2742 10.685Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M15.25 12C15.25 13.7949 13.7949 15.25 12 15.25C10.2051 15.25 8.75 13.7949 8.75 12C8.75 10.2051 10.2051 8.75 12 8.75C13.7949 8.75 15.25 10.2051 15.25 12Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 626 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M11.9216 2.75H7.75C6.09315 2.75 4.75 4.09315 4.75 5.75V18.25C4.75 19.9069 6.09315 21.25 7.75 21.25H16.25C17.9069 21.25 19.25 19.9069 19.25 18.25V10.0784C19.25 9.54799 19.0393 9.03929 18.6642 8.66421L13.3358 3.33579C12.9607 2.96071 12.452 2.75 11.9216 2.75Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M12.75 3.25V7.25C12.75 8.35457 13.6454 9.25 14.75 9.25H18.75" stroke="black" stroke-width="1.5" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 560 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M8.72581 3.75H5.75C4.09315 3.75 2.75 5.09315 2.75 6.75V16.25C2.75 17.9069 4.09315 19.25 5.75 19.25H18.25C19.9069 19.25 21.25 17.9069 21.25 16.25V8.75C21.25 7.09315 19.9069 5.75 18.25 5.75H13.2186C12.4372 5.75 11.6866 5.4451 11.1266 4.90018L10.8179 4.59982C10.2578 4.0549 9.50723 3.75 8.72581 3.75Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M21.25 12.75C21.25 11.0931 19.9069 9.75 18.25 9.75H5.75C4.09315 9.75 2.75 11.0931 2.75 12.75" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 656 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="6.5" cy="6" r="2.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="6.5" cy="18" r="2.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="17.5" cy="6" r="2.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M6.5 8.25V15.75" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M17.5 8.25V9C17.5 10.6569 16.1569 12 14.5 12H9.5C7.84315 12 6.5 13.3431 6.5 15V15.75" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 713 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M10.25 9L7.95711 11.2929C7.56658 11.6834 7.56658 12.3166 7.95711 12.7071L10.25 15M13.75 9L16.0429 11.2929C16.4334 11.6834 16.4334 12.3166 16.0429 12.7071L13.75 15M6.75 20.25H17.25C18.9069 20.25 20.25 18.9069 20.25 17.25V6.75C20.25 5.09315 18.9069 3.75 17.25 3.75H6.75C5.09315 3.75 3.75 5.09315 3.75 6.75V17.25C3.75 18.9069 5.09315 20.25 6.75 20.25Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 522 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="12" cy="12" r="5.25" stroke="black" stroke-width="1.5" stroke-linecap="round"/><path d="M6.5 12H1.75" stroke="black" stroke-width="1.5" stroke-linecap="round"/><path d="M22.25 12H17.5" stroke="black" stroke-width="1.5" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 336 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M21.25 12C21.25 17.1086 17.1086 21.25 12 21.25C6.89137 21.25 2.75 17.1086 2.75 12C2.75 6.89137 6.89137 2.75 12 2.75C17.1086 2.75 21.25 6.89137 21.25 12Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="3 4"/><path d="M15 9L9 15" stroke="black" stroke-width="1.5" stroke-linecap="round"/><path d="M15 15L9 9" stroke="black" stroke-width="1.5" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 507 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M15 9.5L10.5 15L8.5 13" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M21.25 12C21.25 17.1086 17.1086 21.25 12 21.25C6.89137 21.25 2.75 17.1086 2.75 12C2.75 6.89137 6.89137 2.75 12 2.75C17.1086 2.75 21.25 6.89137 21.25 12Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="3 4"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 464 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M21.25 12C21.25 17.1086 17.1086 21.25 12 21.25C6.89137 21.25 2.75 17.1086 2.75 12C2.75 6.89137 6.89137 2.75 12 2.75C17.1086 2.75 21.25 6.89137 21.25 12Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="3 4"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 349 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="6.5" cy="6" r="2.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="6.5" cy="18" r="2.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="17.5" cy="18" r="2.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M6.5 8.25V15.75" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M17.5 10.75V15.75" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M15.5 4L19.5 8M19.5 4L15.5 8" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 768 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="6.5" cy="6" r="2.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="6.5" cy="18" r="2.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="17.5" cy="18" r="2.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M6.5 8.25V15.75" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.25 6C18.25 6.41421 17.9142 6.75 17.5 6.75C17.0858 6.75 16.75 6.41421 16.75 6C16.75 5.58579 17.0858 5.25 17.5 5.25C17.9142 5.25 18.25 5.58579 18.25 6Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.25 11.25C18.25 11.6642 17.9142 12 17.5 12C17.0858 12 16.75 11.6642 16.75 11.25C16.75 10.8358 17.0858 10.5 17.5 10.5C17.9142 10.5 18.25 10.8358 18.25 11.25Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="6" cy="6" r="2.25" stroke="black" stroke-width="1.5"/><circle cx="6" cy="18" r="2.25" stroke="black" stroke-width="1.5"/><circle cx="18" cy="18" r="2.25" stroke="black" stroke-width="1.5"/><path d="M6 8.25V15.75" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M8.5 6H15C16.6569 6 18 7.34315 18 9V15.75" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 522 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="6" cy="6" r="2.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="6" cy="18" r="2.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="18" cy="18" r="2.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M6 8.25V15.75" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M13 6H15C16.6569 6 18 7.34315 18 9V15.75" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M14 3.75L11.75 6L14 8.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 779 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M3.75 8.55C3.75 6.86984 3.75 6.02976 4.07698 5.38803C4.3646 4.82354 4.82354 4.3646 5.38803 4.07698C6.02976 3.75 6.86984 3.75 8.55 3.75H10.25V10.25H3.75V8.55Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M13.75 3.75H15.45C17.1302 3.75 17.9702 3.75 18.612 4.07698C19.1765 4.3646 19.6354 4.82354 19.923 5.38803C20.25 6.02976 20.25 6.86984 20.25 8.55V10.25H13.75V3.75Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M3.75 13.75H10.25V20.25H8.55C6.86984 20.25 6.02976 20.25 5.38803 19.923C4.82354 19.6354 4.3646 19.1765 4.07698 18.612C3.75 17.9702 3.75 17.1302 3.75 15.45V13.75Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M13.75 13.75H20.25V15.45C20.25 17.1302 20.25 17.9702 19.923 18.612C19.6354 19.1765 19.1765 19.6354 18.612 19.923C17.9702 20.25 17.1302 20.25 15.45 20.25H13.75V13.75Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M3.75 12.75H8.0702C8.42126 14.6006 10.0472 16 12 16C13.9528 16 15.5787 14.6006 15.9298 12.75L20.25 12.75M17.25 20.25H6.75001C5.09315 20.25 3.75 18.9068 3.75001 17.25L3.75004 6.74999C3.75005 5.09314 5.09319 3.75 6.75004 3.75L17.25 3.75C18.9069 3.75 20.25 5.09315 20.25 6.75V17.25C20.25 18.9069 18.9069 20.25 17.25 20.25Z" stroke="black" stroke-width="1.5" stroke-linecap="square" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 494 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M12.0003 2.75L12 6.25M12.0003 17.75V21.25M2.75 12.0007H6.25M17.75 12.0007H21.25M5.45948 5.45905L7.93414 7.93414M16.0661 16.0656L18.541 18.5405M5.45976 18.5412L7.93463 16.0664M16.0664 7.93463L18.5412 5.45976" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 380 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M21.25 7.75C21.25 6.09315 19.9069 4.75 18.25 4.75H5.75C4.09315 4.75 2.75 6.09315 2.75 7.75V16.25C2.75 17.9069 4.09315 19.25 5.75 19.25H18.25C19.9069 19.25 21.25 17.9069 21.25 16.25V7.75Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M6.75 14.25V9.75L9 12L11.25 9.75V14.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M15.75 9.75V14.25L14 12.5" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M15.75 14.25L17.5 12.5" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 724 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M16.25 7V11.5C16.25 13.8472 14.3472 15.75 12 15.75C9.65279 15.75 7.75 13.8472 7.75 11.5V7C7.75 4.65279 9.65279 2.75 12 2.75C14.3472 2.75 16.25 4.65279 16.25 7Z" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke="black"/><path d="M12.0009 19C15.0764 19 17.7195 17.1489 18.8769 14.5M12.0009 19C8.92546 19 6.28233 17.1489 5.125 14.5M12.0009 19V21.25" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke="black"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 543 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<rect x="3" y="10" width="4" height="4" rx="2" fill="black"/><rect x="10" y="10" width="4" height="4" rx="2" fill="black"/><rect x="17" y="10" width="4" height="4" rx="2" fill="black"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 266 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M12 5.25V12M12 12V18.75M12 12H5.25M12 12H18.75" stroke="black" stroke-width="1.5" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 196 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M13 21C13.5523 21 14 20.5523 14 20C14 19.4477 13.5523 19 13 19C12.4477 19 12 19.4477 12 20C12 20.5523 12.4477 21 13 21Z" fill="black"/><path d="M21 11C21 10.4477 20.5523 9.99999 20 9.99999C19.4477 9.99999 19 10.4477 19 11C19 11.5523 19.4477 12 20 12C20.5523 12 21 11.5523 21 11Z" fill="black"/><path d="M19.9295 14.2679C20.4078 14.5441 20.5716 15.1557 20.2955 15.634C20.0193 16.1123 19.4078 16.2761 18.9295 16C18.4512 15.7238 18.2873 15.1123 18.5634 14.634C18.8396 14.1557 19.4512 13.9918 19.9295 14.2679Z" fill="black"/><path d="M17.3676 19.2942C17.8459 19.0181 18.0098 18.4065 17.7336 17.9282C17.4575 17.4499 16.8459 17.286 16.3676 17.5621C15.8893 17.8383 15.7254 18.4499 16.0016 18.9282C16.2777 19.4065 16.8893 19.5703 17.3676 19.2942Z" fill="black"/><path d="M18.9269 7.99998C18.4487 8.27612 17.8371 8.11225 17.5609 7.63396C17.2848 7.15566 17.4487 6.54407 17.9269 6.26793C18.4052 5.99179 19.0168 6.15566 19.293 6.63396C19.5691 7.11225 19.4052 7.72384 18.9269 7.99998Z" fill="black"/><path d="M9.25 14.75V20.25H3.75" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M15.2493 4.41452C14.2521 3.98683 13.1537 3.75 12 3.75C7.44365 3.75 3.75 7.44365 3.75 12C3.75 15.498 5.92698 18.4875 9 19.6876" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M20.25 20.25L16.1265 16.1265M16.1265 16.1265C17.4385 14.8145 18.25 13.002 18.25 11C18.25 6.99594 15.0041 3.75 11 3.75C6.99594 3.75 3.75 6.99594 3.75 11C3.75 15.0041 6.99594 18.25 11 18.25C13.002 18.25 14.8145 17.4385 16.1265 16.1265Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 407 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M20.25 15.45V8.55C20.25 6.86984 20.25 6.02976 19.923 5.38803C19.6354 4.82354 19.1765 4.3646 18.612 4.07698C17.9702 3.75 17.1302 3.75 15.45 3.75H8.55C6.86984 3.75 6.02976 3.75 5.38803 4.07698C4.82354 4.3646 4.3646 4.82354 4.07698 5.38803C3.75 6.02976 3.75 6.86984 3.75 8.55V15.45C3.75 17.1302 3.75 17.9702 4.07698 18.612C4.3646 19.1765 4.82354 19.6354 5.38803 19.923C6.02976 20.25 6.86984 20.25 8.55 20.25H15.45C17.1302 20.25 17.9702 20.25 18.612 19.923C19.1765 19.6354 19.6354 19.1765 19.923 18.612C20.25 17.9702 20.25 17.1302 20.25 15.45Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 713 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M6.75 3.75H17.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M4.75 7.25H19.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M19.1556 10.75H4.84441C3.53306 10.75 2.57653 11.9908 2.91026 13.259L4.16144 18.0135C4.50827 19.3314 5.69986 20.25 7.06267 20.25H16.9373C18.3001 20.25 19.4917 19.3314 19.8386 18.0135L21.0897 13.259C21.4235 11.9908 20.4669 10.75 19.1556 10.75Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 633 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M20.25 15.45V8.55C20.25 6.86984 20.25 6.02976 19.923 5.38803C19.6354 4.82354 19.1765 4.3646 18.612 4.07698C17.9702 3.75 17.1302 3.75 15.45 3.75H8.55C6.86984 3.75 6.02976 3.75 5.38803 4.07698C4.82354 4.3646 4.3646 4.82354 4.07698 5.38803C3.75 6.02976 3.75 6.86984 3.75 8.55V15.45C3.75 17.1302 3.75 17.9702 4.07698 18.612C4.3646 19.1765 4.82354 19.6354 5.38803 19.923C6.02976 20.25 6.86984 20.25 8.55 20.25H15.45C17.1302 20.25 17.9702 20.25 18.612 19.923C19.1765 19.6354 19.6354 19.1765 19.923 18.612C20.25 17.9702 20.25 17.1302 20.25 15.45Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 713 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="12" cy="12" r="9.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M7.5 14.5L9 13C9.55229 12.4477 10.4477 12.4477 11 13C11.5523 13.5523 12.4477 13.5523 13 13L15.5 10.5" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M12.75 9.75H16.25V13.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 505 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M7.75 9.75H16.25C17.9069 9.75 19.25 11.0931 19.25 12.75V18.25C19.25 19.9069 17.9069 21.25 16.25 21.25H7.75C6.09315 21.25 4.75 19.9069 4.75 18.25V12.75C4.75 11.0931 6.09315 9.75 7.75 9.75ZM7.75 9.75V7C7.75 4.65279 9.65279 2.75 12 2.75C14.0926 2.75 15.832 4.26237 16.1847 6.25371" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 14V17" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 553 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M12 8.74986V12.7499M12 15.4999V15.4899M9.44847 4.37571L3.08105 14.672C1.84507 16.6706 3.28264 19.2499 5.63256 19.2499H18.3674C20.7173 19.2499 22.1549 16.6706 20.9189 14.672L14.5515 4.3757C13.3789 2.47958 10.6211 2.47958 9.44847 4.37571ZM12.25 15.4999C12.25 15.6379 12.1381 15.7499 12 15.7499C11.8619 15.7499 11.75 15.6379 11.75 15.4999C11.75 15.3618 11.8619 15.2499 12 15.2499C12.1381 15.2499 12.25 15.3618 12.25 15.4999Z" stroke="black" stroke-width="1.5" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 571 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></svg>
|
||||
|
After Width: | Height: | Size: 164 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></svg>
|
||||
|
After Width: | Height: | Size: 164 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></svg>
|
||||
|
After Width: | Height: | Size: 164 B |
@@ -0,0 +1,300 @@
|
||||
//! Signed's icon set: application-defined SVG glyphs.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use gpui::prelude::FluentBuilder as _;
|
||||
use gpui::{
|
||||
AnyElement, AssetSource, Hsla, IntoElement, ParentElement as _, Pixels, RenderOnce,
|
||||
SharedString, Styled as _, TimedTransformation, Transformation, Window, div, px, svg,
|
||||
};
|
||||
|
||||
const SMALL_ICON_SIZE: Pixels = px(14.0);
|
||||
const DEFAULT_ICON_SIZE: Pixels = px(16.0);
|
||||
const LARGE_ICON_SIZE: Pixels = px(20.0);
|
||||
/// The spin presents at most this rate, rotating a sprite needs no more frames.
|
||||
const SPIN_MAX_FPS: f32 = 60.0;
|
||||
|
||||
/// The semantic glyphs UI components need.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum IconRole {
|
||||
Check,
|
||||
Close,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Plus,
|
||||
Search,
|
||||
Folder,
|
||||
Warning,
|
||||
Copy,
|
||||
Eye,
|
||||
EyeOff,
|
||||
WindowMinimize,
|
||||
WindowMaximize,
|
||||
WindowRestore,
|
||||
Loader,
|
||||
Microphone,
|
||||
Stop,
|
||||
Settings,
|
||||
Refresh,
|
||||
More,
|
||||
Grid,
|
||||
File,
|
||||
Clock,
|
||||
Unlock,
|
||||
CirclePlus,
|
||||
GitCommit,
|
||||
GitIssueDone,
|
||||
GitIssueClosed,
|
||||
GitIssueOngoing,
|
||||
GitPullRequest,
|
||||
GitPullRequestClosed,
|
||||
GitPullRequestDraft,
|
||||
GitPullRequestMerged,
|
||||
GitClone,
|
||||
GitBranch,
|
||||
Markdown,
|
||||
Trending,
|
||||
EllipsisVertical,
|
||||
ArrowUp,
|
||||
Inbox,
|
||||
Stack,
|
||||
}
|
||||
|
||||
impl IconRole {
|
||||
/// The stable identifier used for element and debug ids.
|
||||
pub fn slug(self) -> &'static str {
|
||||
match self {
|
||||
Self::Check => "check",
|
||||
Self::Close => "close",
|
||||
Self::ChevronDown => "chevron-down",
|
||||
Self::ChevronRight => "chevron-right",
|
||||
Self::Plus => "plus",
|
||||
Self::Search => "search",
|
||||
Self::Folder => "folder",
|
||||
Self::Warning => "warning",
|
||||
Self::Copy => "copy",
|
||||
Self::Eye => "eye",
|
||||
Self::EyeOff => "eye-off",
|
||||
Self::WindowMinimize => "window-minimize",
|
||||
Self::WindowMaximize => "window-maximize",
|
||||
Self::WindowRestore => "window-restore",
|
||||
Self::Loader => "loader",
|
||||
Self::Microphone => "microphone",
|
||||
Self::Stop => "stop",
|
||||
Self::Settings => "settings",
|
||||
Self::Refresh => "refresh",
|
||||
Self::More => "more",
|
||||
Self::Grid => "grid",
|
||||
Self::File => "file",
|
||||
Self::Clock => "clock",
|
||||
Self::Unlock => "unlock",
|
||||
Self::CirclePlus => "circle-plus",
|
||||
Self::GitCommit => "git-commit",
|
||||
Self::GitIssueDone => "git-issue-done",
|
||||
Self::GitIssueClosed => "git-issue-closed",
|
||||
Self::GitIssueOngoing => "git-issue-ongoing",
|
||||
Self::GitPullRequest => "git-pull-request",
|
||||
Self::GitPullRequestClosed => "git-pull-request-closed",
|
||||
Self::GitPullRequestDraft => "git-pull-request-draft",
|
||||
Self::GitPullRequestMerged => "git-pull-request-merged",
|
||||
Self::GitClone => "git-clone",
|
||||
Self::GitBranch => "git-branch",
|
||||
Self::Markdown => "markdown",
|
||||
Self::Trending => "trending",
|
||||
Self::EllipsisVertical => "ellipsis-vertical",
|
||||
Self::ArrowUp => "arrow-up",
|
||||
Self::Inbox => "inbox",
|
||||
Self::Stack => "stack",
|
||||
}
|
||||
}
|
||||
|
||||
/// The bundled SVG asset path for the role.
|
||||
fn asset_path(self) -> SharedString {
|
||||
SharedString::from(format!("icons/{}.svg", self.slug()))
|
||||
}
|
||||
}
|
||||
|
||||
/// A glyph named by an application's own icon set.
|
||||
pub trait IconNamed {
|
||||
/// The SVG asset path, e.g. `icons/git-commit.svg`.
|
||||
fn path(self) -> SharedString;
|
||||
}
|
||||
|
||||
impl IconNamed for IconRole {
|
||||
fn path(self) -> SharedString {
|
||||
self.asset_path()
|
||||
}
|
||||
}
|
||||
|
||||
/// The glyph an icon draws.
|
||||
#[derive(Clone)]
|
||||
enum Glyph {
|
||||
Role(IconRole),
|
||||
Named(SharedString),
|
||||
}
|
||||
|
||||
/// An icon element. Painted with the ambient text color unless a color is set.
|
||||
#[derive(Clone, IntoElement)]
|
||||
pub struct Icon {
|
||||
glyph: Glyph,
|
||||
size: Pixels,
|
||||
color: Option<Hsla>,
|
||||
transformation: Option<Transformation>,
|
||||
rotation_period: Option<Duration>,
|
||||
}
|
||||
|
||||
/// Creates an icon for the role at the default size.
|
||||
pub fn icon(role: IconRole) -> Icon {
|
||||
Icon {
|
||||
glyph: Glyph::Role(role),
|
||||
size: DEFAULT_ICON_SIZE,
|
||||
color: None,
|
||||
transformation: None,
|
||||
rotation_period: None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Icon {
|
||||
/// Creates an icon from an application-defined icon set.
|
||||
pub fn named<I>(named: I) -> Self
|
||||
where
|
||||
I: IconNamed,
|
||||
{
|
||||
Self {
|
||||
glyph: Glyph::Named(named.path()),
|
||||
size: DEFAULT_ICON_SIZE,
|
||||
color: None,
|
||||
transformation: None,
|
||||
rotation_period: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn size(mut self, size: Pixels) -> Self {
|
||||
self.size = size;
|
||||
self
|
||||
}
|
||||
|
||||
/// The small size.
|
||||
pub fn small(mut self) -> Self {
|
||||
self.size = SMALL_ICON_SIZE;
|
||||
self
|
||||
}
|
||||
|
||||
/// The default medium size.
|
||||
pub fn medium(mut self) -> Self {
|
||||
self.size = DEFAULT_ICON_SIZE;
|
||||
self
|
||||
}
|
||||
|
||||
/// The large size.
|
||||
pub fn large(mut self) -> Self {
|
||||
self.size = LARGE_ICON_SIZE;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn color(mut self, color: Hsla) -> Self {
|
||||
self.color = Some(color);
|
||||
self
|
||||
}
|
||||
|
||||
/// An extra static SVG transformation.
|
||||
pub fn with_transformation(mut self, transformation: Transformation) -> Self {
|
||||
self.transformation = Some(transformation);
|
||||
self
|
||||
}
|
||||
|
||||
/// Spins the icon clockwise, one full turn per `period`.
|
||||
pub fn with_rotation_animation(mut self, period: Duration) -> Self {
|
||||
self.rotation_period = Some(period);
|
||||
self
|
||||
}
|
||||
|
||||
fn render_svg_path(
|
||||
size: Pixels,
|
||||
color: Option<Hsla>,
|
||||
transformation: Option<Transformation>,
|
||||
rotation_period: Option<Duration>,
|
||||
path: SharedString,
|
||||
) -> AnyElement {
|
||||
div()
|
||||
.flex_none()
|
||||
.size(size)
|
||||
.child(
|
||||
svg()
|
||||
.size_full()
|
||||
.path(path)
|
||||
.when_some(color, |el, color| el.text_color(color))
|
||||
.when_some(transformation, |el, transformation| {
|
||||
el.with_transformation(transformation)
|
||||
})
|
||||
.when_some(rotation_period, |el, period| {
|
||||
el.with_timed_transformation(
|
||||
TimedTransformation::rotation(
|
||||
period,
|
||||
transformation.unwrap_or_default(),
|
||||
)
|
||||
.with_max_fps(SPIN_MAX_FPS),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.into_any_element()
|
||||
}
|
||||
}
|
||||
|
||||
impl<I> From<I> for Icon
|
||||
where
|
||||
I: IconNamed,
|
||||
{
|
||||
fn from(named: I) -> Self {
|
||||
Icon::named(named)
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for Icon {
|
||||
fn render(self, window: &mut Window, _cx: &mut gpui::App) -> impl IntoElement {
|
||||
let Icon {
|
||||
glyph,
|
||||
size,
|
||||
color,
|
||||
transformation,
|
||||
rotation_period,
|
||||
} = self;
|
||||
|
||||
let color = color.unwrap_or_else(|| window.text_style().color);
|
||||
|
||||
match glyph {
|
||||
Glyph::Named(path) => {
|
||||
Self::render_svg_path(size, Some(color), transformation, rotation_period, path)
|
||||
}
|
||||
Glyph::Role(role) => Self::render_svg_path(
|
||||
size,
|
||||
Some(color),
|
||||
transformation,
|
||||
rotation_period,
|
||||
role.asset_path(),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(rust_embed::RustEmbed)]
|
||||
#[folder = "src/icons/assets"]
|
||||
#[exclude = "*.DS_Store"]
|
||||
pub struct Assets;
|
||||
|
||||
impl AssetSource for Assets {
|
||||
fn load(&self, path: &str) -> gpui::Result<Option<std::borrow::Cow<'static, [u8]>>> {
|
||||
let name = match path.strip_prefix("icons/") {
|
||||
Some(name) => name,
|
||||
None => return Ok(None),
|
||||
};
|
||||
Ok(Assets::get(name).map(|file| file.data))
|
||||
}
|
||||
|
||||
fn list(&self, path: &str) -> gpui::Result<Vec<SharedString>> {
|
||||
Ok(Self::iter()
|
||||
.map(|file| SharedString::from(format!("icons/{file}")))
|
||||
.filter(|file| file.starts_with(path))
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! Application window layout: a titlebar over a panel row.
|
||||
|
||||
use gpui::{
|
||||
App, BoxShadow, Div, ElementId, FocusHandle, Hsla, Refineable as _, StyleRefinement, Styled,
|
||||
Window, div, px,
|
||||
};
|
||||
|
||||
use crate::theme::{FOCUS_RING_ALPHA, FOCUS_RING_SPREAD};
|
||||
|
||||
pub mod panel;
|
||||
pub mod resizable;
|
||||
pub mod resize_handle;
|
||||
pub mod shell;
|
||||
pub mod titlebar;
|
||||
pub mod window_controls;
|
||||
|
||||
mod window_frame;
|
||||
|
||||
/// A row whose children center on the cross axis.
|
||||
#[must_use]
|
||||
pub fn h_flex() -> Div {
|
||||
div().flex().flex_row().items_center()
|
||||
}
|
||||
|
||||
/// A column whose children stack on the main axis.
|
||||
#[must_use]
|
||||
pub fn v_flex() -> Div {
|
||||
div().flex().flex_col()
|
||||
}
|
||||
|
||||
/// Extensions over [`Styled`], shared by the layout views.
|
||||
pub trait StyledExt: Styled + Sized {
|
||||
#[must_use]
|
||||
fn refine_style(mut self, style: &StyleRefinement) -> Self {
|
||||
self.style().refine(style);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<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()
|
||||
}
|
||||
|
||||
/// 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),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
//! The panel row: the window's main content, island-style over the app
|
||||
//! background. It can split once into two half-width panels with a drag
|
||||
//! divider between them; dragging the seam resizes the panels and a
|
||||
//! double-click restores the half split.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use gpui::{
|
||||
AnyElement, AnyView, App, Axis, Div, ElementId, Entity, IntoElement, ParentElement as _,
|
||||
Render, RenderOnce, SharedString, StyleRefinement, Styled as _, Window, div, px,
|
||||
};
|
||||
|
||||
use crate::components::tabs::Tab;
|
||||
use crate::layout::StyledExt as _;
|
||||
use crate::layout::resizable::{Resizable, ResizableState};
|
||||
use crate::theme::ActiveTheme as _;
|
||||
|
||||
/// A user-defined panel the row can show.
|
||||
#[allow(unused_variables)]
|
||||
pub trait Panel: Render + 'static {
|
||||
/// The kind the panel belongs to; same-kind panels group in the tab bar.
|
||||
fn kind(&self, cx: &App) -> Option<SharedString> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The title shown in the panel's tab.
|
||||
fn title(&self, cx: &App) -> SharedString;
|
||||
|
||||
/// The element drawn before the tab's title, e.g. an avatar or icon.
|
||||
fn prefix(&self, cx: &App) -> Option<AnyElement> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether the tab shows the loading spinner.
|
||||
fn loading(&self, cx: &App) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// An object-safe handle to a panel, so apps can hold panels by kind.
|
||||
#[allow(unused_variables)]
|
||||
pub trait PanelView: 'static {
|
||||
/// The panel's view.
|
||||
fn view(&self) -> AnyView;
|
||||
|
||||
/// The panel's kind, read live from the panel.
|
||||
fn kind(&self, cx: &App) -> Option<SharedString> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The panel's title, read live from the panel.
|
||||
fn title(&self, cx: &App) -> SharedString;
|
||||
|
||||
/// The panel's tab prefix, read live from the panel.
|
||||
fn prefix(&self, cx: &App) -> Option<AnyElement> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether the panel's tab shows the loading spinner.
|
||||
fn loading(&self, cx: &App) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Builds the panel's tab from its title, prefix, and loading state.
|
||||
fn tab(&self, key: ElementId, cx: &App) -> Tab {
|
||||
let mut tab = Tab::new(key, self.title(cx)).busy(self.loading(cx));
|
||||
if let Some(prefix) = self.prefix(cx) {
|
||||
tab = tab.lead(prefix);
|
||||
}
|
||||
tab
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Panel> PanelView for Entity<T> {
|
||||
fn view(&self) -> AnyView {
|
||||
self.clone().into()
|
||||
}
|
||||
|
||||
fn kind(&self, cx: &App) -> Option<SharedString> {
|
||||
self.read(cx).kind(cx)
|
||||
}
|
||||
|
||||
fn title(&self, cx: &App) -> SharedString {
|
||||
self.read(cx).title(cx)
|
||||
}
|
||||
|
||||
fn prefix(&self, cx: &App) -> Option<AnyElement> {
|
||||
self.read(cx).prefix(cx)
|
||||
}
|
||||
|
||||
fn loading(&self, cx: &App) -> bool {
|
||||
self.read(cx).loading(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: PanelView + ?Sized> PanelView for Arc<P> {
|
||||
fn view(&self) -> AnyView {
|
||||
(**self).view()
|
||||
}
|
||||
|
||||
fn kind(&self, cx: &App) -> Option<SharedString> {
|
||||
(**self).kind(cx)
|
||||
}
|
||||
|
||||
fn title(&self, cx: &App) -> SharedString {
|
||||
(**self).title(cx)
|
||||
}
|
||||
|
||||
fn prefix(&self, cx: &App) -> Option<AnyElement> {
|
||||
(**self).prefix(cx)
|
||||
}
|
||||
|
||||
fn loading(&self, cx: &App) -> bool {
|
||||
(**self).loading(cx)
|
||||
}
|
||||
}
|
||||
|
||||
/// The layout the cached panel content lays out with.
|
||||
fn content_style() -> StyleRefinement {
|
||||
StyleRefinement::default().size_full()
|
||||
}
|
||||
|
||||
/// The island chrome every panel paints.
|
||||
fn island(panel: Div, cx: &App) -> Div {
|
||||
let theme = cx.theme();
|
||||
let colors = theme.colors;
|
||||
|
||||
panel
|
||||
.size_full()
|
||||
.bg(colors.background)
|
||||
.border_1()
|
||||
.border_color(colors.border)
|
||||
.rounded(theme.radius.overlay)
|
||||
.overflow_hidden()
|
||||
}
|
||||
|
||||
/// The panel row drawn under the titlebar.
|
||||
#[derive(IntoElement)]
|
||||
#[must_use]
|
||||
pub struct PanelRow {
|
||||
id: ElementId,
|
||||
main: Option<AnyElement>,
|
||||
split: Option<AnyElement>,
|
||||
style: StyleRefinement,
|
||||
}
|
||||
|
||||
impl PanelRow {
|
||||
/// Creates the panel row.
|
||||
pub fn new<I>(id: I) -> Self
|
||||
where
|
||||
I: Into<ElementId>,
|
||||
{
|
||||
Self {
|
||||
id: id.into(),
|
||||
main: None,
|
||||
split: None,
|
||||
style: StyleRefinement::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the main panel's content.
|
||||
pub fn main<P>(mut self, main: P) -> Self
|
||||
where
|
||||
P: PanelView,
|
||||
{
|
||||
self.main = Some(main.view().cached(content_style()).into_any_element());
|
||||
self
|
||||
}
|
||||
|
||||
/// Splits the row into two half-width panels.
|
||||
pub fn split<P>(mut self, panel: P) -> Self
|
||||
where
|
||||
P: PanelView,
|
||||
{
|
||||
self.split = Some(panel.view().cached(content_style()).into_any_element());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl gpui::Styled for PanelRow {
|
||||
fn style(&mut self) -> &mut StyleRefinement {
|
||||
&mut self.style
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for PanelRow {
|
||||
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let id = self.id.clone();
|
||||
let gutter = px(8.);
|
||||
|
||||
let main = island(
|
||||
div()
|
||||
.size_full()
|
||||
.child(self.main.unwrap_or_else(|| div().into_any_element())),
|
||||
cx,
|
||||
);
|
||||
|
||||
let row = match self.split {
|
||||
Some(split) => {
|
||||
let sizes = window.with_element_namespace(id.clone(), |window| {
|
||||
window
|
||||
.use_keyed_state("panel-sizes", cx, |_, _| ResizableState::default())
|
||||
.clone()
|
||||
});
|
||||
let extent = window.viewport_size().width - gutter * 2.0;
|
||||
|
||||
if sizes.read(cx).sizes().is_empty() {
|
||||
sizes.update(cx, |state, cx| {
|
||||
state.set_pane_width(0, (extent - gutter) / 2.0, cx)
|
||||
});
|
||||
}
|
||||
|
||||
div().w_full().h_full().child(
|
||||
Resizable::new((id.clone(), "split"), sizes)
|
||||
.axis(Axis::Horizontal)
|
||||
.pane(main)
|
||||
.pane(island(div().size_full().child(split), cx))
|
||||
.h_full(),
|
||||
)
|
||||
}
|
||||
None => div().w_full().h_full().child(main),
|
||||
};
|
||||
|
||||
div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.h_full()
|
||||
.p_2()
|
||||
.pt_1()
|
||||
.refine_style(&self.style)
|
||||
.child(row)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
//! The resizable group: stacked panes with drag dividers, outside the dock.
|
||||
|
||||
use gpui::prelude::FluentBuilder as _;
|
||||
use gpui::{
|
||||
AnyElement, App, AppContext as _, Axis, Bounds, Context, ElementId, Entity,
|
||||
InteractiveElement as _, IntoElement, ParentElement as _, Pixels, RenderOnce, SharedString,
|
||||
StyleRefinement, Styled, Window, canvas, div, px,
|
||||
};
|
||||
|
||||
use crate::layout::StyledExt as _;
|
||||
use crate::layout::resize_handle::ResizeHandle;
|
||||
use crate::theme::{PANE_DEFAULT_SIZE, PANE_MIN_SIZE};
|
||||
|
||||
type DebugSelector = std::rc::Rc<dyn Fn() -> String>;
|
||||
|
||||
/// The retained pane sizes of one resizable group.
|
||||
#[derive(Default)]
|
||||
pub struct ResizableState {
|
||||
/// Sizes of every pane except the remainder pane, which fills what's left.
|
||||
sizes: Vec<Pixels>,
|
||||
/// The group's main-axis extent, captured at paint for drag clamping.
|
||||
measured: Option<Pixels>,
|
||||
}
|
||||
|
||||
impl ResizableState {
|
||||
/// Creates state whose panes start at the default size.
|
||||
pub fn new(cx: &mut App) -> Entity<Self> {
|
||||
cx.new(|_| Self::default())
|
||||
}
|
||||
|
||||
/// The stored size of each fixed pane; the remainder pane isn't listed.
|
||||
pub fn sizes(&self) -> &[Pixels] {
|
||||
&self.sizes
|
||||
}
|
||||
|
||||
/// Restores pane sizes, e.g. from a persisted layout.
|
||||
pub fn set_sizes<I>(&mut self, sizes: I, cx: &mut Context<Self>)
|
||||
where
|
||||
I: IntoIterator<Item = Pixels>,
|
||||
{
|
||||
self.sizes = sizes.into_iter().collect();
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Records the group's measured extent, notifying only when it changes.
|
||||
fn set_measured(&mut self, extent: Pixels, cx: &mut Context<Self>) {
|
||||
if self.measured != Some(extent) {
|
||||
self.measured = Some(extent);
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// The equal split of the measured extent, or the default pane size unmeasured.
|
||||
fn equal_split(&self, pane_count: usize) -> Pixels {
|
||||
match self.measured {
|
||||
// usize can exceed f32's exact integer range; bound it via u32 before casting.
|
||||
Some(extent) => extent / u32::try_from(pane_count).unwrap_or(u32::MAX) as f32,
|
||||
None => PANE_DEFAULT_SIZE,
|
||||
}
|
||||
}
|
||||
|
||||
/// The size pane `ix` renders at: its stored size, or the equal split.
|
||||
fn pane_size(&self, ix: usize, pane_count: usize) -> Pixels {
|
||||
self.sizes
|
||||
.get(ix)
|
||||
.copied()
|
||||
.unwrap_or_else(|| self.equal_split(pane_count))
|
||||
}
|
||||
|
||||
/// Applies a drag at divider `ix` (between pane ix and ix+1).
|
||||
fn resize(&mut self, ix: usize, delta: Pixels, mins: &[Pixels], cx: &mut Context<Self>) {
|
||||
let Some(&floor) = mins.get(ix) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let pane_count = mins.len();
|
||||
|
||||
let previous = self.pane_size(ix, pane_count);
|
||||
let mut size = previous + delta;
|
||||
size = size.max(floor);
|
||||
|
||||
if let Some(extent) = self.measured {
|
||||
let floors = mins
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(j, _)| *j != ix)
|
||||
.fold(px(0.), |sum, (_, min)| sum + *min);
|
||||
let ceiling = extent - floors;
|
||||
size = size.min(ceiling);
|
||||
}
|
||||
|
||||
// Earlier panes hold the equal split they already render at,
|
||||
// so the first drag does not snap them to a backfilled default.
|
||||
let backfill = self.equal_split(pane_count);
|
||||
while self.sizes.len() <= ix {
|
||||
self.sizes.push(backfill);
|
||||
}
|
||||
|
||||
self.sizes[ix] = size;
|
||||
|
||||
// A drag clamped at its floor or ceiling lands here on every mouse move,
|
||||
// only a change to the rendered size is worth a frame.
|
||||
if size != previous {
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets pane `ix`'s width, backfilling earlier panes.
|
||||
pub fn set_pane_width(&mut self, ix: usize, width: Pixels, cx: &mut Context<Self>) {
|
||||
while self.sizes.len() <= ix {
|
||||
self.sizes.push(width);
|
||||
}
|
||||
if self.sizes[ix] != width {
|
||||
self.sizes[ix] = width;
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// Restores pane `ix` to the equal split, as a double-click does.
|
||||
fn reset_pane(&mut self, ix: usize, pane_count: usize, cx: &mut Context<Self>) {
|
||||
let split = self.equal_split(pane_count);
|
||||
while self.sizes.len() <= ix {
|
||||
self.sizes.push(split);
|
||||
}
|
||||
self.sizes[ix] = split;
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// One pane of a resizable group: its content and its drag floor.
|
||||
#[must_use]
|
||||
pub struct ResizablePane {
|
||||
content: AnyElement,
|
||||
min: Pixels,
|
||||
}
|
||||
|
||||
impl ResizablePane {
|
||||
/// The floor a pane keeps while dragging unless the caller lowers it.
|
||||
pub const DEFAULT_MIN: Pixels = PANE_MIN_SIZE;
|
||||
|
||||
/// Wraps this element as a pane.
|
||||
pub fn new<E>(content: E) -> Self
|
||||
where
|
||||
E: IntoElement,
|
||||
{
|
||||
Self {
|
||||
content: content.into_any_element(),
|
||||
min: Self::DEFAULT_MIN,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the floor this pane keeps while dragging.
|
||||
pub fn min(mut self, min: Pixels) -> Self {
|
||||
self.min = min;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A group of panes stacked along one axis, separated by drag dividers.
|
||||
#[derive(IntoElement)]
|
||||
#[must_use]
|
||||
pub struct Resizable {
|
||||
id: ElementId,
|
||||
state: Entity<ResizableState>,
|
||||
axis: Axis,
|
||||
panes: Vec<ResizablePane>,
|
||||
debug_selector: Option<DebugSelector>,
|
||||
style: StyleRefinement,
|
||||
}
|
||||
|
||||
impl Resizable {
|
||||
/// Creates a group stacking its panes vertically, bound to `state`.
|
||||
pub fn new<I>(id: I, state: Entity<ResizableState>) -> Self
|
||||
where
|
||||
I: Into<ElementId>,
|
||||
{
|
||||
Self {
|
||||
id: id.into(),
|
||||
state,
|
||||
axis: Axis::Vertical,
|
||||
panes: Vec::new(),
|
||||
debug_selector: None,
|
||||
style: StyleRefinement::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the axis the panes stack along.
|
||||
pub fn axis(mut self, axis: Axis) -> Self {
|
||||
self.axis = axis;
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a pane with the default drag floor.
|
||||
pub fn pane<E>(mut self, content: E) -> Self
|
||||
where
|
||||
E: IntoElement,
|
||||
{
|
||||
self.panes.push(ResizablePane::new(content));
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a pane that can't be dragged below `min`.
|
||||
pub fn pane_with_min<E>(mut self, content: E, min: Pixels) -> Self
|
||||
where
|
||||
E: IntoElement,
|
||||
{
|
||||
self.panes.push(ResizablePane::new(content).min(min));
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the debug-bounds selector of each pane, suffixed with its index.
|
||||
pub fn debug_selector<F>(mut self, selector: F) -> Self
|
||||
where
|
||||
F: Fn() -> String + 'static,
|
||||
{
|
||||
self.debug_selector = Some(std::rc::Rc::new(selector));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Styled for Resizable {
|
||||
fn style(&mut self) -> &mut StyleRefinement {
|
||||
&mut self.style
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for Resizable {
|
||||
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let axis = self.axis;
|
||||
let state = self.state.clone();
|
||||
|
||||
let pane_count = self.panes.len();
|
||||
let mins: Vec<Pixels> = self.panes.iter().map(|pane| pane.min).collect();
|
||||
let debug_selector = self.debug_selector;
|
||||
|
||||
let sizes: Vec<Pixels> = (0..pane_count)
|
||||
.map(|ix| state.read(cx).pane_size(ix, pane_count))
|
||||
.collect();
|
||||
|
||||
div()
|
||||
.flex()
|
||||
.overflow_hidden()
|
||||
.when(axis == Axis::Vertical, |group| group.flex_col())
|
||||
.when(axis == Axis::Horizontal, |group| group.flex_row())
|
||||
.refine_style(&self.style)
|
||||
.children(self.panes.into_iter().enumerate().flat_map(|(ix, pane)| {
|
||||
let remainder = ix + 1 == pane_count;
|
||||
let pane_element = div()
|
||||
.overflow_hidden()
|
||||
.when(remainder, |pane_element| {
|
||||
pane_element
|
||||
.flex_1()
|
||||
.when(axis == Axis::Vertical, |p| p.min_h(pane.min))
|
||||
.when(axis == Axis::Horizontal, |p| p.min_w(pane.min))
|
||||
})
|
||||
.when(!remainder, |pane_element| {
|
||||
pane_element
|
||||
.flex_none()
|
||||
.when(axis == Axis::Vertical, |p| p.h(sizes[ix]).w_full())
|
||||
.when(axis == Axis::Horizontal, |p| p.w(sizes[ix]).h_full())
|
||||
})
|
||||
.when_some(debug_selector.clone(), |pane_element, selector| {
|
||||
let prefix = selector();
|
||||
pane_element.debug_selector(move || format!("{prefix}-{ix}"))
|
||||
})
|
||||
.child(pane.content)
|
||||
.into_any_element();
|
||||
|
||||
let divider = (!remainder).then(|| {
|
||||
// The positional index is a stable id: panes are append-only, never reordered.
|
||||
ResizeHandle::new(SharedString::from(format!("{}-divider-{ix}", self.id)))
|
||||
.axis(axis)
|
||||
.on_resize({
|
||||
let state = state.clone();
|
||||
let mins = mins.clone();
|
||||
move |delta, _, cx| {
|
||||
state.update(cx, |state, cx| state.resize(ix, delta, &mins, cx));
|
||||
}
|
||||
})
|
||||
.on_reset({
|
||||
let state = state.clone();
|
||||
let mins = mins.clone();
|
||||
move |_, cx| {
|
||||
state.update(cx, |state, cx| state.reset_pane(ix, mins.len(), cx));
|
||||
}
|
||||
})
|
||||
.into_any_element()
|
||||
});
|
||||
|
||||
std::iter::once(pane_element).chain(divider)
|
||||
}))
|
||||
.when(pane_count > 0, |group| {
|
||||
group.child(
|
||||
canvas(
|
||||
{
|
||||
let state = state.clone();
|
||||
move |bounds: Bounds<Pixels>, _, cx: &mut App| {
|
||||
let extent = match axis {
|
||||
Axis::Vertical => bounds.size.height,
|
||||
Axis::Horizontal => bounds.size.width,
|
||||
};
|
||||
state.update(cx, |state, cx| state.set_measured(extent, cx));
|
||||
}
|
||||
},
|
||||
|_, _, _, _| {},
|
||||
)
|
||||
.absolute()
|
||||
.inset_0(),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
//! The drag divider: a thin handle in the gap between panels that resizes
|
||||
//! them. It shows its hairline only while hovered or dragged.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use gpui::prelude::FluentBuilder as _;
|
||||
use gpui::{
|
||||
App, Axis, Bounds, CursorStyle, DispatchPhase, ElementId, HitboxBehavior,
|
||||
InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent,
|
||||
MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Point, RenderOnce, Role,
|
||||
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas,
|
||||
deferred, div, fill, point, px,
|
||||
};
|
||||
|
||||
use crate::layout::{StyledExt as _, focus_handle, focus_ring};
|
||||
use crate::theme::{
|
||||
ActiveTheme as _, BORDER_WIDTH, DISABLED_OPACITY, HAIRLINE_WIDTH, RESIZE_KEYBOARD_STEP,
|
||||
};
|
||||
|
||||
/// How far one keyboard arrow step moves the seam.
|
||||
const KEYBOARD_STEP: Pixels = RESIZE_KEYBOARD_STEP;
|
||||
|
||||
type ResizeHandler = Rc<dyn Fn(Pixels, &mut Window, &mut App)>;
|
||||
type ResetHandler = Rc<dyn Fn(&mut Window, &mut App)>;
|
||||
|
||||
/// The pointer drag state, keyed to the handle's element id.
|
||||
#[derive(Clone, Copy)]
|
||||
struct DragState {
|
||||
dragging: bool,
|
||||
last: Point<Pixels>,
|
||||
}
|
||||
|
||||
/// A thin drag divider that resizes the adjacent region.
|
||||
#[derive(IntoElement)]
|
||||
#[must_use]
|
||||
pub struct ResizeHandle {
|
||||
id: ElementId,
|
||||
/// The axis the drag moves along: a vertical seam drags horizontally.
|
||||
axis: Axis,
|
||||
disabled: bool,
|
||||
accessibility_label: Option<SharedString>,
|
||||
on_resize: Option<ResizeHandler>,
|
||||
on_reset: Option<ResetHandler>,
|
||||
style: StyleRefinement,
|
||||
}
|
||||
|
||||
impl ResizeHandle {
|
||||
/// Creates a horizontal resize handle (a vertical seam).
|
||||
pub fn new<I>(id: I) -> Self
|
||||
where
|
||||
I: Into<ElementId>,
|
||||
{
|
||||
Self {
|
||||
id: id.into(),
|
||||
axis: Axis::Horizontal,
|
||||
disabled: false,
|
||||
accessibility_label: None,
|
||||
on_resize: None,
|
||||
on_reset: None,
|
||||
style: StyleRefinement::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the axis the drag moves along.
|
||||
pub fn axis(mut self, axis: Axis) -> Self {
|
||||
self.axis = axis;
|
||||
self
|
||||
}
|
||||
|
||||
/// Renders the handle inert and dimmed.
|
||||
pub fn disabled(mut self, disabled: bool) -> Self {
|
||||
self.disabled = disabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Overrides the accessibility label, which defaults to "Resize".
|
||||
pub fn accessibility_label<L>(mut self, label: L) -> Self
|
||||
where
|
||||
L: Into<SharedString>,
|
||||
{
|
||||
self.accessibility_label = Some(label.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Runs for every pointer movement while the seam is dragged.
|
||||
pub fn on_resize<F>(mut self, handler: F) -> Self
|
||||
where
|
||||
F: Fn(Pixels, &mut Window, &mut App) + 'static,
|
||||
{
|
||||
self.on_resize = Some(Rc::new(handler));
|
||||
self
|
||||
}
|
||||
|
||||
/// Runs when the seam is double-clicked, to restore the default size.
|
||||
pub fn on_reset<F>(mut self, handler: F) -> Self
|
||||
where
|
||||
F: Fn(&mut Window, &mut App) + 'static,
|
||||
{
|
||||
self.on_reset = Some(Rc::new(handler));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl gpui::Styled for ResizeHandle {
|
||||
fn style(&mut self) -> &mut StyleRefinement {
|
||||
&mut self.style
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for ResizeHandle {
|
||||
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let theme = cx.theme();
|
||||
let ring = theme.colors.ring;
|
||||
let thickness = px(8.);
|
||||
|
||||
let label = self
|
||||
.accessibility_label
|
||||
.clone()
|
||||
.unwrap_or_else(|| SharedString::from("Resize"));
|
||||
|
||||
let drag = window.with_element_namespace(self.id.clone(), |window| {
|
||||
window
|
||||
.use_keyed_state("resize-drag", cx, |_, _| DragState {
|
||||
dragging: false,
|
||||
last: point(px(0.), px(0.)),
|
||||
})
|
||||
.clone()
|
||||
});
|
||||
|
||||
let focus = focus_handle(&self.id, window, cx);
|
||||
let dragging = drag.read(cx).dragging;
|
||||
let axis = self.axis;
|
||||
let disabled = self.disabled;
|
||||
|
||||
let cursor = match axis {
|
||||
Axis::Horizontal => CursorStyle::ResizeLeftRight,
|
||||
Axis::Vertical => CursorStyle::ResizeUpDown,
|
||||
};
|
||||
|
||||
let on_reset = self.on_reset;
|
||||
|
||||
deferred(
|
||||
div()
|
||||
.id(self.id.clone())
|
||||
.debug_selector(|| "resize-handle".to_string())
|
||||
.role(Role::Splitter)
|
||||
.aria_label(label)
|
||||
.flex_none()
|
||||
.when(axis == Axis::Horizontal, |handle| {
|
||||
handle.w(thickness).h_full()
|
||||
})
|
||||
.when(axis == Axis::Vertical, |handle| {
|
||||
handle.w_full().h(thickness)
|
||||
})
|
||||
.refine_style(&self.style)
|
||||
.when(self.disabled, |handle| handle.opacity(DISABLED_OPACITY))
|
||||
.when(!self.disabled, |handle| {
|
||||
handle
|
||||
.track_focus(&focus)
|
||||
.focusable()
|
||||
.tab_stop(true)
|
||||
.focus_visible(|style| style.shadow(focus_ring(ring)))
|
||||
.on_mouse_down_out({
|
||||
let focus = focus.clone();
|
||||
move |_, window, cx| {
|
||||
if focus.is_focused(window) {
|
||||
window.blur(cx);
|
||||
}
|
||||
}
|
||||
})
|
||||
.on_mouse_down(MouseButton::Left, {
|
||||
let drag = drag.clone();
|
||||
let focus = focus.clone();
|
||||
|
||||
move |event: &MouseDownEvent, window, cx| {
|
||||
window.focus(&focus, cx);
|
||||
cx.stop_propagation();
|
||||
|
||||
if event.click_count >= 2 {
|
||||
drag.update(cx, |drag, cx| {
|
||||
drag.dragging = false;
|
||||
cx.notify();
|
||||
});
|
||||
if let Some(on_reset) = on_reset.clone() {
|
||||
on_reset(window, cx);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
drag.update(cx, |drag, cx| {
|
||||
drag.dragging = true;
|
||||
drag.last = event.position;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
})
|
||||
.on_key_down({
|
||||
let on_resize = self.on_resize.clone();
|
||||
move |event: &KeyDownEvent, window, cx| {
|
||||
let delta = match (axis, event.keystroke.key.as_str()) {
|
||||
(Axis::Horizontal, "left") => Some(-KEYBOARD_STEP),
|
||||
(Axis::Horizontal, "right") => Some(KEYBOARD_STEP),
|
||||
(Axis::Vertical, "up") => Some(-KEYBOARD_STEP),
|
||||
(Axis::Vertical, "down") => Some(KEYBOARD_STEP),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(delta) = delta {
|
||||
cx.stop_propagation();
|
||||
if let Some(on_resize) = on_resize.clone() {
|
||||
on_resize(delta, window, cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.child(
|
||||
canvas(
|
||||
{
|
||||
move |bounds, window, _| {
|
||||
let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
|
||||
(hitbox, bounds)
|
||||
}
|
||||
},
|
||||
{
|
||||
let drag = drag.clone();
|
||||
let on_resize = self.on_resize.clone();
|
||||
move |_, (hitbox, bounds), window, _cx| {
|
||||
let hovered = hitbox.is_hovered(window);
|
||||
|
||||
if !disabled {
|
||||
window.set_cursor_style(cursor, &hitbox);
|
||||
}
|
||||
|
||||
if disabled || !(dragging || hovered) {
|
||||
return;
|
||||
}
|
||||
|
||||
let line = match axis {
|
||||
Axis::Horizontal => {
|
||||
let x = bounds.center().x - HAIRLINE_WIDTH;
|
||||
Bounds::from_corners(
|
||||
point(x, bounds.top()),
|
||||
point(x + BORDER_WIDTH, bounds.bottom()),
|
||||
)
|
||||
}
|
||||
Axis::Vertical => {
|
||||
let y = bounds.center().y - HAIRLINE_WIDTH;
|
||||
Bounds::from_corners(
|
||||
point(bounds.left(), y),
|
||||
point(bounds.right(), y + BORDER_WIDTH),
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
window.paint_quad(fill(line, ring));
|
||||
|
||||
window.on_mouse_event({
|
||||
let drag = drag.clone();
|
||||
let on_resize = on_resize.clone();
|
||||
move |event: &MouseMoveEvent, phase, window, cx| {
|
||||
if phase != DispatchPhase::Bubble {
|
||||
return;
|
||||
}
|
||||
|
||||
let (dragging, last) = {
|
||||
let drag = drag.read(cx);
|
||||
(drag.dragging, drag.last)
|
||||
};
|
||||
|
||||
if !dragging {
|
||||
return;
|
||||
}
|
||||
|
||||
if event.pressed_button != Some(MouseButton::Left) {
|
||||
drag.update(cx, |drag, cx| {
|
||||
drag.dragging = false;
|
||||
cx.notify();
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let delta = match axis {
|
||||
Axis::Horizontal => event.position.x - last.x,
|
||||
Axis::Vertical => event.position.y - last.y,
|
||||
};
|
||||
|
||||
drag.update(cx, |drag, _| drag.last = event.position);
|
||||
|
||||
if let Some(on_resize) = on_resize.clone() {
|
||||
on_resize(delta, window, cx);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
window.on_mouse_event({
|
||||
let drag = drag.clone();
|
||||
move |event: &MouseUpEvent, phase, _, cx| {
|
||||
if phase != DispatchPhase::Bubble
|
||||
|| event.button != MouseButton::Left
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if drag.read(cx).dragging {
|
||||
drag.update(cx, |drag, cx| {
|
||||
drag.dragging = false;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
)
|
||||
.absolute()
|
||||
.inset_0(),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! The application shell: the titlebar above the panel row, wrapped in the
|
||||
//! client-side window frame, with the toast and alert overlays mounted at
|
||||
//! the window root.
|
||||
|
||||
use gpui::prelude::FluentBuilder as _;
|
||||
use gpui::{
|
||||
AnyElement, App, ElementId, Entity, IntoElement, ParentElement as _, RenderOnce,
|
||||
StyleRefinement, Styled as _, Window, div,
|
||||
};
|
||||
|
||||
use crate::components::alert::{Alerts, AlertsView};
|
||||
use crate::components::grain::grain as grain_overlay;
|
||||
use crate::components::toast::{Toasts, ToastsView};
|
||||
use crate::layout::titlebar::Titlebar;
|
||||
use crate::layout::window_frame::frame;
|
||||
use crate::layout::{StyledExt as _, v_flex};
|
||||
use crate::theme::ActiveTheme as _;
|
||||
|
||||
/// The application shell.
|
||||
#[derive(IntoElement)]
|
||||
#[must_use]
|
||||
pub struct Shell {
|
||||
id: ElementId,
|
||||
titlebar: Option<Titlebar>,
|
||||
panel: Option<AnyElement>,
|
||||
transparent: bool,
|
||||
grain: bool,
|
||||
toasts: Option<Entity<Toasts>>,
|
||||
alerts: Option<Entity<Alerts>>,
|
||||
style: StyleRefinement,
|
||||
}
|
||||
|
||||
impl Shell {
|
||||
/// Creates the shell.
|
||||
pub fn new<I>(id: I) -> Self
|
||||
where
|
||||
I: Into<ElementId>,
|
||||
{
|
||||
Self {
|
||||
id: id.into(),
|
||||
titlebar: None,
|
||||
panel: None,
|
||||
transparent: false,
|
||||
grain: false,
|
||||
toasts: None,
|
||||
alerts: None,
|
||||
style: StyleRefinement::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the titlebar drawn above the panel row.
|
||||
pub fn titlebar(mut self, titlebar: Titlebar) -> Self {
|
||||
self.titlebar = Some(titlebar);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the panel row filling the rest of the window.
|
||||
pub fn panel<E>(mut self, panel: E) -> Self
|
||||
where
|
||||
E: IntoElement,
|
||||
{
|
||||
self.panel = Some(panel.into_any_element());
|
||||
self
|
||||
}
|
||||
|
||||
/// Paints the app background with the translucent material fill.
|
||||
pub fn transparent(mut self, transparent: bool) -> Self {
|
||||
self.transparent = transparent;
|
||||
self
|
||||
}
|
||||
|
||||
/// Textures the app background with a film-grain overlay.
|
||||
pub fn grain(mut self, grain: bool) -> Self {
|
||||
self.grain = grain;
|
||||
self
|
||||
}
|
||||
|
||||
/// Hosts the toast overlay raised on `toasts`.
|
||||
pub fn toasts(mut self, toasts: Entity<Toasts>) -> Self {
|
||||
self.toasts = Some(toasts);
|
||||
self
|
||||
}
|
||||
|
||||
/// Hosts the alert overlay stacked on `alerts`.
|
||||
pub fn alerts(mut self, alerts: Entity<Alerts>) -> Self {
|
||||
self.alerts = Some(alerts);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl gpui::Styled for Shell {
|
||||
fn style(&mut self) -> &mut StyleRefinement {
|
||||
&mut self.style
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for Shell {
|
||||
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let id = self.id.clone();
|
||||
let theme = cx.theme();
|
||||
|
||||
let background = if self.transparent {
|
||||
theme.material.background
|
||||
} else {
|
||||
theme.colors.muted
|
||||
};
|
||||
|
||||
frame(
|
||||
v_flex()
|
||||
.w_full()
|
||||
.h_full()
|
||||
.overflow_hidden()
|
||||
.bg(background)
|
||||
.refine_style(&self.style)
|
||||
.when(self.transparent && self.grain, |layout| {
|
||||
layout.child(grain_overlay())
|
||||
})
|
||||
.when_some(self.titlebar, |layout, titlebar| {
|
||||
layout.child(titlebar.transparent(self.transparent))
|
||||
})
|
||||
.child(self.panel.unwrap_or_else(|| div().into_any_element())),
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
.when_some(self.toasts, |frame, toasts| {
|
||||
frame.child(ToastsView::new((id.clone(), "toasts"), toasts))
|
||||
})
|
||||
.when_some(self.alerts, |frame, alerts| {
|
||||
frame.child(AlertsView::new((id, "alerts"), alerts))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//! The window titlebar: the full-width strip drawn above the panel row —
|
||||
//! the prefix, tab bar, and suffix in the middle, the platform's window
|
||||
//! controls at macOS's leading edge and every other platform's trailing
|
||||
//! edge. The bar itself moves the window, tab bar included; the prefix and
|
||||
//! suffix opt out, so a press on a control never starts a drag.
|
||||
|
||||
use gpui::prelude::FluentBuilder as _;
|
||||
use gpui::{
|
||||
AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _,
|
||||
RenderOnce, SharedString, StyleRefinement, Styled as _, Window,
|
||||
};
|
||||
|
||||
use crate::layout::window_controls::{WindowControls, titlebar_strip};
|
||||
use crate::layout::{StyledExt as _, h_flex};
|
||||
use crate::theme::{ActiveTheme as _, Size, TRAFFIC_LIGHT_PAD};
|
||||
|
||||
/// The window's titlebar.
|
||||
#[derive(IntoElement)]
|
||||
#[must_use]
|
||||
pub struct Titlebar {
|
||||
id: ElementId,
|
||||
prefix: Vec<AnyElement>,
|
||||
tab_bar: Option<AnyElement>,
|
||||
suffix: Vec<AnyElement>,
|
||||
transparent: bool,
|
||||
style: StyleRefinement,
|
||||
}
|
||||
|
||||
impl Titlebar {
|
||||
/// Creates the titlebar.
|
||||
pub fn new<I>(id: I) -> Self
|
||||
where
|
||||
I: Into<ElementId>,
|
||||
{
|
||||
Self {
|
||||
id: id.into(),
|
||||
prefix: Vec::new(),
|
||||
tab_bar: None,
|
||||
suffix: Vec::new(),
|
||||
transparent: false,
|
||||
style: StyleRefinement::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the tab bar drawn between the prefix and the suffix.
|
||||
pub fn tab_bar<E>(mut self, tab_bar: E) -> Self
|
||||
where
|
||||
E: IntoElement,
|
||||
{
|
||||
self.tab_bar = Some(tab_bar.into_any_element());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the element drawn before the tab bar, after the leading window controls.
|
||||
pub fn prefix<E>(mut self, prefix: E) -> Self
|
||||
where
|
||||
E: IntoElement,
|
||||
{
|
||||
self.prefix = vec![prefix.into_any_element()];
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the element drawn after the tab bar, before the trailing window controls.
|
||||
pub fn suffix<E>(mut self, suffix: E) -> Self
|
||||
where
|
||||
E: IntoElement,
|
||||
{
|
||||
self.suffix = vec![suffix.into_any_element()];
|
||||
self
|
||||
}
|
||||
|
||||
/// Leaves the strip unpainted so the shell's material backdrop shows through.
|
||||
pub(crate) fn transparent(mut self, transparent: bool) -> Self {
|
||||
self.transparent = transparent;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl gpui::Styled for Titlebar {
|
||||
fn style(&mut self) -> &mut StyleRefinement {
|
||||
&mut self.style
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for Titlebar {
|
||||
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let theme = cx.theme();
|
||||
let height = theme.titlebar_height;
|
||||
let padding_x = theme.sizes.resolve(Size::default()).padding_x;
|
||||
let shadow_bleed = theme.elevations.control.bleed();
|
||||
|
||||
let id = self.id;
|
||||
let bar_id = SharedString::from(format!("{id}-bar"));
|
||||
|
||||
titlebar_strip(
|
||||
h_flex()
|
||||
.id(id.clone())
|
||||
.debug_selector(move || bar_id.to_string())
|
||||
.flex_none()
|
||||
.w_full()
|
||||
.h(height)
|
||||
.gap_2()
|
||||
.when(!self.transparent, |bar| bar.bg(theme.colors.muted))
|
||||
.px(padding_x)
|
||||
.refine_style(&self.style)
|
||||
.when(cfg!(target_os = "macos"), |bar| bar.pl(TRAFFIC_LIGHT_PAD))
|
||||
.when(!self.prefix.is_empty(), |bar| {
|
||||
bar.child(
|
||||
h_flex()
|
||||
.occlude()
|
||||
.flex_none()
|
||||
.h_full()
|
||||
.items_center()
|
||||
.gap_1()
|
||||
.children(self.prefix),
|
||||
)
|
||||
})
|
||||
.when_some(self.tab_bar, |bar, tab_bar| {
|
||||
bar.child(
|
||||
h_flex()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.h_full()
|
||||
.overflow_hidden()
|
||||
// Include the tabs' outer shadow in the clip without shifting content.
|
||||
.px(shadow_bleed)
|
||||
.mx(-shadow_bleed)
|
||||
.when(cfg!(target_os = "windows"), |slot| slot.occlude())
|
||||
.child(tab_bar),
|
||||
)
|
||||
})
|
||||
.when(!self.suffix.is_empty(), |bar| {
|
||||
bar.child(
|
||||
h_flex()
|
||||
.occlude()
|
||||
.flex_none()
|
||||
.h_full()
|
||||
.items_center()
|
||||
.gap_1()
|
||||
.children(self.suffix),
|
||||
)
|
||||
}),
|
||||
(id.clone(), "drag"),
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
.child(WindowControls::new((id, "window-controls")))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
//! The window controls: minimize, maximize/restore, close — in the platform's
|
||||
//! own dress and behavior. Titlebar strips are app-owned: they move the
|
||||
//! window themselves via [`titlebar_strip`], so a dragged tab or button press
|
||||
//! never moves it; macOS draws its traffic lights in the shell's reserved pad
|
||||
//! and needs no controls of ours.
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use gpui::Decorations;
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
use gpui::SharedString;
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
use gpui::Styled as _;
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
use gpui::prelude::FluentBuilder as _;
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
use gpui::{AnyElement, ParentElement as _};
|
||||
use gpui::{
|
||||
App, ClickEvent, Div, ElementId, InteractiveElement as _, IntoElement, MouseButton, RenderOnce,
|
||||
Stateful, StatefulInteractiveElement as _, Window, WindowControlArea, div,
|
||||
};
|
||||
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
use crate::icons::{IconRole, icon};
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
use crate::theme::ActiveTheme as _;
|
||||
/// macOS traffic-lights zone: the pad a leading titlebar strip reserves.
|
||||
pub use crate::theme::TRAFFIC_LIGHT_PAD;
|
||||
#[cfg(target_os = "windows")]
|
||||
use crate::theme::{
|
||||
WINDOWS_CAPTION_WIDTH as CAPTION_WIDTH, WINDOWS_CLOSE_FOREGROUND, WINDOWS_CLOSE_HOVER,
|
||||
WINDOWS_CLOSE_PRESSED,
|
||||
};
|
||||
|
||||
/// The window controls for the trailing end of a titlebar strip.
|
||||
#[derive(IntoElement)]
|
||||
pub struct WindowControls {
|
||||
id: ElementId,
|
||||
}
|
||||
|
||||
impl WindowControls {
|
||||
/// Creates the controls row.
|
||||
pub fn new<I>(id: I) -> Self
|
||||
where
|
||||
I: Into<ElementId>,
|
||||
{
|
||||
Self { id: id.into() }
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for WindowControls {
|
||||
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let id = self.id.clone();
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
let controls = {
|
||||
// macOS draws native traffic lights in the shell's reserved pad; nothing to render.
|
||||
let _ = (id, window, cx);
|
||||
div()
|
||||
};
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
let controls = {
|
||||
let controls = window.window_controls();
|
||||
div()
|
||||
.flex_none()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.h_full()
|
||||
.when(controls.minimize, |row| {
|
||||
row.child(caption_button(
|
||||
cx,
|
||||
SharedString::from(format!("{id}-minimize")),
|
||||
IconRole::WindowMinimize,
|
||||
WindowControlArea::Min,
|
||||
window.is_minimizable(),
|
||||
false,
|
||||
))
|
||||
})
|
||||
.when(controls.maximize, |row| {
|
||||
row.child(caption_button(
|
||||
cx,
|
||||
SharedString::from(format!("{id}-maximize")),
|
||||
if window.is_maximized() {
|
||||
IconRole::WindowRestore
|
||||
} else {
|
||||
IconRole::WindowMaximize
|
||||
},
|
||||
WindowControlArea::Max,
|
||||
window.is_resizable(),
|
||||
false,
|
||||
))
|
||||
})
|
||||
.child(caption_button(
|
||||
cx,
|
||||
SharedString::from(format!("{id}-close")),
|
||||
IconRole::Close,
|
||||
WindowControlArea::Close,
|
||||
true,
|
||||
true,
|
||||
))
|
||||
};
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
let controls = {
|
||||
let controls = window.window_controls();
|
||||
let client_decorated =
|
||||
matches!(window.window_decorations(), Decorations::Client { .. });
|
||||
|
||||
div()
|
||||
.flex_none()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap_1()
|
||||
.when(client_decorated && controls.minimize, |row| {
|
||||
row.child(circle_button(
|
||||
cx,
|
||||
SharedString::from(format!("{id}-minimize")),
|
||||
IconRole::WindowMinimize,
|
||||
window.is_minimizable(),
|
||||
|window, _cx| window.minimize_window(),
|
||||
))
|
||||
})
|
||||
.when(client_decorated && controls.maximize, |row| {
|
||||
row.child(circle_button(
|
||||
cx,
|
||||
SharedString::from(format!("{id}-maximize")),
|
||||
if window.is_maximized() {
|
||||
IconRole::WindowRestore
|
||||
} else {
|
||||
IconRole::WindowMaximize
|
||||
},
|
||||
window.is_resizable(),
|
||||
|window, _cx| window.zoom_window(),
|
||||
))
|
||||
})
|
||||
.when(client_decorated, |row| {
|
||||
row.child(circle_button(
|
||||
cx,
|
||||
SharedString::from(format!("{id}-close")),
|
||||
IconRole::Close,
|
||||
true,
|
||||
|window, _cx| window.remove_window(),
|
||||
))
|
||||
})
|
||||
};
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
|
||||
let controls = {
|
||||
let _ = (id, window, cx);
|
||||
div()
|
||||
};
|
||||
|
||||
controls
|
||||
}
|
||||
}
|
||||
|
||||
/// Double-click on a titlebar strip maximizes where the platform does not do it.
|
||||
fn maximize_on_double_click() -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static {
|
||||
move |event, window, _cx| {
|
||||
if event.click_count() != 2 {
|
||||
return;
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
window.titlebar_double_click();
|
||||
#[cfg(target_os = "linux")]
|
||||
window.zoom_window();
|
||||
// Windows handles titlebar double-click natively via WindowControlArea::Drag.
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let _ = (event, window);
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
|
||||
{
|
||||
let _ = (event, window);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes an element a titlebar strip; `id` keys its drag state, which
|
||||
/// `use_state` would otherwise share among every strip in the window.
|
||||
pub fn titlebar_strip<I>(
|
||||
this: Stateful<Div>,
|
||||
id: I,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Stateful<Div>
|
||||
where
|
||||
I: Into<ElementId>,
|
||||
{
|
||||
let should_move = window.use_keyed_state(id.into(), cx, |_, _| false);
|
||||
this.window_control_area(WindowControlArea::Drag)
|
||||
.on_mouse_down_out(window.listener_for(&should_move, |should_move, _, _, _| {
|
||||
*should_move = false;
|
||||
}))
|
||||
.on_mouse_down(
|
||||
MouseButton::Left,
|
||||
window.listener_for(&should_move, |should_move, _, _, _| {
|
||||
*should_move = true;
|
||||
}),
|
||||
)
|
||||
.on_mouse_up(
|
||||
MouseButton::Left,
|
||||
window.listener_for(&should_move, |should_move, _, _, _| {
|
||||
*should_move = false;
|
||||
}),
|
||||
)
|
||||
.on_mouse_move(
|
||||
window.listener_for(&should_move, |should_move, _, window, cx| {
|
||||
if *should_move {
|
||||
*should_move = false;
|
||||
if !cx.has_active_drag() {
|
||||
window.start_window_move();
|
||||
}
|
||||
}
|
||||
}),
|
||||
)
|
||||
.on_click(maximize_on_double_click())
|
||||
}
|
||||
|
||||
/// One Windows caption button.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn caption_button(
|
||||
cx: &App,
|
||||
id: ElementId,
|
||||
role: IconRole,
|
||||
area: WindowControlArea,
|
||||
enabled: bool,
|
||||
close: bool,
|
||||
) -> AnyElement {
|
||||
let theme = cx.theme();
|
||||
let glyph_size = theme.sizes.small.dense_icon_size;
|
||||
|
||||
let hover = if close {
|
||||
WINDOWS_CLOSE_HOVER
|
||||
} else {
|
||||
theme.colors.muted_hover
|
||||
};
|
||||
|
||||
div()
|
||||
.id(id)
|
||||
.debug_selector({
|
||||
let id = SharedString::from(format!("window-control-{}", role.slug()));
|
||||
move || id.to_string()
|
||||
})
|
||||
.occlude()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.w(CAPTION_WIDTH)
|
||||
.h_full()
|
||||
.window_control_area(area)
|
||||
.text_color(if enabled {
|
||||
theme.colors.foreground
|
||||
} else {
|
||||
theme.colors.muted_foreground
|
||||
})
|
||||
.when(enabled, |button| {
|
||||
button
|
||||
.cursor_pointer()
|
||||
.hover(|hovered| {
|
||||
hovered.bg(hover).text_color(if close {
|
||||
WINDOWS_CLOSE_FOREGROUND
|
||||
} else {
|
||||
theme.colors.foreground
|
||||
})
|
||||
})
|
||||
.active(|pressed| {
|
||||
pressed
|
||||
.bg(if close {
|
||||
WINDOWS_CLOSE_PRESSED
|
||||
} else {
|
||||
theme.ramps.secondary.pressed
|
||||
})
|
||||
.text_color(theme.colors.foreground)
|
||||
})
|
||||
})
|
||||
.child(icon(role).size(glyph_size))
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
/// Adwaita's headerbar control: a small circle around a symbolic glyph.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn circle_button<I, F>(cx: &App, id: I, role: IconRole, enabled: bool, action: F) -> AnyElement
|
||||
where
|
||||
I: Into<ElementId>,
|
||||
F: Fn(&mut Window, &mut App) + 'static,
|
||||
{
|
||||
let theme = cx.theme();
|
||||
let small = theme.sizes.small;
|
||||
|
||||
div()
|
||||
.id(id)
|
||||
.debug_selector(move || format!("window-control-{}", role.slug()))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.size(small.control_height)
|
||||
.rounded(theme.radius.full)
|
||||
.text_color(if enabled {
|
||||
theme.colors.foreground
|
||||
} else {
|
||||
theme.colors.muted_foreground
|
||||
})
|
||||
.when(enabled, |button| {
|
||||
button
|
||||
.cursor_pointer()
|
||||
.hover(|hovered| hovered.bg(theme.colors.muted_hover))
|
||||
.on_click(move |_, window, cx| {
|
||||
cx.stop_propagation();
|
||||
action(window, cx);
|
||||
})
|
||||
})
|
||||
.child(icon(role).size(small.dense_icon_size))
|
||||
.into_any_element()
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//! The client-side window frame: the border, corners, shadow, and resize
|
||||
//! edges of a window the system does not decorate.
|
||||
|
||||
use gpui::prelude::FluentBuilder as _;
|
||||
use gpui::{
|
||||
App, Bounds, BoxShadow, CursorStyle, Decorations, Div, HitboxBehavior, InteractiveElement as _,
|
||||
IntoElement, MouseButton, ParentElement as _, Pixels, Point, ResizeEdge, Size, Styled as _,
|
||||
Tiling, Window, canvas, div, point, px, size,
|
||||
};
|
||||
|
||||
use crate::theme::{ActiveTheme as _, BORDER_WIDTH, INACTIVE_SHADOW_OPACITY, WINDOW_RESIZE_INSET};
|
||||
|
||||
/// Wraps a window's root in the frame it owes.
|
||||
pub fn frame<E>(child: E, window: &mut Window, cx: &App) -> Div
|
||||
where
|
||||
E: IntoElement,
|
||||
{
|
||||
let Decorations::Client { tiling } = window.window_decorations() else {
|
||||
return div().size_full().child(child);
|
||||
};
|
||||
|
||||
let tiling = if window.is_maximized() {
|
||||
Tiling::tiled()
|
||||
} else {
|
||||
tiling
|
||||
};
|
||||
|
||||
let inset = WINDOW_RESIZE_INSET;
|
||||
let border = cx.theme().colors.border;
|
||||
let radius = cx.theme().radius.overlay;
|
||||
|
||||
let shadow = frame_shadow(cx, window.is_window_active());
|
||||
window.set_client_inset(inset);
|
||||
|
||||
div()
|
||||
.size_full()
|
||||
.child(
|
||||
canvas(
|
||||
move |_, window, _| {
|
||||
let size = window.window_bounds().get_bounds().size;
|
||||
bands(size, inset)
|
||||
.into_iter()
|
||||
.filter(|(edge, _)| live(*edge, tiling))
|
||||
.map(|(edge, band)| {
|
||||
(edge, window.insert_hitbox(band, HitboxBehavior::Normal))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
},
|
||||
|_, bands, window, _| {
|
||||
for (edge, band) in bands {
|
||||
window.set_cursor_style(cursor(edge), &band);
|
||||
}
|
||||
},
|
||||
)
|
||||
.absolute()
|
||||
.size_full(),
|
||||
)
|
||||
.when(!tiling.top, |frame| frame.pt(inset))
|
||||
.when(!tiling.bottom, |frame| frame.pb(inset))
|
||||
.when(!tiling.left, |frame| frame.pl(inset))
|
||||
.when(!tiling.right, |frame| frame.pr(inset))
|
||||
.on_mouse_down(MouseButton::Left, move |event, window, _| {
|
||||
let size = window.window_bounds().get_bounds().size;
|
||||
if let Some(edge) =
|
||||
resize_edge(event.position, inset, size).filter(|edge| live(*edge, tiling))
|
||||
{
|
||||
window.start_window_resize(edge);
|
||||
}
|
||||
})
|
||||
.child(
|
||||
div()
|
||||
.size_full()
|
||||
.overflow_hidden()
|
||||
.border_color(border)
|
||||
.when(!tiling.top, |surface| surface.border_t(BORDER_WIDTH))
|
||||
.when(!tiling.bottom, |surface| surface.border_b(BORDER_WIDTH))
|
||||
.when(!tiling.left, |surface| surface.border_l(BORDER_WIDTH))
|
||||
.when(!tiling.right, |surface| surface.border_r(BORDER_WIDTH))
|
||||
.when(!(tiling.top || tiling.left), |surface| {
|
||||
surface.rounded_tl(radius)
|
||||
})
|
||||
.when(!(tiling.top || tiling.right), |surface| {
|
||||
surface.rounded_tr(radius)
|
||||
})
|
||||
.when(!(tiling.bottom || tiling.left), |surface| {
|
||||
surface.rounded_bl(radius)
|
||||
})
|
||||
.when(!(tiling.bottom || tiling.right), |surface| {
|
||||
surface.rounded_br(radius)
|
||||
})
|
||||
.when(!tiling.is_tiled(), |surface| surface.shadow(shadow))
|
||||
.child(child),
|
||||
)
|
||||
}
|
||||
|
||||
/// The dialog elevation's shadow, dimmed while the window is inactive.
|
||||
fn frame_shadow(cx: &App, active: bool) -> Vec<BoxShadow> {
|
||||
let opacity = if active { 1.0 } else { INACTIVE_SHADOW_OPACITY };
|
||||
cx.theme()
|
||||
.elevations
|
||||
.dialog
|
||||
.shadows()
|
||||
.iter()
|
||||
.map(|shadow| {
|
||||
let mut dimmed = shadow.clone();
|
||||
dimmed.color.a *= opacity;
|
||||
dimmed
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Which edge a press at `pos` resizes, or `None` for a press on the content.
|
||||
fn resize_edge(pos: Point<Pixels>, inset: Pixels, size: Size<Pixels>) -> Option<ResizeEdge> {
|
||||
let (top, bottom) = (pos.y < inset, pos.y > size.height - inset);
|
||||
let (left, right) = (pos.x < inset, pos.x > size.width - inset);
|
||||
|
||||
Some(match (top, bottom, left, right) {
|
||||
(true, _, true, _) => ResizeEdge::TopLeft,
|
||||
(true, _, _, true) => ResizeEdge::TopRight,
|
||||
(_, true, true, _) => ResizeEdge::BottomLeft,
|
||||
(_, true, _, true) => ResizeEdge::BottomRight,
|
||||
(true, ..) => ResizeEdge::Top,
|
||||
(_, true, ..) => ResizeEdge::Bottom,
|
||||
(_, _, true, _) => ResizeEdge::Left,
|
||||
(_, _, _, true) => ResizeEdge::Right,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The eight bands, as the rects [`resize_edge`] classifies to.
|
||||
fn bands(window: Size<Pixels>, inset: Pixels) -> [(ResizeEdge, Bounds<Pixels>); 8] {
|
||||
let band = |x: Pixels, y: Pixels, width: Pixels, height: Pixels| Bounds {
|
||||
origin: point(x, y),
|
||||
size: size(width, height),
|
||||
};
|
||||
|
||||
let (far_x, far_y) = (window.width - inset, window.height - inset);
|
||||
let (span_x, span_y) = (window.width - inset - inset, window.height - inset - inset);
|
||||
let zero = px(0.0);
|
||||
|
||||
[
|
||||
(ResizeEdge::TopLeft, band(zero, zero, inset, inset)),
|
||||
(ResizeEdge::TopRight, band(far_x, zero, inset, inset)),
|
||||
(ResizeEdge::BottomLeft, band(zero, far_y, inset, inset)),
|
||||
(ResizeEdge::BottomRight, band(far_x, far_y, inset, inset)),
|
||||
(ResizeEdge::Top, band(inset, zero, span_x, inset)),
|
||||
(ResizeEdge::Bottom, band(inset, far_y, span_x, inset)),
|
||||
(ResizeEdge::Left, band(zero, inset, inset, span_y)),
|
||||
(ResizeEdge::Right, band(far_x, inset, inset, span_y)),
|
||||
]
|
||||
}
|
||||
|
||||
/// Whether `edge` resizes: none of the sides it touches is flush.
|
||||
fn live(edge: ResizeEdge, tiling: Tiling) -> bool {
|
||||
let (top, bottom, left, right) = match edge {
|
||||
ResizeEdge::Top => (true, false, false, false),
|
||||
ResizeEdge::Bottom => (false, true, false, false),
|
||||
ResizeEdge::Left => (false, false, true, false),
|
||||
ResizeEdge::Right => (false, false, false, true),
|
||||
ResizeEdge::TopLeft => (true, false, true, false),
|
||||
ResizeEdge::TopRight => (true, false, false, true),
|
||||
ResizeEdge::BottomLeft => (false, true, true, false),
|
||||
ResizeEdge::BottomRight => (false, true, false, true),
|
||||
};
|
||||
!(top && tiling.top || bottom && tiling.bottom || left && tiling.left || right && tiling.right)
|
||||
}
|
||||
|
||||
/// The pointer an edge shows.
|
||||
fn cursor(edge: ResizeEdge) -> CursorStyle {
|
||||
match edge {
|
||||
ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
|
||||
ResizeEdge::Left | ResizeEdge::Right => CursorStyle::ResizeLeftRight,
|
||||
ResizeEdge::TopLeft | ResizeEdge::BottomRight => CursorStyle::ResizeUpLeftDownRight,
|
||||
ResizeEdge::TopRight | ResizeEdge::BottomLeft => CursorStyle::ResizeUpRightDownLeft,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Signed's native GPUI layer: theme, icons, components, and layout.
|
||||
|
||||
pub mod components;
|
||||
pub mod icons;
|
||||
pub mod layout;
|
||||
pub mod theme;
|
||||
|
||||
pub use components::*;
|
||||
use gpui::App;
|
||||
pub use icons::{Assets, Icon, IconRole};
|
||||
|
||||
/// Initializes the theme and every key binding the UI layer owns.
|
||||
pub fn init(cx: &mut App) {
|
||||
theme::Theme::init(cx);
|
||||
components::input::bind_input_keys(cx, None);
|
||||
components::combobox::bind_combobox_keys(cx);
|
||||
components::command_palette::bind_command_palette_keys(cx);
|
||||
components::code::bind_code_view_keys(cx);
|
||||
components::markdown::bind_text_view_keys(cx);
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
//! Semantic color roles. This module is the only place in the workspace
|
||||
//! allowed to hold color literals.
|
||||
|
||||
use gpui::{Hsla, hsla, rgb};
|
||||
|
||||
use crate::theme::{
|
||||
DEFAULT_TRANSPARENCY, MIN_MATERIAL_FILL_DARK, MIN_MATERIAL_FILL_LIGHT, ThemeVariant,
|
||||
};
|
||||
|
||||
fn hex(hex: u32) -> Hsla {
|
||||
rgb(hex).into()
|
||||
}
|
||||
|
||||
/// The dim scrim behind modal layers; always a translucent black.
|
||||
pub(crate) fn scrim(alpha: f32) -> Hsla {
|
||||
hsla(0., 0., 0., alpha)
|
||||
}
|
||||
|
||||
/// The semantic color roles components paint from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ColorTokens {
|
||||
pub background: Hsla,
|
||||
pub foreground: Hsla,
|
||||
pub surface: Hsla,
|
||||
pub surface_foreground: Hsla,
|
||||
pub primary: Hsla,
|
||||
pub primary_foreground: Hsla,
|
||||
pub secondary: Hsla,
|
||||
pub secondary_foreground: Hsla,
|
||||
pub muted: Hsla,
|
||||
pub muted_hover: Hsla,
|
||||
pub muted_foreground: Hsla,
|
||||
pub accent: Hsla,
|
||||
pub accent_foreground: Hsla,
|
||||
pub destructive: Hsla,
|
||||
pub destructive_foreground: Hsla,
|
||||
pub success: Hsla,
|
||||
pub success_foreground: Hsla,
|
||||
pub warning: Hsla,
|
||||
pub warning_foreground: Hsla,
|
||||
pub info: Hsla,
|
||||
pub info_foreground: Hsla,
|
||||
pub border: Hsla,
|
||||
pub input: Hsla,
|
||||
pub ring: Hsla,
|
||||
pub selection: Hsla,
|
||||
/// The scrim behind modal layers, translucent in every theme.
|
||||
pub overlay: Hsla,
|
||||
/// The overlay scrollbar thumb, translucent over scrolling content.
|
||||
pub scrollbar_thumb: Hsla,
|
||||
}
|
||||
|
||||
impl ColorTokens {
|
||||
/// Neutral light palette; the fallback when no system theme applies.
|
||||
pub fn light() -> Self {
|
||||
Self {
|
||||
background: hex(0xffffff),
|
||||
foreground: hex(0x18181b),
|
||||
surface: hex(0xfafafa),
|
||||
surface_foreground: hex(0x18181b),
|
||||
primary: hex(0x2563eb),
|
||||
primary_foreground: hex(0xffffff),
|
||||
secondary: hex(0xf4f4f5),
|
||||
secondary_foreground: hex(0x18181b),
|
||||
muted: hex(0xf4f4f5),
|
||||
muted_hover: hex(0xe4e4e7),
|
||||
muted_foreground: hex(0x71717a),
|
||||
accent: hex(0x2563eb),
|
||||
accent_foreground: hex(0xffffff),
|
||||
destructive: hex(0xdc2626),
|
||||
destructive_foreground: hex(0xffffff),
|
||||
success: hex(0x16a34a),
|
||||
success_foreground: hex(0xffffff),
|
||||
warning: hex(0xd97706),
|
||||
warning_foreground: hex(0xffffff),
|
||||
info: hex(0x0284c7),
|
||||
info_foreground: hex(0xffffff),
|
||||
border: hex(0xe4e4e7),
|
||||
input: hex(0xffffff),
|
||||
ring: hex(0x2563eb),
|
||||
selection: hex(0xdbeafe),
|
||||
overlay: scrim(0.25),
|
||||
// macOS light overlay thumbs are translucent black.
|
||||
scrollbar_thumb: hsla(0., 0., 0., 0.25),
|
||||
}
|
||||
}
|
||||
|
||||
/// Neutral dark palette; the fallback when no system theme applies.
|
||||
pub fn dark() -> Self {
|
||||
Self {
|
||||
background: hex(0x09090b),
|
||||
foreground: hex(0xfafafa),
|
||||
surface: hex(0x18181b),
|
||||
surface_foreground: hex(0xfafafa),
|
||||
primary: hex(0x3b82f6),
|
||||
primary_foreground: hex(0xffffff),
|
||||
secondary: hex(0x27272a),
|
||||
secondary_foreground: hex(0xfafafa),
|
||||
muted: hex(0x27272a),
|
||||
muted_hover: hex(0x3f3f46),
|
||||
muted_foreground: hex(0xa1a1aa),
|
||||
accent: hex(0x3b82f6),
|
||||
accent_foreground: hex(0xffffff),
|
||||
destructive: hex(0xef4444),
|
||||
destructive_foreground: hex(0xffffff),
|
||||
success: hex(0x22c55e),
|
||||
success_foreground: hex(0x052e16),
|
||||
warning: hex(0xf59e0b),
|
||||
warning_foreground: hex(0x451a03),
|
||||
info: hex(0x38bdf8),
|
||||
info_foreground: hex(0x082f49),
|
||||
border: hex(0x27272a),
|
||||
input: hex(0x09090b),
|
||||
ring: hex(0x3b82f6),
|
||||
selection: hex(0x1e3a8a),
|
||||
overlay: scrim(0.45),
|
||||
// macOS dark overlay thumbs are translucent light gray.
|
||||
scrollbar_thumb: hsla(0., 0., 1., 0.3),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The translucent paints surfaces lay over a native window material.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MaterialTokens {
|
||||
/// The window-sized fill the material shows through.
|
||||
pub background: Hsla,
|
||||
/// The hover wash over material surfaces.
|
||||
pub hover: Hsla,
|
||||
/// The selected-row fill over material surfaces.
|
||||
pub selection: Hsla,
|
||||
}
|
||||
|
||||
impl MaterialTokens {
|
||||
/// Derives the material paints from the resolved palette.
|
||||
pub(crate) fn derive(
|
||||
colors: &ColorTokens,
|
||||
selection: Hsla,
|
||||
variant: ThemeVariant,
|
||||
translucent: bool,
|
||||
transparency: Option<u8>,
|
||||
) -> Self {
|
||||
if !translucent {
|
||||
return Self {
|
||||
background: colors.background,
|
||||
hover: colors.muted,
|
||||
selection,
|
||||
};
|
||||
}
|
||||
|
||||
let level = transparency.unwrap_or(DEFAULT_TRANSPARENCY) as f32 / 100.0;
|
||||
|
||||
let floor = match variant {
|
||||
ThemeVariant::Light => MIN_MATERIAL_FILL_LIGHT,
|
||||
ThemeVariant::Dark => MIN_MATERIAL_FILL_DARK,
|
||||
};
|
||||
|
||||
Self {
|
||||
// The fill eases toward a floor instead of zero.
|
||||
background: colors.background.alpha(1.0 - level * (1.0 - floor)),
|
||||
// A foreground wash keeps hover visible over any backdrop hue.
|
||||
hover: colors.foreground.alpha(0.06),
|
||||
selection: selection.alpha(0.85),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
//! Sparse theme definitions: the shared schema for bundled presets and
|
||||
//! user theme files. Any field may be omitted; omitted fields fall through
|
||||
//! to the system theme, then to the neutral presets.
|
||||
|
||||
use gpui::{Hsla, Rgba};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::theme::ThemeVariant;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
|
||||
pub struct ThemeDefinition {
|
||||
mode: Option<ThemeVariant>,
|
||||
control_radius: Option<f32>,
|
||||
overlay_radius: Option<f32>,
|
||||
sm_radius: Option<f32>,
|
||||
accent: Option<String>,
|
||||
accent_foreground: Option<String>,
|
||||
background: Option<String>,
|
||||
foreground: Option<String>,
|
||||
surface: Option<String>,
|
||||
surface_foreground: Option<String>,
|
||||
primary: Option<String>,
|
||||
primary_foreground: Option<String>,
|
||||
secondary: Option<String>,
|
||||
secondary_foreground: Option<String>,
|
||||
muted: Option<String>,
|
||||
muted_hover: Option<String>,
|
||||
muted_foreground: Option<String>,
|
||||
destructive: Option<String>,
|
||||
destructive_foreground: Option<String>,
|
||||
success: Option<String>,
|
||||
success_foreground: Option<String>,
|
||||
warning: Option<String>,
|
||||
warning_foreground: Option<String>,
|
||||
info: Option<String>,
|
||||
info_foreground: Option<String>,
|
||||
border: Option<String>,
|
||||
input: Option<String>,
|
||||
ring: Option<String>,
|
||||
selection: Option<String>,
|
||||
overlay: Option<String>,
|
||||
scrollbar_thumb: Option<String>,
|
||||
}
|
||||
|
||||
impl ThemeDefinition {
|
||||
pub fn parse_toml(source: &str) -> anyhow::Result<Self> {
|
||||
Ok(toml::from_str(source)?)
|
||||
}
|
||||
|
||||
pub fn mode(&self) -> Option<ThemeVariant> {
|
||||
self.mode
|
||||
}
|
||||
|
||||
pub fn control_radius(&self) -> Option<f32> {
|
||||
self.control_radius
|
||||
}
|
||||
|
||||
pub fn overlay_radius(&self) -> Option<f32> {
|
||||
self.overlay_radius
|
||||
}
|
||||
|
||||
pub fn sm_radius(&self) -> Option<f32> {
|
||||
self.sm_radius
|
||||
}
|
||||
|
||||
pub fn accent(&self) -> Option<Hsla> {
|
||||
self.color(&self.accent, "accent")
|
||||
}
|
||||
|
||||
pub fn accent_foreground(&self) -> Option<Hsla> {
|
||||
self.color(&self.accent_foreground, "accent_foreground")
|
||||
}
|
||||
|
||||
pub fn background(&self) -> Option<Hsla> {
|
||||
self.color(&self.background, "background")
|
||||
}
|
||||
|
||||
pub fn foreground(&self) -> Option<Hsla> {
|
||||
self.color(&self.foreground, "foreground")
|
||||
}
|
||||
|
||||
pub fn surface(&self) -> Option<Hsla> {
|
||||
self.color(&self.surface, "surface")
|
||||
}
|
||||
|
||||
pub fn surface_foreground(&self) -> Option<Hsla> {
|
||||
self.color(&self.surface_foreground, "surface_foreground")
|
||||
}
|
||||
|
||||
pub fn primary(&self) -> Option<Hsla> {
|
||||
self.color(&self.primary, "primary")
|
||||
}
|
||||
|
||||
pub fn primary_foreground(&self) -> Option<Hsla> {
|
||||
self.color(&self.primary_foreground, "primary_foreground")
|
||||
}
|
||||
|
||||
pub fn secondary(&self) -> Option<Hsla> {
|
||||
self.color(&self.secondary, "secondary")
|
||||
}
|
||||
|
||||
pub fn secondary_foreground(&self) -> Option<Hsla> {
|
||||
self.color(&self.secondary_foreground, "secondary_foreground")
|
||||
}
|
||||
|
||||
pub fn muted(&self) -> Option<Hsla> {
|
||||
self.color(&self.muted, "muted")
|
||||
}
|
||||
|
||||
pub fn muted_hover(&self) -> Option<Hsla> {
|
||||
self.color(&self.muted_hover, "muted_hover")
|
||||
}
|
||||
|
||||
pub fn muted_foreground(&self) -> Option<Hsla> {
|
||||
self.color(&self.muted_foreground, "muted_foreground")
|
||||
}
|
||||
|
||||
pub fn destructive(&self) -> Option<Hsla> {
|
||||
self.color(&self.destructive, "destructive")
|
||||
}
|
||||
|
||||
pub fn destructive_foreground(&self) -> Option<Hsla> {
|
||||
self.color(&self.destructive_foreground, "destructive_foreground")
|
||||
}
|
||||
|
||||
pub fn success(&self) -> Option<Hsla> {
|
||||
self.color(&self.success, "success")
|
||||
}
|
||||
|
||||
pub fn success_foreground(&self) -> Option<Hsla> {
|
||||
self.color(&self.success_foreground, "success_foreground")
|
||||
}
|
||||
|
||||
pub fn warning(&self) -> Option<Hsla> {
|
||||
self.color(&self.warning, "warning")
|
||||
}
|
||||
|
||||
pub fn warning_foreground(&self) -> Option<Hsla> {
|
||||
self.color(&self.warning_foreground, "warning_foreground")
|
||||
}
|
||||
|
||||
pub fn info(&self) -> Option<Hsla> {
|
||||
self.color(&self.info, "info")
|
||||
}
|
||||
|
||||
pub fn info_foreground(&self) -> Option<Hsla> {
|
||||
self.color(&self.info_foreground, "info_foreground")
|
||||
}
|
||||
|
||||
pub fn border(&self) -> Option<Hsla> {
|
||||
self.color(&self.border, "border")
|
||||
}
|
||||
|
||||
pub fn input(&self) -> Option<Hsla> {
|
||||
self.color(&self.input, "input")
|
||||
}
|
||||
|
||||
pub fn ring(&self) -> Option<Hsla> {
|
||||
self.color(&self.ring, "ring")
|
||||
}
|
||||
|
||||
pub fn selection(&self) -> Option<Hsla> {
|
||||
self.color(&self.selection, "selection")
|
||||
}
|
||||
|
||||
pub fn overlay(&self) -> Option<Hsla> {
|
||||
self.color(&self.overlay, "overlay")
|
||||
}
|
||||
|
||||
pub fn scrollbar_thumb(&self) -> Option<Hsla> {
|
||||
self.color(&self.scrollbar_thumb, "scrollbar_thumb")
|
||||
}
|
||||
|
||||
/// Parses a color field, warning when a stated value is malformed.
|
||||
fn color(&self, field: &Option<String>, role: &str) -> Option<Hsla> {
|
||||
let value = field.as_deref()?;
|
||||
match parse_hex(value) {
|
||||
Some(color) => Some(color),
|
||||
None => {
|
||||
log::warn!("theme definition {role} is not #rgb/#rrggbb: {value:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses `#rgb` or `#rrggbb` into an opaque color.
|
||||
pub(crate) fn parse_hex(value: &str) -> Option<Hsla> {
|
||||
let digits = value.strip_prefix('#')?;
|
||||
let expand = |channels: [f32; 3]| Some(expand_rgb([channels[0], channels[1], channels[2]]));
|
||||
|
||||
match digits.len() {
|
||||
3 => {
|
||||
let mut channels = [0u8; 3];
|
||||
for (i, byte) in channels.iter_mut().enumerate() {
|
||||
*byte = u8::from_str_radix(&digits[i..i + 1], 16).ok()?;
|
||||
}
|
||||
expand([
|
||||
channels[0] as f32 / 15.0,
|
||||
channels[1] as f32 / 15.0,
|
||||
channels[2] as f32 / 15.0,
|
||||
])
|
||||
}
|
||||
6 => {
|
||||
let mut channels = [0u8; 3];
|
||||
for (i, byte) in channels.iter_mut().enumerate() {
|
||||
*byte = u8::from_str_radix(&digits[i * 2..i * 2 + 2], 16).ok()?;
|
||||
}
|
||||
expand([
|
||||
channels[0] as f32 / 255.0,
|
||||
channels[1] as f32 / 255.0,
|
||||
channels[2] as f32 / 255.0,
|
||||
])
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn expand_rgb([r, g, b]: [f32; 3]) -> Hsla {
|
||||
Hsla::from(Rgba { r, g, b, a: 1.0 })
|
||||
}
|
||||
@@ -0,0 +1,762 @@
|
||||
//! The theme engine: reads the running system theme, resolves it through
|
||||
//! presets and overrides, and installs the tokens every component paints
|
||||
//! from.
|
||||
//!
|
||||
//! Pipeline (plan §4.5): `ThemeSource` snapshot → `resolve` overlay chain →
|
||||
//! `Theme` global → all windows repaint. Watchers re-run the pipeline on
|
||||
//! real OS change events.
|
||||
|
||||
mod colors;
|
||||
mod definition;
|
||||
mod presets;
|
||||
mod ramps;
|
||||
mod resolve;
|
||||
mod source;
|
||||
mod system;
|
||||
mod typography;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
pub use colors::{ColorTokens, MaterialTokens};
|
||||
pub use definition::ThemeDefinition;
|
||||
use gpui::{
|
||||
App, Global, Hsla, Pixels, SpringConfig, WindowAppearance, WindowBackgroundAppearance, hsla, px,
|
||||
};
|
||||
pub use ramps::{AccentShades, Oklch};
|
||||
pub use resolve::{Ramps, ResolvedTheme};
|
||||
pub use system::{AccessibilityPreferences, SourceKind, SystemTheme};
|
||||
pub use typography::{TextRole, TypeMetrics, Typeset, Typography};
|
||||
|
||||
/// The hairline width of the control border every button and field paints.
|
||||
pub const BORDER_WIDTH: Pixels = px(1.0);
|
||||
/// The underline and drop indicators a tab strip paints.
|
||||
pub const TAB_INDICATOR_WIDTH: Pixels = px(2.0);
|
||||
/// The widest a titlebar tab grows before its label fades.
|
||||
pub const TAB_MAX_WIDTH: Pixels = px(240.0);
|
||||
/// The narrowest a titlebar tab shrinks, keeping short labels clear of the fade.
|
||||
pub const TAB_MIN_WIDTH: Pixels = px(140.0);
|
||||
/// Opacity applied to disabled controls.
|
||||
pub const DISABLED_OPACITY: f32 = 0.5;
|
||||
/// The focus ring's ink alpha.
|
||||
pub const FOCUS_RING_ALPHA: f32 = 0.5;
|
||||
/// The narrowest a popover may grow.
|
||||
pub const POPOVER_MIN_WIDTH: Pixels = px(128.0);
|
||||
/// The default minimum width of a dialog.
|
||||
pub const DIALOG_MIN_WIDTH: Pixels = px(384.0);
|
||||
/// The default minimum width of a menu.
|
||||
pub const MENU_MIN_WIDTH: Pixels = px(224.0);
|
||||
/// The width of the pushed-alert stack.
|
||||
pub const ALERT_STACK_WIDTH: Pixels = px(320.0);
|
||||
/// The accent edge of an inline alert.
|
||||
pub const ALERT_EDGE_WIDTH: Pixels = px(6.0);
|
||||
/// The default width of a combobox trigger.
|
||||
pub const COMBOBOX_WIDTH: Pixels = px(192.0);
|
||||
/// The narrowest a combobox trigger may shrink.
|
||||
pub const COMBOBOX_MIN_WIDTH: Pixels = px(96.0);
|
||||
/// The width of a code view's line-number gutter.
|
||||
pub const CODE_GUTTER_WIDTH: Pixels = px(40.0);
|
||||
/// The width of the speech waveform strip.
|
||||
pub const SPEECH_WAVEFORM_WIDTH: Pixels = px(96.0);
|
||||
/// The line-height ratio of monospace code.
|
||||
pub const CODE_LINE_HEIGHT: f32 = 1.5;
|
||||
/// The tallest an anchored popup's list may grow.
|
||||
pub const POPUP_MAX_HEIGHT: Pixels = px(320.0);
|
||||
/// The widest a tooltip may grow.
|
||||
pub const TOOLTIP_MAX_WIDTH: Pixels = px(360.0);
|
||||
/// How far a tooltip sits from the pointer.
|
||||
pub const TOOLTIP_OFFSET: Pixels = px(1.0);
|
||||
/// The caret's thickness.
|
||||
pub const CARET_WIDTH: Pixels = px(1.5);
|
||||
/// The IME preedit underline's thickness.
|
||||
pub const UNDERLINE_WIDTH: Pixels = px(1.0);
|
||||
/// How far one wheel line scrolls, as a multiple of the line height.
|
||||
pub const WHEEL_LINE_HEIGHT: f32 = 20.0;
|
||||
/// How far one keyboard arrow step moves a resize seam.
|
||||
pub const RESIZE_KEYBOARD_STEP: Pixels = px(32.0);
|
||||
/// The inset around a window's edge that starts a resize gesture.
|
||||
pub const WINDOW_RESIZE_INSET: Pixels = px(4.0);
|
||||
/// The pad macOS reserves for its traffic lights at a strip's leading edge.
|
||||
pub const TRAFFIC_LIGHT_PAD: Pixels = px(88.0);
|
||||
/// The width of a Windows caption button.
|
||||
pub const WINDOWS_CAPTION_WIDTH: Pixels = px(36.0);
|
||||
/// Windows paints its caption close-button hover red in every theme.
|
||||
pub const WINDOWS_CLOSE_HOVER: Hsla = hsla(0.986043, 0.863406, 0.488235, 1.0);
|
||||
/// The close-button hover dimmed while pressed.
|
||||
pub const WINDOWS_CLOSE_PRESSED: Hsla = hsla(0.986043, 0.863406, 0.488235, 0.8);
|
||||
/// The close glyph's color over the red hover.
|
||||
pub const WINDOWS_CLOSE_FOREGROUND: Hsla = gpui::white();
|
||||
/// The width a sidebar opens at.
|
||||
pub const SIDEBAR_DEFAULT_WIDTH: Pixels = px(240.0);
|
||||
/// The narrowest a sidebar may be dragged.
|
||||
pub const SIDEBAR_MIN_WIDTH: Pixels = px(160.0);
|
||||
/// The widest a sidebar may be dragged.
|
||||
pub const SIDEBAR_MAX_WIDTH: Pixels = px(480.0);
|
||||
/// The size a pane starts at before its group has measured the extent.
|
||||
pub const PANE_DEFAULT_SIZE: Pixels = px(200.0);
|
||||
/// The floor a pane keeps while dragging unless the caller lowers it.
|
||||
pub const PANE_MIN_SIZE: Pixels = px(48.0);
|
||||
/// The hairline a resize seam paints on a shared boundary.
|
||||
pub const HAIRLINE_WIDTH: Pixels = px(0.5);
|
||||
/// How much of the window shadow's strength survives losing focus.
|
||||
pub const INACTIVE_SHADOW_OPACITY: f32 = 0.7;
|
||||
/// The spread of the keyboard focus ring.
|
||||
pub const FOCUS_RING_SPREAD: Pixels = px(3.0);
|
||||
/// How far a pushed alert slides in on entry.
|
||||
pub const ENTER_SLIDE_DISTANCE: Pixels = px(24.0);
|
||||
/// The widest a toast may grow.
|
||||
pub const TOAST_MAX_WIDTH: Pixels = px(480.0);
|
||||
/// One revolution of the spinner.
|
||||
pub const SPINNER_PERIOD: Duration = Duration::from_millis(800);
|
||||
/// One sweep of the indeterminate progress bar.
|
||||
pub const PROGRESS_ANIMATION_PERIOD: Duration = Duration::from_millis(1500);
|
||||
/// How long an autohide scrollbar thumb stays fully visible before fading.
|
||||
pub const SCROLLBAR_AUTOHIDE_DELAY: Duration = Duration::from_millis(700);
|
||||
/// How long the autohide scrollbar's fade runs.
|
||||
pub const SCROLLBAR_FADE_DURATION: Duration = Duration::from_millis(250);
|
||||
/// How much a change wash tints the rows it covers.
|
||||
pub const WASH_ALPHA: f32 = 0.14;
|
||||
/// The stronger wash under number gutters and intra-line word changes.
|
||||
pub const WASH_ALPHA_STRONG: f32 = 0.34;
|
||||
/// The subtle wash that sets the number gutter off from the code.
|
||||
pub const WASH_ALPHA_GUTTER: f32 = 0.18;
|
||||
/// The soft wash that marks the active code row.
|
||||
pub const WASH_ALPHA_SOFT: f32 = 0.45;
|
||||
/// How far a scrolling list renders past its viewport.
|
||||
pub const CODE_OVERSCROLL_MAX: Pixels = px(400.0);
|
||||
/// The spring every control's toggle and segment animations ride.
|
||||
pub const CONTROL_SPRING: SpringConfig = SpringConfig::new(500., 35., 1.);
|
||||
/// The monospace advance estimate as a share of the text size.
|
||||
pub const MONO_ADVANCE_RATIO: f32 = 0.62;
|
||||
/// How much a pixel avatar's tint washes over its background.
|
||||
pub const PIXEL_AVATAR_TINT_ALPHA: f32 = 0.16;
|
||||
/// Pixel avatar cell lightness multipliers.
|
||||
pub const PIXEL_AVATAR_LIGHT_LIFT: f32 = 1.6;
|
||||
pub const PIXEL_AVATAR_LIGHT_CAP: f32 = 0.95;
|
||||
pub const PIXEL_AVATAR_DARK_FACTOR: f32 = 0.45;
|
||||
pub const PIXEL_AVATAR_DARK_FLOOR: f32 = 0.18;
|
||||
/// The default window material transparency, as a percent (0 opaque, 100 the lightest fill).
|
||||
pub const DEFAULT_TRANSPARENCY: u8 = 80;
|
||||
/// The light-mode floor of the material fill.
|
||||
pub const MIN_MATERIAL_FILL_LIGHT: f32 = 0.45;
|
||||
/// The dark-mode floor of the material fill.
|
||||
pub const MIN_MATERIAL_FILL_DARK: f32 = 0.15;
|
||||
/// The opacity of the grain overlay's noise.
|
||||
pub const GRAIN_ALPHA: f32 = 0.08;
|
||||
|
||||
/// Light or dark, resolved from the system appearance.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ThemeVariant {
|
||||
#[default]
|
||||
Light,
|
||||
Dark,
|
||||
}
|
||||
|
||||
impl ThemeVariant {
|
||||
fn from_appearance(appearance: WindowAppearance) -> Self {
|
||||
match appearance {
|
||||
WindowAppearance::Light | WindowAppearance::VibrantLight => Self::Light,
|
||||
WindowAppearance::Dark | WindowAppearance::VibrantDark => Self::Dark,
|
||||
}
|
||||
}
|
||||
|
||||
/// Classifies a surface by its lightness, for platforms that state no mode.
|
||||
pub fn by_lightness(background: Hsla) -> Self {
|
||||
if background.l >= 0.5 {
|
||||
Self::Light
|
||||
} else {
|
||||
Self::Dark
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A named control size class.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Size {
|
||||
XSmall,
|
||||
Small,
|
||||
/// The default.
|
||||
#[default]
|
||||
Medium,
|
||||
Large,
|
||||
}
|
||||
|
||||
/// The resolved theme, installed as the app-wide global.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Theme {
|
||||
pub variant: ThemeVariant,
|
||||
pub colors: ColorTokens,
|
||||
/// The translucent paints over the window's native material.
|
||||
pub material: MaterialTokens,
|
||||
pub ramps: Ramps,
|
||||
pub radius: Radius,
|
||||
pub elevations: Elevations,
|
||||
/// Overlay transition timing; gpui's animation primitives do the rest.
|
||||
pub motion: Motion,
|
||||
/// Overlay scrollbar geometry.
|
||||
pub scrollbar: Scrollbar,
|
||||
/// The height the window's titlebar strips draw at.
|
||||
pub titlebar_height: Pixels,
|
||||
/// The theme's root font size; rem-based sizing scales with it.
|
||||
pub root_font_size: Pixels,
|
||||
/// The monospace family, for code surfaces.
|
||||
pub mono_font: &'static str,
|
||||
/// The type ladder, resolved at the root font size.
|
||||
pub typography: Typography,
|
||||
pub sizes: SizeTable,
|
||||
pub accessibility: AccessibilityPreferences,
|
||||
/// The material a window should open with, after accessibility.
|
||||
pub window_background: WindowBackgroundAppearance,
|
||||
}
|
||||
|
||||
impl Global for Theme {}
|
||||
|
||||
impl Theme {
|
||||
/// Reads the theme global. Panics before `init`.
|
||||
pub fn global(cx: &App) -> &Self {
|
||||
cx.global::<Self>()
|
||||
}
|
||||
|
||||
fn from_resolved(resolved: ResolvedTheme) -> Self {
|
||||
Self {
|
||||
variant: resolved.variant,
|
||||
colors: resolved.colors,
|
||||
material: resolved.material,
|
||||
ramps: resolved.ramps,
|
||||
radius: resolved.radius,
|
||||
elevations: resolved.elevations,
|
||||
motion: resolved.motion,
|
||||
scrollbar: resolved.scrollbar,
|
||||
titlebar_height: resolved.titlebar_height,
|
||||
root_font_size: resolved.root_font_size,
|
||||
mono_font: resolved.mono_font,
|
||||
typography: resolved.typography,
|
||||
sizes: resolved.sizes,
|
||||
accessibility: resolved.accessibility,
|
||||
window_background: resolved.window_background,
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs the engine global, its platform watchers, and the initial resolved theme.
|
||||
pub fn init(cx: &mut App) {
|
||||
let mut engine = ThemeEngine {
|
||||
source: source::platform_source(),
|
||||
mode_override: None,
|
||||
preset: None,
|
||||
custom: None,
|
||||
};
|
||||
engine.source.install_watchers(cx.to_async());
|
||||
cx.set_global(engine);
|
||||
reapply(cx);
|
||||
}
|
||||
|
||||
/// Synchronizes the theme from the window's appearance.
|
||||
pub fn sync_from_window(window: &mut gpui::Window, cx: &mut App) {
|
||||
let window_variant = ThemeVariant::from_appearance(window.appearance());
|
||||
let theme = cx.global::<Theme>();
|
||||
let engine = cx.global::<ThemeEngine>();
|
||||
if engine.mode_override.is_none() && theme.variant != window_variant {
|
||||
reapply(cx);
|
||||
}
|
||||
}
|
||||
|
||||
/// Sizes the window's rem to the theme's root font size.
|
||||
pub fn sync_window_rem_size(window: &mut gpui::Window, cx: &App) {
|
||||
let theme = cx.global::<Theme>();
|
||||
window.set_rem_size(theme.root_font_size);
|
||||
}
|
||||
}
|
||||
|
||||
/// Corner radii components paint from; grows one class at a time.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Radius {
|
||||
/// Small controls: checkbox and radio indicators.
|
||||
pub sm: Pixels,
|
||||
pub control: Pixels,
|
||||
/// Floating layers: popovers, menus, dialogs.
|
||||
pub overlay: Pixels,
|
||||
/// Pill and circle shapes.
|
||||
pub full: Pixels,
|
||||
}
|
||||
|
||||
impl Default for Radius {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
sm: px(4.),
|
||||
control: px(6.),
|
||||
overlay: px(10.),
|
||||
full: px(9999.),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One layer of a floating panel's drop shadow.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Shadow {
|
||||
pub offset_x: Pixels,
|
||||
pub offset_y: Pixels,
|
||||
pub blur_radius: Pixels,
|
||||
pub spread_radius: Pixels,
|
||||
/// Translucent black, like every native overlay shadow.
|
||||
pub color: Hsla,
|
||||
}
|
||||
|
||||
impl Shadow {
|
||||
fn none() -> Self {
|
||||
Self {
|
||||
offset_x: px(0.),
|
||||
offset_y: px(0.),
|
||||
blur_radius: px(0.),
|
||||
spread_radius: px(0.),
|
||||
color: colors::scrim(0.),
|
||||
}
|
||||
}
|
||||
|
||||
fn black(offset_x: f32, offset_y: f32, blur_radius: f32, alpha: f32) -> Self {
|
||||
Self {
|
||||
offset_x: px(offset_x),
|
||||
offset_y: px(offset_y),
|
||||
blur_radius: px(blur_radius),
|
||||
spread_radius: px(0.),
|
||||
color: colors::scrim(alpha),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The drop shadow stack of a floating layer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Elevation {
|
||||
/// Key shadow first, ambient grounding second.
|
||||
pub layers: [Shadow; 2],
|
||||
}
|
||||
|
||||
impl Elevation {
|
||||
/// No shadow: dark floating layers separate by border.
|
||||
fn none() -> Self {
|
||||
Self {
|
||||
layers: [Shadow::none(), Shadow::none()],
|
||||
}
|
||||
}
|
||||
|
||||
fn single(key: Shadow) -> Self {
|
||||
Self {
|
||||
layers: [key, Shadow::none()],
|
||||
}
|
||||
}
|
||||
|
||||
fn layered(key: Shadow, ambient: Shadow) -> Self {
|
||||
Self {
|
||||
layers: [key, ambient],
|
||||
}
|
||||
}
|
||||
|
||||
/// How far the shadow layers paint past the element's bounds.
|
||||
pub fn bleed(self) -> Pixels {
|
||||
self.layers.iter().fold(px(0.), |bleed, layer| {
|
||||
if layer.color.a > 0. {
|
||||
bleed.max(
|
||||
layer.offset_x.abs().max(layer.offset_y.abs())
|
||||
+ layer.blur_radius
|
||||
+ layer.spread_radius,
|
||||
)
|
||||
} else {
|
||||
bleed
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The gpui shadow list an overlay panel paints with.
|
||||
pub fn shadows(self) -> Vec<gpui::BoxShadow> {
|
||||
self.layers
|
||||
.iter()
|
||||
.filter(|layer| layer.color.a > 0.)
|
||||
.map(|layer| gpui::BoxShadow {
|
||||
color: layer.color,
|
||||
offset: gpui::point(layer.offset_x, layer.offset_y),
|
||||
blur_radius: layer.blur_radius,
|
||||
spread_radius: layer.spread_radius,
|
||||
inset: false,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The drop shadows of each floating layer class.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Elevations {
|
||||
/// Popovers, menus, and pushed alerts ride above content.
|
||||
pub popover: Elevation,
|
||||
/// Modal dialogs sit higher with a wider one.
|
||||
pub dialog: Elevation,
|
||||
/// Raised plates inside controls — a selected segmented segment.
|
||||
pub control: Elevation,
|
||||
}
|
||||
|
||||
impl Elevations {
|
||||
pub(crate) fn for_variant(variant: ThemeVariant) -> Self {
|
||||
if variant == ThemeVariant::Dark {
|
||||
return Self {
|
||||
popover: Elevation::none(),
|
||||
dialog: Elevation::none(),
|
||||
control: Elevation::single(Shadow::black(0., 1., 2., 0.25)),
|
||||
};
|
||||
}
|
||||
|
||||
Self {
|
||||
popover: Elevation::layered(
|
||||
Shadow::black(0., 4., 24., 0.12),
|
||||
Shadow::black(0., 1., 1., 0.05),
|
||||
),
|
||||
dialog: Elevation::layered(
|
||||
Shadow::black(0., 8., 40., 0.14),
|
||||
Shadow::black(0., 1., 2., 0.06),
|
||||
),
|
||||
control: Elevation::single(Shadow::black(0., 1., 2., 0.1)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Overlay transition timings.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Motion {
|
||||
/// The enter transition of popovers, menus, and dialogs.
|
||||
pub overlay: Duration,
|
||||
}
|
||||
|
||||
impl Default for Motion {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
overlay: Duration::from_millis(200),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Overlay scrollbar presentation.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Scrollbar {
|
||||
/// The painted thumb's thickness.
|
||||
pub width: Pixels,
|
||||
/// Edge padding between the thumb and the viewport it floats over.
|
||||
pub inset: Pixels,
|
||||
/// The thumb never shrinks below this length, so it stays grabbable.
|
||||
pub min_thumb: Pixels,
|
||||
/// Whether the platform's scrollbars hide while idle.
|
||||
pub autohide: bool,
|
||||
}
|
||||
|
||||
impl Default for Scrollbar {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
width: px(8.),
|
||||
inset: px(2.),
|
||||
min_thumb: px(24.),
|
||||
autohide: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The control metrics for one size class.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ControlMetrics {
|
||||
/// Push buttons, toggles, and field rows.
|
||||
pub control_height: Pixels,
|
||||
/// Text fields; slightly taller than buttons, as native fields are.
|
||||
pub input_height: Pixels,
|
||||
/// Horizontal padding inside controls.
|
||||
pub padding_x: Pixels,
|
||||
/// Label text size.
|
||||
pub text_size: Pixels,
|
||||
/// Icons and on/off indicators.
|
||||
pub icon_size: Pixels,
|
||||
/// Icons inline with dense content — menu rows, badges, chevrons.
|
||||
pub dense_icon_size: Pixels,
|
||||
/// Selection indicators — checkboxes, radios, and switch knobs.
|
||||
pub indicator_size: Pixels,
|
||||
/// Avatars.
|
||||
pub avatar_size: Pixels,
|
||||
/// Dense label text.
|
||||
pub caption_size: Pixels,
|
||||
/// Tight horizontal padding inside pills, segments, fields, and icon-only buttons.
|
||||
pub dense_padding_x: Pixels,
|
||||
/// The inset between a control's edge and a raised inner plate.
|
||||
pub plate_inset: Pixels,
|
||||
/// The band height of multi-segment strips.
|
||||
pub strip_height: Pixels,
|
||||
/// The height of one menu row.
|
||||
pub menu_item_height: Pixels,
|
||||
/// Switch track height, width, and knob size.
|
||||
pub switch_height: Pixels,
|
||||
pub switch_width: Pixels,
|
||||
pub switch_knob: Pixels,
|
||||
}
|
||||
|
||||
/// The control metrics for every size class.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct SizeTable {
|
||||
pub xsmall: ControlMetrics,
|
||||
pub small: ControlMetrics,
|
||||
pub medium: ControlMetrics,
|
||||
pub large: ControlMetrics,
|
||||
}
|
||||
|
||||
impl SizeTable {
|
||||
pub fn with_root_font_size(rem_size: Pixels) -> Self {
|
||||
struct ClassFactors {
|
||||
control_height: f32,
|
||||
input_height: f32,
|
||||
padding_x: f32,
|
||||
text_size: f32,
|
||||
icon_size: f32,
|
||||
dense_icon_size: f32,
|
||||
indicator_size: f32,
|
||||
avatar_size: f32,
|
||||
caption_size: f32,
|
||||
dense_padding_x: f32,
|
||||
plate_inset: f32,
|
||||
strip_height: f32,
|
||||
menu_item_height: f32,
|
||||
switch_height: f32,
|
||||
switch_width: f32,
|
||||
switch_knob: f32,
|
||||
}
|
||||
|
||||
let xsmall = ClassFactors {
|
||||
control_height: 1.25,
|
||||
input_height: 1.25,
|
||||
padding_x: 0.25,
|
||||
text_size: 0.6875,
|
||||
icon_size: 0.625,
|
||||
dense_icon_size: 0.5,
|
||||
indicator_size: 0.625,
|
||||
avatar_size: 1.125,
|
||||
caption_size: 0.625,
|
||||
dense_padding_x: 0.25,
|
||||
plate_inset: 0.0,
|
||||
strip_height: 1.25,
|
||||
menu_item_height: 1.25,
|
||||
switch_height: 0.875,
|
||||
switch_width: 1.5,
|
||||
switch_knob: 0.5,
|
||||
};
|
||||
|
||||
let small = ClassFactors {
|
||||
control_height: 1.75,
|
||||
input_height: 1.75,
|
||||
padding_x: 0.5,
|
||||
text_size: 0.75,
|
||||
icon_size: 0.875,
|
||||
dense_icon_size: 0.75,
|
||||
indicator_size: 0.875,
|
||||
avatar_size: 1.5,
|
||||
caption_size: 0.75,
|
||||
dense_padding_x: 0.5,
|
||||
plate_inset: 0.125,
|
||||
strip_height: 1.75,
|
||||
menu_item_height: 1.75,
|
||||
switch_height: 1.125,
|
||||
switch_width: 2.0,
|
||||
switch_knob: 0.75,
|
||||
};
|
||||
|
||||
let medium = ClassFactors {
|
||||
control_height: 2.0,
|
||||
input_height: 2.0,
|
||||
padding_x: 0.75,
|
||||
text_size: 0.875,
|
||||
icon_size: 1.0,
|
||||
dense_icon_size: 0.75,
|
||||
indicator_size: 1.0,
|
||||
avatar_size: 2.0,
|
||||
caption_size: 0.75,
|
||||
dense_padding_x: 0.5,
|
||||
plate_inset: 0.125,
|
||||
strip_height: 2.0,
|
||||
menu_item_height: 2.0,
|
||||
switch_height: 1.25,
|
||||
switch_width: 2.25,
|
||||
switch_knob: 0.875,
|
||||
};
|
||||
|
||||
let large = ClassFactors {
|
||||
control_height: 2.5,
|
||||
input_height: 2.5,
|
||||
padding_x: 1.0,
|
||||
text_size: 1.0,
|
||||
icon_size: 1.25,
|
||||
dense_icon_size: 0.9375,
|
||||
indicator_size: 1.25,
|
||||
avatar_size: 2.5,
|
||||
caption_size: 0.875,
|
||||
dense_padding_x: 0.75,
|
||||
plate_inset: 0.1875,
|
||||
strip_height: 2.5,
|
||||
menu_item_height: 2.25,
|
||||
switch_height: 1.5,
|
||||
switch_width: 2.75,
|
||||
switch_knob: 1.125,
|
||||
};
|
||||
|
||||
let metrics = |f: &ClassFactors| ControlMetrics {
|
||||
control_height: rem_size * f.control_height,
|
||||
input_height: rem_size * f.input_height,
|
||||
padding_x: rem_size * f.padding_x,
|
||||
text_size: rem_size * f.text_size,
|
||||
icon_size: rem_size * f.icon_size,
|
||||
dense_icon_size: rem_size * f.dense_icon_size,
|
||||
indicator_size: rem_size * f.indicator_size,
|
||||
avatar_size: rem_size * f.avatar_size,
|
||||
caption_size: rem_size * f.caption_size,
|
||||
dense_padding_x: rem_size * f.dense_padding_x,
|
||||
plate_inset: rem_size * f.plate_inset,
|
||||
strip_height: rem_size * f.strip_height,
|
||||
menu_item_height: rem_size * f.menu_item_height,
|
||||
switch_height: rem_size * f.switch_height,
|
||||
switch_width: rem_size * f.switch_width,
|
||||
switch_knob: rem_size * f.switch_knob,
|
||||
};
|
||||
|
||||
Self {
|
||||
xsmall: metrics(&xsmall),
|
||||
small: metrics(&small),
|
||||
medium: metrics(&medium),
|
||||
large: metrics(&large),
|
||||
}
|
||||
}
|
||||
|
||||
/// The metrics for `size`.
|
||||
pub fn resolve(&self, size: Size) -> ControlMetrics {
|
||||
match size {
|
||||
Size::XSmall => self.xsmall,
|
||||
Size::Small => self.small,
|
||||
Size::Medium => self.medium,
|
||||
Size::Large => self.large,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// User customizations layered over the resolved theme.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct CustomTheme {
|
||||
pub root_font_size: Option<Pixels>,
|
||||
pub sm_radius: Option<Pixels>,
|
||||
pub control_radius: Option<Pixels>,
|
||||
pub overlay_radius: Option<Pixels>,
|
||||
pub popover_elevation: Option<Elevation>,
|
||||
pub dialog_elevation: Option<Elevation>,
|
||||
pub control_elevation: Option<Elevation>,
|
||||
/// Window material transparency as a percent (0 opaque, 100 pure blur).
|
||||
///
|
||||
/// Note: windows platform is not supported
|
||||
pub transparency: Option<u8>,
|
||||
}
|
||||
|
||||
/// The engine's knobs and its platform source.
|
||||
struct ThemeEngine {
|
||||
source: Box<dyn source::ThemeSource>,
|
||||
mode_override: Option<ThemeVariant>,
|
||||
preset: Option<(&'static str, ThemeDefinition)>,
|
||||
custom: Option<CustomTheme>,
|
||||
}
|
||||
|
||||
impl Global for ThemeEngine {}
|
||||
|
||||
/// Reads the resolved theme global from any app context.
|
||||
pub trait ActiveTheme {
|
||||
fn theme(&self) -> &Theme;
|
||||
}
|
||||
|
||||
impl ActiveTheme for App {
|
||||
fn theme(&self) -> &Theme {
|
||||
Theme::global(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reapplies the theme to the application.
|
||||
pub(crate) fn reapply(cx: &mut App) {
|
||||
let (preset, mode_override, custom, system) = {
|
||||
let engine = cx.global::<ThemeEngine>();
|
||||
let system_appearance = ThemeVariant::from_appearance(cx.window_appearance());
|
||||
let preset = engine.preset.as_ref().map(|(_, def)| def.clone());
|
||||
let mode_override = engine.mode_override;
|
||||
let custom = engine.custom;
|
||||
let variant = mode_override
|
||||
.or(preset.as_ref().and_then(|def| def.mode()))
|
||||
.unwrap_or(system_appearance);
|
||||
(
|
||||
preset,
|
||||
mode_override,
|
||||
custom,
|
||||
engine.source.snapshot(variant),
|
||||
)
|
||||
};
|
||||
|
||||
let resolved = resolve::resolve(&system, preset.as_ref(), mode_override, custom);
|
||||
|
||||
cx.set_reduce_motion(resolved.accessibility.reduce_motion);
|
||||
cx.set_global(Theme::from_resolved(resolved));
|
||||
cx.refresh_windows();
|
||||
}
|
||||
|
||||
/// Forces a variant, independent of the OS. `None` follows the system.
|
||||
pub fn set_mode_override(variant: Option<ThemeVariant>, cx: &mut App) {
|
||||
let engine = cx.global_mut::<ThemeEngine>();
|
||||
engine.mode_override = variant;
|
||||
reapply(cx);
|
||||
}
|
||||
|
||||
/// Installs a built-in preset, or `None` to follow the system again.
|
||||
pub fn set_preset(name: Option<&str>, cx: &mut App) -> anyhow::Result<()> {
|
||||
let preset = name
|
||||
.map(|name| {
|
||||
presets::builtin(name).ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"unknown preset: {name}; available: {}",
|
||||
presets::preset_names().collect::<Vec<_>>().join(", ")
|
||||
)
|
||||
})
|
||||
})
|
||||
.transpose()?;
|
||||
let engine = cx.global_mut::<ThemeEngine>();
|
||||
engine.preset = preset;
|
||||
reapply(cx);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Installs the user's custom theme, or `None` to follow the current scheme.
|
||||
pub fn set_custom_theme(custom: Option<CustomTheme>, cx: &mut App) {
|
||||
let engine = cx.global_mut::<ThemeEngine>();
|
||||
engine.custom = custom;
|
||||
reapply(cx);
|
||||
}
|
||||
|
||||
/// The variant the mode override forces, if any.
|
||||
pub fn mode_override(cx: &App) -> Option<ThemeVariant> {
|
||||
let engine = cx.global::<ThemeEngine>();
|
||||
engine.mode_override
|
||||
}
|
||||
|
||||
/// The installed custom theme, if any.
|
||||
pub fn custom_theme(cx: &App) -> Option<CustomTheme> {
|
||||
let engine = cx.global::<ThemeEngine>();
|
||||
engine.custom
|
||||
}
|
||||
|
||||
/// The active preset name, if one is installed.
|
||||
pub fn active_preset(cx: &App) -> Option<&'static str> {
|
||||
let engine = cx.global::<ThemeEngine>();
|
||||
engine.preset.as_ref().map(|(name, _)| *name)
|
||||
}
|
||||
|
||||
/// Clears the mode override and preset; the theme follows the system again.
|
||||
pub fn follow_system(cx: &mut App) {
|
||||
let engine = cx.global_mut::<ThemeEngine>();
|
||||
engine.mode_override = None;
|
||||
engine.preset = None;
|
||||
reapply(cx);
|
||||
}
|
||||
|
||||
/// Which adapter produced the current system snapshot.
|
||||
pub fn detected_source(cx: &App) -> &'static str {
|
||||
let engine = cx.global::<ThemeEngine>();
|
||||
engine.source.label()
|
||||
}
|
||||