use gpui::{
Anchor, Context, Div, ElementId, Entity, FocusHandle, FontWeight, KeyDownEvent, MouseButton,
MouseDownEvent, PathBuilder, ScrollHandle, SharedString, Window, anchored, canvas, deferred,
div, point, prelude::*, px,
};
use std::rc::Rc;
use crate::easing::{ease_out_cubic, lerp_f32};
use crate::keyboard::{self, Dismiss, Key, Orientation};
use crate::lighting;
use crate::menu::VIEWPORT_MARGIN;
use crate::overlay::Hint;
use crate::palette::Palette;
use crate::scroll::{SCROLLBAR_THICKNESS, ScrollAxis, ScrollDrag, THUMB_THICKNESS};
use crate::state::{ComboId, ControlHost, ControlState, MOVE, SWITCH_SLIDE, Tag, TrackAxis};
use crate::text_input::TextInput;
pub struct WidgetContext<'v, 'c, 'app, V: ControlHost + 'v> {
pub palette: Palette,
pub view: &'v V,
pub cx: &'c mut Context<'app, V>,
}
impl<'v, 'c, 'app, V: ControlHost> WidgetContext<'v, 'c, 'app, V> {
pub fn new(palette: Palette, view: &'v V, cx: &'c mut Context<'app, V>) -> Self {
Self { palette, view, cx }
}
pub fn state(&self) -> &'v ControlState {
self.view.control_state()
}
pub fn reborrow(&mut self) -> WidgetContext<'v, '_, 'app, V> {
WidgetContext {
palette: self.palette,
view: self.view,
cx: &mut *self.cx,
}
}
}
pub const CONTROL_HEIGHT: f32 = 30.0;
pub const CONTROL_RADIUS: f32 = 6.0;
pub const DISABLED_OPACITY: f32 = 0.5;
const PRESS_SHADE_DELTA: f32 = -0.06;
const CAPTION_TEXT_SIZE: f32 = 12.0;
const BUTTON_TEXT_SIZE: f32 = 12.5;
const BUTTON_PADDING_H: f32 = 12.0;
const SWITCH_TRACK_H: f32 = 26.0;
const SWITCH_TRACK_RADIUS: f32 = 13.0;
const SWITCH_LABEL_TEXT_SIZE: f32 = 12.5;
const SWITCH_TRACK_DISABLED: f32 = 0.45;
const SWITCH_TRACK_OPACITY_DARK: f32 = 0.5;
const SWITCH_TRACK_OPACITY_LIGHT: f32 = 0.58;
const STEP_BUTTON_SIZE: f32 = 22.0;
const STEP_BUTTON_RADIUS: f32 = 3.0;
const STEP_BUTTON_TEXT_SIZE: f32 = 13.0;
const SPINBOX_WIDTH: f32 = 118.0;
const SPINBOX_PAD_H: f32 = 4.0;
const SPINBOX_TEXT_SIZE: f32 = 12.0;
const FOCUSED_GLOW_OPACITY: f32 = 0.35;
const FOCUSED_GLOW_BLUR: f32 = 3.0;
const TEXT_FIELD_PAD_H: f32 = 9.0;
const TEXT_AREA_MIN_H: f32 = 40.0;
const TEXT_AREA_LINE_HEIGHT: f32 = 17.0;
const TEXT_AREA_PAD_H: f32 = 10.0;
const TEXT_AREA_PAD_V: f32 = 8.0;
const COMBO_PAD_L: f32 = 10.0;
const COMBO_PAD_R: f32 = 28.0;
const COMBO_TEXT_SIZE: f32 = 12.5;
const COMBO_ROW_PAD_H: f32 = 9.0;
const COMBO_BODY_LIT: f32 = 0.05;
const COMBO_ROW_SELECTED_LIT: f32 = 0.08;
const CHEVRON_STROKE_W: f32 = 1.5;
const CHEVRON_CHIP_INSET_R: f32 = 5.0;
const CHEVRON_CHIP_SIZE: f32 = 18.0;
const CHEVRON_CHIP_LIT: f32 = 0.12;
const SPIN_BUTTON_DISABLED: f32 = 0.45;
pub fn caption(palette: Palette, text: &str) -> impl IntoElement {
div()
.flex_none()
.text_size(px(CAPTION_TEXT_SIZE))
.font_weight(FontWeight::MEDIUM)
.text_color(palette.text_secondary)
.whitespace_nowrap()
.child(SharedString::from(text))
}
pub fn fading_text(id: &'static str, text: impl Into<SharedString>, state: &ControlState) -> Div {
use std::hash::{Hash, Hasher};
let text = text.into();
let mut hasher = std::collections::hash_map::DefaultHasher::new();
text.hash(&mut hasher);
let arrived = ease_out_cubic(state.transition(id, hasher.finish(), SWITCH_SLIDE));
div().opacity(arrived).child(text)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ButtonVariant {
Soft,
Primary,
Danger,
}
impl ButtonVariant {
fn colors(self, palette: Palette) -> (gpui::Rgba, gpui::Rgba, gpui::Rgba) {
match self {
ButtonVariant::Primary => (
palette.primary_fill,
palette.primary_fill_hover,
palette.primary_label,
),
ButtonVariant::Danger => (
palette.danger_fill,
palette.danger_fill_hover,
palette.danger_label,
),
ButtonVariant::Soft => (
palette.soft_fill,
palette.soft_fill_hover,
palette.soft_label,
),
}
}
}
pub fn button<V: ControlHost>(
id: impl Into<ElementId>,
text: &str,
variant: ButtonVariant,
enabled: bool,
palette: Palette,
cx: &mut Context<V>,
on_click: impl Fn(&mut V, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
build_button(
id.into(),
text,
variant,
enabled,
None,
palette,
cx,
Rc::new(on_click),
)
}
#[allow(clippy::too_many_arguments)]
pub fn button_focused<V: ControlHost>(
id: impl Into<ElementId>,
text: &str,
variant: ButtonVariant,
enabled: bool,
focus: &FocusHandle,
palette: Palette,
cx: &mut Context<V>,
on_click: impl Fn(&mut V, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
build_button(
id.into(),
text,
variant,
enabled,
Some(focus),
palette,
cx,
Rc::new(on_click),
)
}
type Press<V> = Rc<dyn Fn(&mut V, &mut Window, &mut Context<V>)>;
#[allow(clippy::too_many_arguments)]
fn build_button<V: ControlHost>(
id: ElementId,
text: &str,
variant: ButtonVariant,
enabled: bool,
focus: Option<&FocusHandle>,
palette: Palette,
cx: &mut Context<V>,
on_click: Press<V>,
) -> impl IntoElement {
let dark = palette.is_dark;
let (fill, fill_hover, label_color) = variant.colors(palette);
let label: SharedString = SharedString::from(text);
let pressed = on_click.clone();
let activate = cx.listener(move |this, event: &KeyDownEvent, window, cx| {
if keyboard::key(event) == Some(Key::Activate) {
cx.stop_propagation();
pressed(this, window, cx);
cx.notify();
}
});
let ring: gpui::AnyElement = match focus {
Some(focus) => keyboard::ring_for(focus, CONTROL_RADIUS, palette)
.on_key_down(activate)
.into_any_element(),
None => keyboard::ring("ring", CONTROL_RADIUS, palette)
.on_key_down(activate)
.into_any_element(),
};
div()
.id(id)
.h(px(CONTROL_HEIGHT))
.w_full()
.px(px(BUTTON_PADDING_H))
.flex()
.items_center()
.justify_center()
.relative()
.rounded(px(CONTROL_RADIUS))
.bg(lighting::lit(fill, 0.08))
.border_1()
.border_color(lighting::rim(fill, dark))
.shadow(lighting::raised(dark))
.text_size(px(BUTTON_TEXT_SIZE))
.font_weight(FontWeight::MEDIUM)
.text_color(label_color)
.whitespace_nowrap()
.overflow_hidden()
.when(!enabled, |el| el.opacity(DISABLED_OPACITY))
.when(enabled, move |el| {
el.cursor_pointer()
.hover(move |style| style.bg(lighting::lit(fill_hover, 0.1)))
.active(move |style| {
style.bg(lighting::lit(lighting::shade(fill, PRESS_SHADE_DELTA), 0.0))
})
.on_click(cx.listener(move |this, _event, window, cx| {
on_click(this, window, cx);
}))
})
.child(label)
.when(enabled, |el| el.child(ring))
}
#[allow(clippy::too_many_arguments)]
pub fn switch<V: ControlHost>(
id: impl Into<ElementId>,
checked: bool,
label: Option<&str>,
enabled: bool,
ctx: WidgetContext<'_, '_, '_, V>,
on_toggle: impl Fn(&mut V, bool, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
const KNOB: f32 = 20.0;
const TRACK_W: f32 = 46.0;
const PAD: f32 = 3.0;
let left_off = PAD;
let left_on = TRACK_W - KNOB - PAD;
let palette = ctx.palette;
let id: ElementId = id.into();
let track_off = palette.field_border;
let track_on = palette.accent;
let track_opacity = if !enabled {
SWITCH_TRACK_DISABLED
} else if checked {
if palette.is_dark {
SWITCH_TRACK_OPACITY_DARK
} else {
SWITCH_TRACK_OPACITY_LIGHT
}
} else {
1.0
};
let on = ctx.state().blend(&id, checked, SWITCH_SLIDE);
let cx: &mut Context<V> = &mut *ctx.cx;
let track_color = crate::color::lerp(track_off, track_on, on);
let left = lerp_f32(left_off, left_on, on);
let label: Option<SharedString> = label.map(std::convert::Into::into);
let on_toggle = Rc::new(on_toggle);
let toggled = on_toggle.clone();
div()
.id(id)
.flex()
.items_center()
.gap(px(7.0))
.flex_none()
.when(enabled, |el| {
el.cursor_pointer()
.on_click(cx.listener(move |this, _event, window, cx| {
on_toggle(this, !checked, window, cx);
cx.notify();
}))
})
.child(
div()
.w(px(TRACK_W))
.h(px(SWITCH_TRACK_H))
.flex_none()
.relative()
.rounded(px(SWITCH_TRACK_RADIUS))
.bg(crate::color::with_alpha(track_color, track_opacity))
.child(
div()
.absolute()
.top(px(PAD))
.left(px(left))
.w(px(KNOB))
.h(px(KNOB))
.rounded_full()
.bg(palette.field_surface)
.border_1()
.border_color(palette.field_border_strong),
)
.when(enabled, |el| {
el.child(
keyboard::ring("ring", SWITCH_TRACK_RADIUS, palette).on_key_down(
ctx.cx
.listener(move |this, event: &KeyDownEvent, window, cx| {
if keyboard::key(event) == Some(Key::Activate) {
cx.stop_propagation();
toggled(this, !checked, window, cx);
cx.notify();
}
}),
),
)
}),
)
.children(label.map(|label| {
div()
.text_size(px(SWITCH_LABEL_TEXT_SIZE))
.text_color(palette.text_primary)
.whitespace_nowrap()
.when(!enabled, |el| el.opacity(DISABLED_OPACITY))
.child(label)
}))
}
#[allow(clippy::too_many_arguments)]
pub fn spinbox<V: ControlHost>(
id_prefix: &'static str,
value: i32,
min: i32,
max: i32,
enabled: bool,
edit_input: &Entity<TextInput>,
palette: Palette,
cx: &mut Context<V>,
on_change: impl Fn(&mut V, i32, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
edit_input.update(cx, |input, _cx| {
input.restyle(palette);
input.disabled = !enabled;
});
let edit = edit_input.clone();
let commit: Commit<V> = Rc::new(move |this, value, window, cx| {
edit.update(cx, |input, cx| {
if value == min || value == max {
window.focus(&input.focus_handle, cx);
}
input.set_text(&value.to_string(), cx);
});
on_change(this, value, window, cx);
});
let dec = commit.clone();
let key_step = commit.clone();
let typed = commit.clone();
let typed_from = edit_input.clone();
let inc = commit;
type Step<V> = Rc<dyn Fn(&mut V, &mut Window, &mut Context<V>) + 'static>;
let step_button = |id: ElementId,
glyph: &'static str,
active: bool,
cx: &mut Context<V>,
handler: Step<V>| {
div()
.id(id)
.w(px(STEP_BUTTON_SIZE))
.h(px(STEP_BUTTON_SIZE))
.rounded(px(STEP_BUTTON_RADIUS))
.flex()
.items_center()
.justify_center()
.text_size(px(STEP_BUTTON_TEXT_SIZE))
.text_color(palette.text_secondary)
.when(!enabled, |el| el.opacity(SPIN_BUTTON_DISABLED))
.when(enabled && active, move |el| {
let key_handler = handler.clone();
el.relative()
.cursor_pointer()
.hover(move |style| style.bg(palette.soft_fill))
.active(move |style| style.bg(palette.soft_fill_hover))
.on_click(cx.listener(move |this, _event, window, cx| {
handler(this, window, cx);
}))
.child(
keyboard::ring("ring", STEP_BUTTON_RADIUS, palette).on_key_down(
cx.listener(move |this, event: &KeyDownEvent, window, cx| {
if keyboard::key(event) == Some(Key::Activate) {
cx.stop_propagation();
key_handler(this, window, cx);
cx.notify();
}
}),
),
)
})
.child(glyph)
};
div()
.w(px(SPINBOX_WIDTH))
.h(px(CONTROL_HEIGHT))
.flex_none()
.rounded(px(CONTROL_RADIUS))
.bg(palette.field_surface)
.border_1()
.border_color(palette.field_border)
.shadow(lighting::recessed(palette.is_dark))
.when(!enabled, |el| el.opacity(DISABLED_OPACITY))
.flex()
.items_center()
.justify_between()
.px(px(SPINBOX_PAD_H))
.when(enabled, |el| {
let step_down = key_step.clone();
el.on_action(
cx.listener(move |this, _: &crate::text_input::Up, window, cx| {
if value < max {
key_step(this, (value + 1).min(max), window, cx);
cx.notify();
}
}),
)
.on_action(
cx.listener(move |this, _: &crate::text_input::Down, window, cx| {
if value > min {
step_down(this, (value - 1).max(min), window, cx);
cx.notify();
}
}),
)
.on_action(cx.listener(
move |this, _: &crate::text_input::Enter, window, cx| {
let text = typed_from.read(cx).shared_text();
match text.trim().parse::<i32>() {
Ok(entered) => typed(this, entered.clamp(min, max), window, cx),
Err(_) => typed_from.update(cx, |input, cx| {
input.set_text(&value.to_string(), cx);
}),
}
cx.notify();
},
))
})
.child(step_button(
Tag::new((id_prefix, "spinbox-dec")).element_id(),
"\u{2212}",
value > min,
cx,
Rc::new(move |this, window, cx| {
dec(this, (value - 1).max(min), window, cx);
}),
))
.child(
div()
.flex_1()
.px(px(SPINBOX_PAD_H))
.text_size(px(SPINBOX_TEXT_SIZE))
.text_color(palette.text_primary)
.child(edit_input.clone()),
)
.child(step_button(
Tag::new((id_prefix, "spinbox-inc")).element_id(),
"+",
value < max,
cx,
Rc::new(move |this, window, cx| {
inc(this, (value + 1).min(max), window, cx);
}),
))
}
type Commit<V> = Rc<dyn Fn(&mut V, i32, &mut Window, &mut Context<V>)>;
fn well_shadows(palette: Palette, focused: bool) -> Vec<gpui::BoxShadow> {
let mut shadows = lighting::recessed(palette.is_dark);
if focused {
shadows.push(lighting::glow(
palette.accent,
FOCUSED_GLOW_OPACITY,
FOCUSED_GLOW_BLUR,
));
}
shadows
}
pub fn text_field<V: ControlHost>(
input: &Entity<TextInput>,
palette: Palette,
window: &Window,
cx: &mut Context<V>,
) -> impl IntoElement {
input.update(cx, |input, _cx| {
input.restyle(palette);
});
let focused = input.read(cx).focus_handle.is_focused(window);
let click_input = input.clone();
div()
.h(px(CONTROL_HEIGHT))
.w_full()
.px(px(TEXT_FIELD_PAD_H))
.flex()
.items_center()
.rounded(px(CONTROL_RADIUS))
.bg(palette.field_surface)
.border_1()
.border_color(if focused {
palette.accent
} else {
palette.field_border
})
.shadow(well_shadows(palette, focused))
.overflow_hidden()
.on_mouse_down(
MouseButton::Left,
cx.listener(move |_host, event: &MouseDownEvent, window, cx| {
click_input.update(cx, |input, cx| {
input.handle_chrome_click(event.position, window, cx)
});
}),
)
.child(input.clone())
}
pub fn text_area<V: ControlHost>(
input: &Entity<TextInput>,
height: Option<f32>,
enabled: bool,
palette: Palette,
window: &Window,
cx: &mut Context<V>,
) -> impl IntoElement {
input.update(cx, |input, _cx| {
input.restyle(palette);
input.disabled = !enabled;
});
let focused = input.read(cx).focus_handle.is_focused(window);
let click_input = input.clone();
div()
.id(("text-area", input.entity_id()))
.when_some(height, |el, h| el.h(px(h)))
.when(height.is_none(), |el| {
el.flex_1().min_h(px(TEXT_AREA_MIN_H))
})
.line_height(px(TEXT_AREA_LINE_HEIGHT))
.w_full()
.px(px(TEXT_AREA_PAD_H))
.py(px(TEXT_AREA_PAD_V))
.rounded(px(CONTROL_RADIUS))
.bg(palette.area_surface)
.border_1()
.border_color(if focused {
palette.accent
} else {
palette.area_border
})
.shadow(well_shadows(palette, focused))
.when(!enabled, |el| el.opacity(DISABLED_OPACITY))
.overflow_y_scroll()
.restrict_scroll_to_axis()
.when(enabled, |el| {
el.on_mouse_down(
MouseButton::Left,
cx.listener(move |_host, event: &MouseDownEvent, window, cx| {
click_input.update(cx, |input, cx| {
input.handle_chrome_click(event.position, window, cx)
});
}),
)
})
.child(input.clone())
}
const COMBO_ROW_HEIGHT: f32 = 28.0;
const COMBO_ROW_GAP: f32 = 2.0;
const COMBO_LIST_PADDING: f32 = 5.0;
const COMBO_LIST_BORDER: f32 = 1.0;
const COMBO_LIST_MAX_HEIGHT: f32 = 240.0;
#[derive(Clone, Copy, Debug, PartialEq)]
struct ComboPlacement {
top: f32,
scroll: f32,
}
fn combo_placement(chosen: usize, count: usize) -> ComboPlacement {
let pitch = COMBO_ROW_HEIGHT + COMBO_ROW_GAP;
let row_top = COMBO_LIST_PADDING + chosen as f32 * pitch;
let row_bottom = row_top + COMBO_ROW_HEIGHT;
let content = 2.0 * COMBO_LIST_PADDING + (count as f32 * pitch - COMBO_ROW_GAP).max(0.0);
let furthest = (content - COMBO_LIST_MAX_HEIGHT).max(0.0);
let scroll = (row_bottom - COMBO_LIST_MAX_HEIGHT).clamp(0.0, furthest);
let top = (CONTROL_HEIGHT - COMBO_ROW_HEIGHT) / 2.0 - COMBO_LIST_BORDER - row_top + scroll;
ComboPlacement { top, scroll }
}
fn open_list(state: &mut ControlState, id: ComboId, chosen: usize, count: usize) {
let Some(last) = count.checked_sub(1) else {
return;
};
let chosen = chosen.min(last);
state.open_combo(id, chosen);
let placement = combo_placement(chosen, count);
state
.scroll(id)
.set_offset(point(px(0.0), px(-placement.scroll)));
}
#[allow(clippy::too_many_arguments)]
pub fn combo<V: ControlHost>(
id: ComboId,
current_index: usize,
options: &[String],
width: Option<f32>,
ctx: WidgetContext<'_, '_, '_, V>,
on_select: impl Fn(&mut V, usize, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
let palette = ctx.palette;
let view = ctx.view;
let cx: &mut Context<V> = &mut *ctx.cx;
let dark = palette.is_dark;
let state = view.control_state();
let is_open = state.is_combo_open(id);
let list_scroll = state.scroll(id);
let fade = state.combo_fade(id);
let showing = fade.is_some();
let reveal = fade.map_or(1.0, |(reveal, _)| reveal);
let drift = -4.0 * (1.0 - reveal);
let display: SharedString = options
.get(current_index)
.map(|option| SharedString::from(option.as_str()))
.unwrap_or_default();
let count = options.len();
let placement = combo_placement(state.combo_opened_on(id).unwrap_or(current_index), count);
let button = state.track(id);
let weak = cx.entity().downgrade();
let keyboard_at = if is_open {
state.combo_highlight_or(current_index)
} else {
current_index
};
let on_select = Rc::new(on_select);
let key_select = on_select.clone();
let body_fill = if dark {
palette.soft_fill
} else {
palette.field_surface
};
let chip_fill = palette.control_fill;
let chevron_color: gpui::Hsla = crate::color::to_hsla(palette.control_label);
div()
.id(Tag::new((id, "combo")).element_id())
.relative()
.when_some(width, |el, w| el.w(px(w)).flex_none())
.when(width.is_none(), |el| el.w_full())
.child(
canvas(
move |bounds, _window, cx| {
if let Some(host) = weak.upgrade() {
host.update(cx, |host, _cx| {
host.control_state_mut().record_track(id, bounds);
});
}
},
|_bounds, _state, _window, _cx| {},
)
.absolute()
.size_full(),
)
.child(
div()
.id("toggle")
.h(px(CONTROL_HEIGHT))
.w_full()
.pl(px(COMBO_PAD_L))
.pr(px(COMBO_PAD_R))
.flex()
.items_center()
.rounded(px(CONTROL_RADIUS))
.bg(lighting::lit(body_fill, COMBO_BODY_LIT))
.border_1()
.border_color(if is_open {
palette.accent
} else {
lighting::rim(body_fill, dark)
})
.shadow(lighting::raised(dark))
.cursor_pointer()
.text_size(px(12.5))
.text_color(palette.text_primary)
.whitespace_nowrap()
.overflow_hidden()
.hover(move |style| style.bg(lighting::lit(body_fill, 0.09)))
.relative()
.child(
keyboard::ring("ring", CONTROL_RADIUS, palette)
.on_action(cx.listener(move |this, _: &Dismiss, _window, cx| {
if !this.control_state().is_combo_open(id) {
cx.propagate();
return;
}
this.control_state_mut().close_combo();
cx.notify();
}))
.on_key_down(cx.listener(move |this, event: &KeyDownEvent, window, cx| {
let Some(key) = keyboard::key(event) else {
return;
};
if !this.control_state().is_combo_open(id) {
if matches!(key, Key::Activate | Key::Down) {
cx.stop_propagation();
open_list(this.control_state_mut(), id, current_index, count);
cx.notify();
}
return;
}
cx.stop_propagation();
match key {
Key::Dismiss => {
this.control_state_mut().close_combo();
}
Key::Activate => {
let chosen =
this.control_state().combo_highlight_or(current_index);
this.control_state_mut().close_combo();
if chosen < count {
key_select(this, chosen, window, cx);
}
}
key => {
let at = this.control_state().combo_highlight_or(current_index);
if let Some(moved) =
keyboard::step(key, Orientation::Vertical, at, count)
{
this.control_state_mut().highlight_combo(moved);
this.control_state().scroll(id).scroll_to_item(moved);
}
}
}
cx.notify();
})),
)
.child(display)
.child(chevron_chip(chip_fill, chevron_color, dark))
.on_click(cx.listener(move |this, _event, _window, cx| {
let state = this.control_state_mut();
if state.take_combo_dismissal() == Some(id) {
cx.notify();
return;
}
if state.is_combo_open(id) {
state.close_combo();
} else {
open_list(state, id, current_index, count);
}
cx.notify();
})),
)
.when_some(button.filter(|_| showing), |el, button| {
el.child(
deferred(
anchored()
.position(point(button.origin.x, button.origin.y + px(placement.top)))
.anchor(Anchor::TopLeft)
.offset(point(px(0.0), px(drift)))
.snap_to_window_with_margin(px(VIEWPORT_MARGIN))
.child(
div()
.id("popup")
.w(button.size.width)
.opacity(reveal)
.rounded(px(CONTROL_RADIUS + 1.0))
.bg(body_fill)
.border_1()
.border_color(lighting::rim(body_fill, dark))
.shadow(lighting::panel(dark))
.overflow_hidden()
.relative()
.when(is_open, |el| {
el.occlude().on_mouse_down_out(cx.listener(
move |this, _event, _window, cx| {
let state = this.control_state_mut();
state.combo_pressed_outside(id);
cx.notify();
},
))
})
.child(
div()
.id("popup-list")
.max_h(px(COMBO_LIST_MAX_HEIGHT))
.p(px(COMBO_LIST_PADDING))
.flex()
.flex_col()
.gap(px(COMBO_ROW_GAP))
.overflow_y_scroll()
.restrict_scroll_to_axis()
.track_scroll(&list_scroll)
.children(options.iter().enumerate().map(
|(index, option)| {
let on_select = on_select.clone();
let highlighted = index == keyboard_at;
div()
.id(("option", index))
.h(px(COMBO_ROW_HEIGHT))
.flex_none()
.w_full()
.px(px(COMBO_ROW_PAD_H))
.flex()
.items_center()
.rounded(px(CONTROL_RADIUS - 1.0))
.text_size(px(COMBO_TEXT_SIZE))
.text_color(if highlighted {
palette.control_label
} else {
palette.text_primary
})
.when(highlighted, |elem| {
elem.bg(lighting::lit(
palette.control_fill,
COMBO_ROW_SELECTED_LIT,
))
})
.when(!highlighted, |elem| {
elem.hover(move |style| {
style.bg(palette.row_hover)
})
})
.overflow_hidden()
.child(SharedString::from(option))
.when(is_open, |elem| {
let on_select = on_select.clone();
elem.cursor_pointer().on_click(cx.listener(
move |this, _event, window, cx| {
this.control_state_mut()
.close_combo();
on_select(this, index, window, cx);
cx.notify();
},
))
})
},
)),
)
.children(crate::scroll::scroll_fades(
state,
id,
&list_scroll,
crate::scroll::ScrollAxis::Vertical,
body_fill,
body_fill,
)),
),
)
.priority(160),
)
})
}
fn chevron_chip(fill: gpui::Rgba, chevron: gpui::Hsla, dark: bool) -> impl IntoElement {
div()
.absolute()
.right(px(CHEVRON_CHIP_INSET_R))
.top(px((CONTROL_HEIGHT - 2.0 - CHEVRON_CHIP_SIZE) / 2.0))
.w(px(CHEVRON_CHIP_SIZE))
.h(px(CHEVRON_CHIP_SIZE))
.rounded(px(CONTROL_RADIUS - 2.0))
.bg(lighting::lit(fill, CHEVRON_CHIP_LIT))
.shadow(lighting::raised(dark))
.child(
canvas(
|_bounds, _window, _cx| {},
move |bounds, _state, window, _cx| {
let origin = bounds.origin;
let mut builder = PathBuilder::stroke(px(CHEVRON_STROKE_W));
builder.move_to(point(origin.x + px(5.5), origin.y + px(7.5)));
builder.line_to(point(origin.x + px(9.0), origin.y + px(4.0)));
builder.line_to(point(origin.x + px(12.5), origin.y + px(7.5)));
builder.move_to(point(origin.x + px(5.5), origin.y + px(10.5)));
builder.line_to(point(origin.x + px(9.0), origin.y + px(14.0)));
builder.line_to(point(origin.x + px(12.5), origin.y + px(10.5)));
if let Ok(path) = builder.build() {
window.paint_path(path, chevron);
}
},
)
.size_full(),
)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum SliderTrack {
#[default]
Continuous,
Stepped { stops: u32 },
}
impl SliderTrack {
pub fn stops(self) -> Option<u32> {
match self {
SliderTrack::Stepped { stops } if stops >= 2 => Some(stops),
_ => None,
}
}
}
pub fn slider<V: ControlHost>(
id: ComboId,
ratio: f32,
track: SliderTrack,
ctx: WidgetContext<'_, '_, '_, V>,
) -> impl IntoElement {
let WidgetContext { palette, view, cx } = ctx;
let ratio = ratio.clamp(0.0, 1.0);
let stops = track.stops();
let weak = cx.entity().downgrade();
let state = view.control_state();
let shown = if state.is_dragging(id) {
state.snap((id, "ratio"), ratio)
} else {
state.tween((id, "ratio"), ratio, MOVE)
};
let focus = state.focus((id, "thumb"), cx);
let click_focus = focus.clone();
let arrows = cx.listener(move |this, event: &KeyDownEvent, _window, cx| {
let Some(key) = keyboard::key(event) else {
return;
};
let moved = match stops {
Some(stops) => keyboard::nudge_stepped(key, Orientation::Horizontal, ratio, stops),
None => keyboard::nudge(key, Orientation::Horizontal, ratio, 0.05),
};
if let Some(moved) = moved {
cx.stop_propagation();
crate::state::update_track(this, id, point(moved, 0.0), cx);
cx.notify();
}
});
div()
.id(id)
.h(px(28.0))
.flex_1()
.px(px(6.0))
.flex()
.items_center()
.relative()
.cursor_pointer()
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, event: &MouseDownEvent, window, cx| {
this.control_state_mut()
.begin_track_drag(id, TrackAxis::Horizontal, stops);
if let Some((_, at)) = this.control_state().track_ratio_at(event.position) {
crate::state::update_track(this, id, at, cx);
}
window.focus(&click_focus, cx);
window.prevent_default();
cx.notify();
}),
)
.child(
div()
.flex_1()
.h(px(5.0))
.rounded(px(2.5))
.bg(palette.field_border)
.relative()
.child(track_probe(id, weak))
.children(stops.map(|stops| tick_marks(stops, palette)))
.child(
div()
.absolute()
.left_0()
.top_0()
.bottom_0()
.w(gpui::relative(shown))
.rounded(px(2.5))
.bg(palette.accent)
.opacity(if palette.is_dark { 0.45 } else { 0.55 }),
)
.child(
div()
.relative()
.child(keyboard::ring_for(&focus, 7.0, palette).on_key_down(arrows))
.absolute()
.top(px(-4.5))
.left(gpui::relative(shown))
.ml(px(-7.0))
.w(px(14.0))
.h(px(14.0))
.rounded_full()
.bg(palette.field_surface)
.border_1()
.border_color(palette.field_border_strong),
),
)
}
pub(crate) fn track_probe<V: ControlHost>(
id: ComboId,
weak: gpui::WeakEntity<V>,
) -> impl IntoElement {
canvas(
move |bounds, _window, cx| {
if let Some(host) = weak.upgrade() {
host.update(cx, |host, _cx| {
host.control_state_mut().record_track(id, bounds);
});
}
},
|_bounds, _state, _window, _cx| {},
)
.absolute()
.size_full()
}
fn tick_marks(stops: u32, palette: Palette) -> impl IntoElement {
let last = (stops - 1) as f32;
div()
.absolute()
.inset_0()
.children((0..stops).map(move |stop| {
let at = stop as f32 / last;
div()
.absolute()
.top(px(7.0))
.left(gpui::relative(at))
.ml(px(-0.5))
.w(px(1.0))
.h(px(4.0))
.bg(palette.field_border_strong)
.opacity(0.7)
}))
}
#[allow(clippy::too_many_arguments)]
pub fn checkbox<V: ControlHost>(
id: impl Into<ElementId>,
checked: bool,
label: Option<&str>,
enabled: bool,
ctx: WidgetContext<'_, '_, '_, V>,
on_toggle: impl Fn(&mut V, bool, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
const BOX: f32 = 15.0;
let dark = ctx.palette.is_dark;
let palette = ctx.palette;
let tick: gpui::Hsla = crate::color::to_hsla(palette.control_label);
let label: Option<SharedString> = label.map(std::convert::Into::into);
let on_toggle = Rc::new(on_toggle);
let id: ElementId = id.into();
let on = ctx.state().blend((&id, "state"), checked, SWITCH_SLIDE);
let cx: &mut Context<V> = &mut *ctx.cx;
let fill = lighting::lit_mix(palette.field_surface, palette.control_fill, 0.1, on);
let border = crate::color::lerp(
palette.field_border_strong,
lighting::rim(palette.control_fill, dark),
on,
);
div()
.id(id)
.flex()
.items_center()
.gap(px(7.0))
.flex_none()
.when(!enabled, |el| el.opacity(0.5))
.when(enabled, |el| {
let clicked = on_toggle.clone();
el.cursor_pointer()
.on_click(cx.listener(move |this, _event, window, cx| {
clicked(this, !checked, window, cx);
cx.notify();
}))
})
.child(
div()
.relative()
.w(px(BOX))
.h(px(BOX))
.flex_none()
.rounded(px(4.0))
.bg(fill)
.border_1()
.border_color(border)
.shadow(if on >= 0.5 {
lighting::raised(dark)
} else {
lighting::recessed(dark)
})
.when(on > 0.01, move |el| {
el.child(
canvas(
|_bounds, _window, _cx| {},
move |bounds, _state, window, _cx| {
let origin = bounds.origin;
let scale = 0.6 + 0.4 * on;
let at = |x: f32, y: f32| {
point(
origin.x + px(7.5 + (x - 7.5) * scale),
origin.y + px(7.5 + (y - 7.5) * scale),
)
};
let mut tick = tick;
tick.alpha *= on;
let mut builder = PathBuilder::stroke(px(1.75));
builder.move_to(at(3.5, 7.5));
builder.line_to(at(6.2, 10.5));
builder.line_to(at(11.5, 4.5));
if let Ok(path) = builder.build() {
window.paint_path(path, tick);
}
},
)
.size_full(),
)
})
.when(enabled, |el| {
let toggled = on_toggle.clone();
el.child(
keyboard::ring("ring", 4.0, palette).on_key_down(cx.listener(
move |this, event: &KeyDownEvent, window, cx| {
if keyboard::key(event) == Some(Key::Activate) {
cx.stop_propagation();
toggled(this, !checked, window, cx);
cx.notify();
}
},
)),
)
}),
)
.children(label.map(|label| {
div()
.text_size(px(12.5))
.text_color(palette.text_primary)
.whitespace_nowrap()
.child(label)
}))
}
#[allow(clippy::too_many_arguments)]
pub fn segmented<V: ControlHost>(
id: &'static str,
options: &[String],
selected: usize,
enabled: bool,
ctx: WidgetContext<'_, '_, '_, V>,
on_select: impl Fn(&mut V, usize, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
let palette = ctx.palette;
let view = ctx.view;
let cx: &mut Context<V> = &mut *ctx.cx;
let dark = palette.is_dark;
let on_select = Rc::new(on_select);
let fill = palette.control_fill;
let state = view.control_state();
let focus = state.focus(id, cx);
let count = options.len();
let weak = cx.entity().downgrade();
let mut arrows = (enabled && count > 0).then(|| {
let on_select = on_select.clone();
cx.listener(move |this, event: &KeyDownEvent, window, cx| {
let Some(key) = keyboard::key(event) else {
return;
};
if let Some(moved) = keyboard::step(key, Orientation::Horizontal, selected, count) {
cx.stop_propagation();
on_select(this, moved, window, cx);
cx.notify();
}
})
});
let pill = state
.group(id)
.zip(state.slot(id, selected))
.map(|(group, slot)| {
let x = f32::from(slot.origin.x) - f32::from(group.origin.x);
(
state.tween((id, "pill-x"), x, MOVE),
state.tween((id, "pill-w"), f32::from(slot.size.width), MOVE),
)
});
let mut segments: Vec<gpui::AnyElement> = Vec::with_capacity(options.len());
for (index, option) in options.iter().enumerate() {
let cx: &mut Context<V> = &mut *cx;
let on_select = on_select.clone();
let active = index == selected;
let click_focus = focus.clone();
let on = state.blend((id, "segment-on", index), active, SWITCH_SLIDE);
let segment_arrows = if active { arrows.take() } else { None };
segments.push(
div()
.id(("segment", index))
.relative()
.child(slot_probe(id, index, weak.clone()))
.when(active && enabled, |el| {
el.child(
keyboard::ring_for(&focus, CONTROL_RADIUS - 2.0, palette)
.when_some(segment_arrows, |el, arrows| el.on_key_down(arrows)),
)
})
.h_full()
.flex_1()
.px(px(10.0))
.flex()
.items_center()
.justify_center()
.rounded(px(CONTROL_RADIUS - 2.0))
.text_size(px(12.0))
.font_weight(if active {
FontWeight::MEDIUM
} else {
FontWeight::NORMAL
})
.text_color(crate::color::lerp(
palette.text_secondary,
palette.control_label,
on,
))
.whitespace_nowrap()
.overflow_hidden()
.when(active && pill.is_none(), |el| {
el.bg(lighting::lit(fill, 0.09))
.shadow(lighting::raised(dark))
})
.when(enabled && !active, move |el| {
el.cursor_pointer()
.hover(move |style| style.bg(palette.row_hover))
.on_click(cx.listener(move |this, _event, window, cx| {
window.focus(&click_focus, cx);
on_select(this, index, window, cx);
cx.notify();
}))
})
.child(SharedString::from(option))
.into_any_element(),
);
}
div()
.id(id)
.relative()
.h(px(CONTROL_HEIGHT))
.flex()
.items_center()
.gap(px(2.0))
.p(px(2.0))
.rounded(px(CONTROL_RADIUS))
.bg(palette.field_surface)
.border_1()
.border_color(palette.field_border)
.shadow(lighting::recessed(dark))
.when(!enabled, |el| el.opacity(0.5))
.child(group_probe(id, weak))
.when_some(pill, |el, (x, width)| {
el.child(
div()
.absolute()
.top(px(2.0))
.bottom(px(2.0))
.left(px(x))
.w(px(width))
.rounded(px(CONTROL_RADIUS - 2.0))
.bg(lighting::lit(fill, 0.09))
.shadow(lighting::raised(dark)),
)
})
.children(segments)
}
fn slot_probe<V: ControlHost>(
id: ComboId,
slot: usize,
weak: gpui::WeakEntity<V>,
) -> impl IntoElement {
canvas(
move |bounds, _window, cx| {
if let Some(host) = weak.upgrade() {
host.update(cx, |host, _cx| {
host.control_state_mut().record_slot(id, slot, bounds);
});
}
},
|_bounds, _state, _window, _cx| {},
)
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
}
pub(crate) fn measure_probe<V: ControlHost>(
tag: Tag,
weak: gpui::WeakEntity<V>,
) -> impl IntoElement {
canvas(
move |bounds, _window, cx| {
if let Some(host) = weak.upgrade() {
host.update(cx, |host, _cx| {
host.control_state_mut().measure(tag, bounds);
});
}
},
|_bounds, _state, _window, _cx| {},
)
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
}
fn group_probe<V: ControlHost>(id: ComboId, weak: gpui::WeakEntity<V>) -> impl IntoElement {
canvas(
move |bounds, _window, cx| {
if let Some(host) = weak.upgrade() {
host.update(cx, |host, _cx| {
host.control_state_mut().record_group(id, bounds);
});
}
},
|_bounds, _state, _window, _cx| {},
)
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
}
#[allow(clippy::too_many_arguments)]
pub fn icon_button<V: ControlHost>(
id: impl Into<ElementId>,
icon: impl IntoElement,
label: impl Into<Hint>,
size: f32,
active: bool,
enabled: bool,
palette: Palette,
cx: &mut Context<V>,
on_click: impl Fn(&mut V, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
let dark = palette.is_dark;
let on_click = Rc::new(on_click);
let id: ElementId = id.into();
let fill = if active {
palette.control_fill
} else {
palette.soft_fill
};
div()
.id(id)
.w(px(size))
.h(px(size))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded(px(CONTROL_RADIUS))
.bg(lighting::lit(fill, if active { 0.04 } else { 0.08 }))
.border_1()
.border_color(lighting::rim(fill, dark))
.text_color(if active {
palette.control_label
} else {
palette.text_secondary
})
.when(active, |el| el.shadow(lighting::recessed(dark)))
.when(!active, |el| el.shadow(lighting::raised(dark)))
.when(!enabled, |el| el.opacity(0.5))
.when(enabled, move |el| {
let pressed = on_click.clone();
el.cursor_pointer()
.hover(move |style| style.bg(lighting::lit(palette.soft_fill_hover, 0.1)))
.on_click(cx.listener(move |this, _event, window, cx| {
on_click(this, window, cx);
}))
.relative()
.child(
keyboard::ring("ring", CONTROL_RADIUS, palette).on_key_down(cx.listener(
move |this, event: &KeyDownEvent, window, cx| {
if keyboard::key(event) == Some(Key::Activate) {
cx.stop_propagation();
pressed(this, window, cx);
cx.notify();
}
},
)),
)
})
.child(icon)
.tooltip(label.into().tooltip(palette))
}
pub fn glyph(character: &'static str) -> Div {
div().text_size(px(13.0)).child(character)
}
pub fn progress_bar(fraction: f32, palette: Palette) -> impl IntoElement {
let fraction = fraction.clamp(0.0, 1.0);
div()
.h(px(6.0))
.w_full()
.flex_none()
.rounded(px(3.0))
.bg(palette.field_border)
.shadow(lighting::recessed(palette.is_dark))
.overflow_hidden()
.child(
div()
.h_full()
.w(gpui::relative(fraction))
.rounded(px(3.0))
.bg(lighting::lit(palette.accent, 0.12)),
)
}
pub fn separator(vertical: bool, palette: Palette) -> impl IntoElement {
let mut color: gpui::Hsla = crate::color::to_hsla(palette.field_border);
color.alpha = 0.9;
div()
.flex_none()
.bg(color)
.when(vertical, |el| el.w(px(1.0)).h_full())
.when(!vertical, |el| el.h(px(1.0)).w_full())
}
pub fn scrollbar<V: ControlHost>(
id: &'static str,
handle: &ScrollHandle,
axis: ScrollAxis,
ctx: WidgetContext<'_, '_, '_, V>,
) -> gpui::AnyElement {
use crate::scroll::{apply_scroll_drag, scrollbar_geometry};
let WidgetContext { palette, view, cx } = ctx;
let Some(geometry) = scrollbar_geometry(handle, axis) else {
return div().absolute().into_any_element();
};
let shown = view
.control_state()
.tween_from(("scrollbar", id, "shown"), 0.0, 1.0, SWITCH_SLIDE);
let mut thumb_color: gpui::Hsla = crate::color::to_hsla(palette.text_secondary);
thumb_color.alpha = 0.24;
let drag_handle = handle.clone();
let track = div()
.id(Tag::new((id, "scrollbar")).element_id())
.absolute()
.opacity(shown)
.block_mouse_except_scroll()
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, event: &MouseDownEvent, _window, cx| {
let Some(geometry) = scrollbar_geometry(&drag_handle, axis) else {
return;
};
let position = match axis {
ScrollAxis::Vertical => f32::from(event.position.y),
ScrollAxis::Horizontal => f32::from(event.position.x),
};
let within = position - geometry.track_start - geometry.thumb_pos;
let grab = if (0.0..=geometry.thumb_len).contains(&within) {
within
} else {
geometry.thumb_len / 2.0
};
let drag = ScrollDrag {
handle: drag_handle.clone(),
axis,
grab,
};
apply_scroll_drag(&drag, position);
this.control_state_mut().begin_scroll_drag(drag);
cx.notify();
}),
)
.on_mouse_move(
cx.listener(|this, event: &gpui::MouseMoveEvent, window, cx| {
this.forwarded_mouse_move(event, window, cx);
}),
)
.on_mouse_up(
MouseButton::Left,
cx.listener(|this, _event, window, cx| {
this.forwarded_mouse_up(window, cx);
}),
);
let thumb = div()
.absolute()
.rounded_full()
.bg(thumb_color)
.hover(move |style| {
let mut hovered = thumb_color;
hovered.alpha = 0.50;
style.bg(hovered)
});
match axis {
ScrollAxis::Vertical => track
.top_0()
.bottom(px(geometry.track_end_inset))
.right_0()
.w(px(SCROLLBAR_THICKNESS))
.child(
thumb
.top(px(geometry.thumb_pos))
.right(px(3.0))
.w(px(THUMB_THICKNESS))
.h(px(geometry.thumb_len)),
)
.into_any_element(),
ScrollAxis::Horizontal => track
.left_0()
.right(px(geometry.track_end_inset))
.bottom_0()
.h(px(SCROLLBAR_THICKNESS))
.child(
thumb
.left(px(geometry.thumb_pos))
.bottom(px(3.0))
.h(px(THUMB_THICKNESS))
.w(px(geometry.thumb_len)),
)
.into_any_element(),
}
}
pub const CHIP_HEIGHT: f32 = 26.0;
#[derive(Clone, Copy, Debug)]
pub enum ChipSelection<'a> {
One(Option<usize>),
Many(&'a [bool]),
}
impl ChipSelection<'_> {
fn holds(&self, index: usize) -> bool {
match self {
ChipSelection::One(selected) => *selected == Some(index),
ChipSelection::Many(mask) => mask.get(index).copied().unwrap_or(false),
}
}
}
#[allow(clippy::too_many_arguments)]
pub fn chip<V: ControlHost>(
id: impl Into<ElementId>,
label: &str,
selected: bool,
enabled: bool,
ctx: WidgetContext<'_, '_, '_, V>,
on_click: impl Fn(&mut V, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
let WidgetContext { palette, view, cx } = ctx;
let dark = palette.is_dark;
let text: SharedString = SharedString::from(label);
let on_click = Rc::new(on_click);
let id: ElementId = id.into();
let on = view
.control_state()
.blend((&id, "state"), selected, SWITCH_SLIDE);
let mix = |a, b| crate::color::lerp(a, b, on);
let fill = mix(palette.soft_fill, palette.control_fill);
let fill_hover = mix(palette.soft_fill_hover, palette.control_fill);
let label_color = mix(palette.soft_label, palette.control_label);
let border = mix(lighting::rim(palette.soft_fill, dark), palette.accent);
div()
.id(id)
.h(px(CHIP_HEIGHT))
.flex_none()
.px(px(11.0))
.flex()
.items_center()
.justify_center()
.rounded(px(CONTROL_RADIUS))
.bg(lighting::lit(fill, 0.08))
.border_1()
.border_color(border)
.shadow(lighting::raised(dark))
.text_size(px(12.0))
.font_weight(if selected {
FontWeight::MEDIUM
} else {
FontWeight::NORMAL
})
.text_color(label_color)
.whitespace_nowrap()
.when(!enabled, |el| el.opacity(0.5))
.when(enabled, move |el| {
let pressed = on_click.clone();
el.cursor_pointer()
.hover(move |style| style.bg(lighting::lit(fill_hover, 0.11)))
.active(move |style| style.bg(lighting::lit(lighting::shade(fill, -0.06), 0.0)))
.on_click(cx.listener(move |this, _event, window, cx| {
on_click(this, window, cx);
}))
.relative()
.child(
keyboard::ring("ring", CONTROL_RADIUS, palette).on_key_down(cx.listener(
move |this, event: &KeyDownEvent, window, cx| {
if keyboard::key(event) == Some(Key::Activate) {
cx.stop_propagation();
pressed(this, window, cx);
cx.notify();
}
},
)),
)
})
.child(text)
}
#[allow(clippy::too_many_arguments)]
pub fn chip_group<V: ControlHost>(
id: &'static str,
options: &[String],
selected: ChipSelection<'_>,
enabled: bool,
mut ctx: WidgetContext<'_, '_, '_, V>,
on_select: impl Fn(&mut V, usize, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
let on_select = Rc::new(on_select);
let mut chips: Vec<gpui::AnyElement> = Vec::with_capacity(options.len());
for (index, option) in options.iter().enumerate() {
let on_select = on_select.clone();
chips.push(
chip(
Tag::new((id, "chip", index)).element_id(),
option,
selected.holds(index),
enabled,
ctx.reborrow(),
move |this, window, cx| on_select(this, index, window, cx),
)
.into_any_element(),
);
}
div()
.flex()
.flex_row()
.flex_wrap()
.gap(px(6.0))
.children(chips)
}
#[derive(Clone, Debug)]
pub struct Choice {
pub label: SharedString,
pub detail: Option<SharedString>,
pub enabled: bool,
}
impl Choice {
pub fn new(label: impl Into<SharedString>) -> Self {
Self {
label: label.into(),
detail: None,
enabled: true,
}
}
pub fn detail(mut self, detail: impl Into<SharedString>) -> Self {
self.detail = Some(detail.into());
self
}
pub fn disabled(mut self) -> Self {
self.enabled = false;
self
}
}
fn radio_tab_stop(choices: &[Choice], selected: usize, enabled: bool) -> Option<usize> {
if !enabled {
None
} else if choices.get(selected).is_some_and(|choice| choice.enabled) {
Some(selected)
} else {
choices.iter().position(|choice| choice.enabled)
}
}
#[allow(clippy::too_many_arguments)]
pub fn radio_group<V: ControlHost>(
id: &'static str,
choices: &[Choice],
selected: usize,
enabled: bool,
ctx: WidgetContext<'_, '_, '_, V>,
on_select: impl Fn(&mut V, usize, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
let palette = ctx.palette;
let view = ctx.view;
let cx: &mut Context<V> = &mut *ctx.cx;
let dark = palette.is_dark;
let on_select = Rc::new(on_select);
let focus = view.control_state().focus(id, cx);
let live: Vec<usize> = choices
.iter()
.enumerate()
.filter(|(_, choice)| choice.enabled)
.map(|(index, _)| index)
.collect();
let keyboard_at = radio_tab_stop(choices, selected, enabled);
let here = live
.iter()
.position(|index| *index == selected)
.unwrap_or(0);
let mut arrows = (enabled && !live.is_empty()).then(|| {
let on_select = on_select.clone();
cx.listener(move |this, event: &KeyDownEvent, window, cx| {
let Some(key) = keyboard::key(event) else {
return;
};
let moved = if key == Key::Activate {
Some(here)
} else {
keyboard::step(key, Orientation::Vertical, here, live.len())
};
if let Some(moved) = moved {
cx.stop_propagation();
on_select(this, live[moved], window, cx);
cx.notify();
}
})
});
let mut rows: Vec<gpui::AnyElement> = Vec::with_capacity(choices.len());
for (index, choice) in choices.iter().enumerate() {
let cx: &mut Context<V> = &mut *cx;
let on_select = on_select.clone();
let active = index == selected;
let clickable = enabled && choice.enabled;
let detail = choice.detail.clone();
let click_focus = focus.clone();
let on = view
.control_state()
.blend((id, "choice-on", index), active, SWITCH_SLIDE);
let tab_stop = keyboard_at == Some(index);
let dot_arrows = if tab_stop { arrows.take() } else { None };
rows.push(
div()
.id(("choice", index))
.flex()
.items_start()
.gap(px(8.0))
.py(px(4.0))
.when(!clickable, |el| el.opacity(0.5))
.when(clickable, move |el| {
el.cursor_pointer()
.on_click(cx.listener(move |this, _event, window, cx| {
window.focus(&click_focus, cx);
on_select(this, index, window, cx);
cx.notify();
}))
})
.child(
div()
.id("dot")
.relative()
.mt(px(2.0))
.w(px(15.0))
.h(px(15.0))
.flex_none()
.rounded_full()
.bg(palette.field_surface)
.border_1()
.border_color(crate::color::lerp(
palette.field_border_strong,
palette.accent,
on,
))
.shadow(lighting::recessed(dark))
.flex()
.items_center()
.justify_center()
.when(on > 0.01, |el| {
let core = 7.0 * (0.4 + 0.6 * on);
el.child(
div()
.w(px(core))
.h(px(core))
.rounded_full()
.opacity(on)
.bg(lighting::lit(palette.control_fill, 0.12)),
)
})
.when(tab_stop, |el| {
el.child(
keyboard::ring_for(&focus, 7.5, palette)
.when_some(dot_arrows, |el, arrows| el.on_key_down(arrows)),
)
}),
)
.child(
div()
.flex()
.flex_col()
.gap(px(1.0))
.child(
div()
.text_size(px(12.5))
.text_color(palette.text_primary)
.child(choice.label.clone()),
)
.children(detail.map(|detail| {
div()
.text_size(px(11.5))
.text_color(palette.text_secondary)
.child(detail)
})),
)
.into_any_element(),
);
}
div().id(id).flex().flex_col().gap(px(2.0)).children(rows)
}
pub fn search_field<V: ControlHost>(
id: &'static str,
input: &Entity<TextInput>,
palette: Palette,
window: &Window,
cx: &mut Context<V>,
) -> impl IntoElement {
input.update(cx, |input, _cx| {
input.restyle(palette);
});
let focused = input.read(cx).focus_handle.is_focused(window);
let has_text = !input.read(cx).content.is_empty();
let glyph: gpui::Hsla = crate::color::to_hsla(palette.text_secondary);
let click_input = input.clone();
let clear_input = input.clone();
let key_clear = input.clone();
div()
.h(px(CONTROL_HEIGHT))
.w_full()
.pl(px(28.0))
.pr(px(if has_text { 26.0 } else { 9.0 }))
.relative()
.flex()
.items_center()
.rounded(px(CONTROL_RADIUS))
.bg(palette.field_surface)
.border_1()
.border_color(if focused {
palette.accent
} else {
palette.field_border
})
.shadow(well_shadows(palette, focused))
.overflow_hidden()
.on_mouse_down(
MouseButton::Left,
cx.listener(move |_host, event: &MouseDownEvent, window, cx| {
click_input.update(cx, |input, cx| {
input.handle_chrome_click(event.position, window, cx)
});
}),
)
.child(
div()
.absolute()
.left(px(8.0))
.top(px((CONTROL_HEIGHT - 2.0 - 14.0) / 2.0))
.w(px(14.0))
.h(px(14.0))
.child(
canvas(
|_bounds, _window, _cx| {},
move |bounds, _state, window, _cx| {
let origin = bounds.origin;
let mut builder = PathBuilder::stroke(px(1.3));
let (cx_, cy, r) = (origin.x + px(6.0), origin.y + px(6.0), 4.3f32);
for step in 0..=12 {
let angle = step as f32 * std::f32::consts::TAU / 12.0;
let at = point(cx_ + px(r * angle.cos()), cy + px(r * angle.sin()));
if step == 0 {
builder.move_to(at);
} else {
builder.line_to(at);
}
}
builder.move_to(point(origin.x + px(9.2), origin.y + px(9.2)));
builder.line_to(point(origin.x + px(13.0), origin.y + px(13.0)));
if let Ok(path) = builder.build() {
window.paint_path(path, glyph);
}
},
)
.size_full(),
),
)
.child(input.clone())
.when(has_text, |el| {
el.child(
div()
.id(Tag::new((id, "search-clear")).element_id())
.relative()
.child(
keyboard::ring("ring", 8.0, palette).on_key_down(cx.listener(
move |_host, event: &KeyDownEvent, window, cx| {
if keyboard::key(event) == Some(Key::Activate) {
cx.stop_propagation();
key_clear.update(cx, |input, cx| {
window.focus(&input.focus_handle, cx);
input.set_text("", cx);
});
cx.notify();
}
},
)),
)
.absolute()
.right(px(6.0))
.top(px((CONTROL_HEIGHT - 2.0 - 16.0) / 2.0))
.w(px(16.0))
.h(px(16.0))
.rounded_full()
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(move |style| style.bg(palette.row_hover))
.on_click(cx.listener(move |_host, _event, window, cx| {
clear_input.update(cx, |input, cx| {
window.focus(&input.focus_handle, cx);
input.set_text("", cx);
});
cx.notify();
}))
.child(cross_glyph(7.0, palette.text_secondary)),
)
})
}
pub(crate) fn cross_glyph(size: f32, color: gpui::Rgba) -> impl IntoElement {
canvas(
|_bounds, _window, _cx| {},
move |bounds, _state, window, _cx| {
let (x, y) = (bounds.origin.x, bounds.origin.y);
let mut builder = PathBuilder::stroke(px(1.2));
builder.move_to(point(x, y));
builder.line_to(point(x + px(size), y + px(size)));
builder.move_to(point(x + px(size), y));
builder.line_to(point(x, y + px(size)));
if let Ok(path) = builder.build() {
window.paint_path(path, color);
}
},
)
.w(px(size))
.h(px(size))
}
fn spinner_phase(since_epoch: std::time::Duration) -> f32 {
(since_epoch.as_millis() % 1000) as f32 / 1000.0
}
pub fn spinner(size: f32, palette: Palette) -> impl IntoElement {
let color: gpui::Hsla = crate::color::to_hsla(palette.accent);
let radius = size / 2.0 - 1.5;
div().w(px(size)).h(px(size)).flex_none().child(
canvas(
|_bounds, _window, _cx| {},
move |bounds, _state, window, cx| {
if bounds.intersect(&window.content_mask().bounds).is_empty() {
return;
}
let phase = if cx.reduce_motion() {
0.0
} else {
window.request_animation_frame();
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(spinner_phase)
.unwrap_or(0.0)
};
let start = phase * std::f32::consts::TAU;
let origin = bounds.origin;
let centre = point(origin.x + px(size / 2.0), origin.y + px(size / 2.0));
let mut builder = PathBuilder::stroke(px(1.8));
let steps = 18;
for step in 0..=steps {
let angle = start + (step as f32 / steps as f32) * std::f32::consts::TAU * 0.75;
let at = point(
centre.x + px(radius * angle.cos()),
centre.y + px(radius * angle.sin()),
);
if step == 0 {
builder.move_to(at);
} else {
builder.line_to(at);
}
}
if let Ok(path) = builder.build() {
window.paint_path(path, color);
}
},
)
.size_full(),
)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum BadgeTone {
#[default]
Neutral,
Accent,
Danger,
}
pub fn badge(text: &str, tone: BadgeTone, palette: Palette) -> impl IntoElement {
let (fill, label) = match tone {
BadgeTone::Neutral => (palette.soft_fill, palette.soft_label),
BadgeTone::Accent => (palette.control_fill, palette.control_label),
BadgeTone::Danger => (palette.danger_fill, palette.danger_label),
};
div()
.flex_none()
.h(px(17.0))
.px(px(6.0))
.flex()
.items_center()
.rounded(px(8.5))
.bg(lighting::lit(fill, 0.07))
.border_1()
.border_color(lighting::rim(fill, palette.is_dark))
.text_size(px(10.5))
.font_weight(FontWeight::MEDIUM)
.text_color(label)
.whitespace_nowrap()
.child(SharedString::from(text))
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn spinner_phase_walks_the_second() {
assert_eq!(spinner_phase(Duration::from_millis(0)), 0.0);
assert_eq!(spinner_phase(Duration::from_millis(250)), 0.25);
assert_eq!(spinner_phase(Duration::from_millis(999)), 0.999);
assert_eq!(spinner_phase(Duration::from_millis(1250)), 0.25);
}
#[test]
fn spinner_phase_still_moves_at_a_real_timestamp() {
let now = Duration::from_millis(1_757_000_000_500);
assert_eq!(now.as_secs_f32() % 1.0, 0.0, "the trap this avoids");
assert_eq!(spinner_phase(now), 0.5);
}
#[test]
fn spinner_phase_is_distinct_across_a_frame() {
let a = spinner_phase(Duration::from_millis(1_757_000_000_000));
let b = spinner_phase(Duration::from_millis(1_757_000_000_016));
assert_ne!(a, b);
}
fn chosen_row_centre(placement: ComboPlacement, chosen: usize) -> f32 {
placement.top
+ COMBO_LIST_BORDER
+ COMBO_LIST_PADDING
+ chosen as f32 * (COMBO_ROW_HEIGHT + COMBO_ROW_GAP)
- placement.scroll
+ COMBO_ROW_HEIGHT / 2.0
}
#[test]
fn the_chosen_row_lands_centred_on_the_button() {
for (chosen, count) in [(0, 1), (0, 4), (3, 4), (2, 7), (7, 20), (15, 20), (19, 20)] {
let placement = combo_placement(chosen, count);
assert_eq!(
chosen_row_centre(placement, chosen),
CONTROL_HEIGHT / 2.0,
"row {chosen} of {count}"
);
}
}
#[test]
fn a_list_that_fits_does_not_start_scrolled() {
for chosen in 0..7 {
assert_eq!(combo_placement(chosen, 7).scroll, 0.0, "row {chosen}");
}
}
#[test]
fn a_long_list_scrolls_only_as_far_as_the_chosen_row_needs() {
let pitch = COMBO_ROW_HEIGHT + COMBO_ROW_GAP;
assert_eq!(combo_placement(6, 20).scroll, 0.0);
let row_bottom = COMBO_LIST_PADDING + 15.0 * pitch + COMBO_ROW_HEIGHT;
assert_eq!(
combo_placement(15, 20).scroll,
row_bottom - COMBO_LIST_MAX_HEIGHT
);
let content = 2.0 * COMBO_LIST_PADDING + 20.0 * pitch - COMBO_ROW_GAP;
let furthest = content - COMBO_LIST_MAX_HEIGHT;
assert!(combo_placement(19, 20).scroll <= furthest);
assert_eq!(combo_placement(40, 20).scroll, furthest);
}
#[test]
fn empty_combos_do_not_open_and_stale_selections_open_on_a_real_option() {
let mut state = ControlState::default();
open_list(&mut state, "empty", 0, 0);
assert!(!state.is_combo_open("empty"));
open_list(&mut state, "short", 20, 3);
assert_eq!(state.combo_highlight_or(20), 2);
}
#[test]
fn radio_focus_skips_unavailable_choices_and_disabled_groups() {
let choices = [
Choice::new("Unavailable").disabled(),
Choice::new("First"),
Choice::new("Second"),
];
assert_eq!(radio_tab_stop(&choices, 2, true), Some(2));
assert_eq!(radio_tab_stop(&choices, 0, true), Some(1));
assert_eq!(radio_tab_stop(&choices, 99, true), Some(1));
assert_eq!(radio_tab_stop(&choices, 1, false), None);
assert_eq!(radio_tab_stop(&choices[..1], 0, true), None);
assert_eq!(radio_tab_stop(&[], 0, true), None);
}
}