use std::rc::Rc;
use std::time::Instant;
use gpui::{
Anchor, Context, Div, ElementId, Entity, FocusHandle, FontWeight, KeyDownEvent, MouseButton,
MouseDownEvent, PathBuilder, ScrollHandle, SharedString, Window, anchored, canvas, deferred,
div, point, prelude::*, px,
};
use crate::easing::{ease_in_cubic, ease_out_cubic, lerp_f32, progress};
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::{
COMBO_REVEAL, ComboId, ControlHost, ControlState, MOVE, SWITCH_SLIDE, TrackAxis,
};
use crate::text_input::TextInput;
pub const CONTROL_HEIGHT: f32 = 30.0;
pub const CONTROL_RADIUS: f32 = 6.0;
pub fn caption(palette: Palette, text: &str) -> impl IntoElement {
div()
.flex_none()
.text_size(px(12.0))
.font_weight(FontWeight::MEDIUM)
.text_color(palette.text_secondary)
.whitespace_nowrap()
.child(SharedString::from(text.to_string()))
}
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(
&ElementId::Name(id.into()),
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 = text.to_string().into();
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(
ElementId::Name(format!("{id}-ring").into()),
CONTROL_RADIUS,
palette,
)
.on_key_down(activate)
.into_any_element(),
};
div()
.id(id)
.h(px(CONTROL_HEIGHT))
.w_full()
.px(px(12.0))
.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(12.5))
.font_weight(FontWeight::MEDIUM)
.text_color(label_color)
.whitespace_nowrap()
.overflow_hidden()
.when(!enabled, |el| el.opacity(0.5))
.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, -0.06), 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,
palette: Palette,
view: &V,
cx: &mut Context<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 id: ElementId = id.into();
let track_off = palette.field_border;
let track_on = palette.accent;
let track_target = if checked { track_on } else { track_off };
let track_source = if checked { track_off } else { track_on };
let left_target = if checked { left_on } else { left_off };
let left_source = if checked { left_off } else { left_on };
let track_opacity = if !enabled {
0.45
} else if checked {
if palette.is_dark { 0.5 } else { 0.58 }
} else {
1.0
};
let t = view
.control_state()
.transition(&id, u64::from(checked), SWITCH_SLIDE);
let eased = ease_out_cubic(t);
let track_color = crate::color::lerp(track_source, track_target, eased);
let left = lerp_f32(left_source, left_target, eased);
let ring_id = ElementId::Name(format!("{id}-ring").into());
let label: Option<SharedString> = label.map(|text| text.to_string().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(26.0))
.flex_none()
.relative()
.rounded(px(13.0))
.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_id, 13.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()
.when(!enabled, |el| el.opacity(0.5))
.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);
});
let edit = edit_input.clone();
let commit: Commit<V> = Rc::new(move |this, value, window, cx| {
edit.update(cx, |input, 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> = Box<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>| {
let step_ring = ElementId::Name(format!("{id:?}-ring").into());
div()
.id(id)
.w(px(22.0))
.h(px(22.0))
.rounded(px(3.0))
.flex()
.items_center()
.justify_center()
.text_size(px(13.0))
.text_color(palette.text_secondary)
.when(!enabled, |el| el.opacity(0.45))
.when(enabled && active, move |el| {
let handler = Rc::new(handler);
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(step_ring, 3.0, 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(118.0))
.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(0.5))
.flex()
.items_center()
.justify_between()
.px(px(4.0))
.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).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(
ElementId::Name(format!("{id_prefix}-dec").into()),
"\u{2212}",
value > min,
cx,
Box::new(move |this, window, cx| {
dec(this, (value - 1).max(min), window, cx);
}),
))
.child(
div()
.flex_1()
.px(px(4.0))
.text_size(px(12.0))
.text_color(palette.text_primary)
.child(edit_input.clone()),
)
.child(step_button(
ElementId::Name(format!("{id_prefix}-inc").into()),
"+",
value < max,
cx,
Box::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, 0.35, 3.0));
}
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(9.0))
.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);
});
let focused = input.read(cx).focus_handle.is_focused(window);
let click_input = input.clone();
div()
.id(ElementId::Name(
format!("text-area-{}", input.entity_id()).into(),
))
.when_some(height, |el, h| el.h(px(h)))
.when(height.is_none(), |el| el.flex_1().min_h(px(40.0)))
.line_height(px(17.0))
.w_full()
.px(px(10.0))
.py(px(8.0))
.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(0.5))
.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) {
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>,
palette: Palette,
view: &V,
cx: &mut Context<V>,
on_select: impl Fn(&mut V, usize, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
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 closing_since = state.combo_closing.and_then(|(closing, since)| {
(closing == id && since.elapsed() < state.scaled(COMBO_REVEAL)).then_some(since)
});
let showing = is_open || closing_since.is_some();
let reveal = if is_open {
state
.combo_opened_at
.map(|since| ease_out_cubic(progress(since, state.scaled(COMBO_REVEAL))))
.unwrap_or(1.0)
} else if let Some(since) = closing_since {
1.0 - ease_in_cubic(progress(since, state.scaled(COMBO_REVEAL)))
} else {
1.0
};
let drift = -4.0 * (1.0 - reveal);
let display: SharedString = options
.get(current_index)
.cloned()
.unwrap_or_default()
.into();
let options_owned: Vec<String> = options.to_vec();
let count = options.len();
let placement = combo_placement(state.combo_opened_on.unwrap_or(current_index), count);
let button = state.track_bounds.get(id).copied();
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()
.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().track_bounds.insert(id, bounds);
});
}
},
|_bounds, _state, _window, _cx| {},
)
.absolute()
.size_full(),
)
.child(
div()
.id(ElementId::Name(format!("{id}-toggle").into()))
.h(px(CONTROL_HEIGHT))
.w_full()
.pl(px(10.0))
.pr(px(28.0))
.flex()
.items_center()
.rounded(px(CONTROL_RADIUS))
.bg(lighting::lit(body_fill, 0.05))
.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(
ElementId::Name(format!("{id}-ring").into()),
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();
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);
}
}
}
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();
let dismissed_recently = state
.combo_dismissed_at
.is_some_and(|since| since.elapsed() < COMBO_REVEAL);
let dismissed = state.combo_dismissed.take();
state.combo_dismissed_at = None;
if dismissed_recently && dismissed == 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(ElementId::Name(format!("{id}-popup").into()))
.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.close_combo();
state.combo_dismissed = Some(id);
state.combo_dismissed_at = Some(Instant::now());
cx.notify();
},
))
})
.child(
div()
.id(ElementId::Name(format!("{id}-popup-list").into()))
.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_owned.into_iter().enumerate().map(
|(index, option)| {
let on_select = on_select.clone();
let highlighted = index == keyboard_at;
div()
.id(ElementId::NamedInteger(
format!("{id}-option").into(),
index as u64,
))
.h(px(COMBO_ROW_HEIGHT))
.flex_none()
.w_full()
.px(px(9.0))
.flex()
.items_center()
.rounded(px(CONTROL_RADIUS - 1.0))
.text_size(px(12.5))
.text_color(if highlighted {
palette.control_label
} else {
palette.text_primary
})
.when(highlighted, |elem| {
elem.bg(lighting::lit(
palette.control_fill,
0.08,
))
})
.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,
)),
),
)
.with_priority(100),
)
})
}
fn chevron_chip(fill: gpui::Rgba, chevron: gpui::Hsla, dark: bool) -> impl IntoElement {
div()
.absolute()
.right(px(5.0))
.top(px((CONTROL_HEIGHT - 2.0 - 18.0) / 2.0))
.w(px(18.0))
.h(px(18.0))
.rounded(px(CONTROL_RADIUS - 2.0))
.bg(lighting::lit(fill, 0.12))
.shadow(lighting::raised(dark))
.child(
canvas(
|_bounds, _window, _cx| {},
move |bounds, _state, window, _cx| {
let o = bounds.origin;
let mut builder = PathBuilder::stroke(px(1.5));
builder.move_to(point(o.x + px(5.5), o.y + px(7.5)));
builder.line_to(point(o.x + px(9.0), o.y + px(4.0)));
builder.line_to(point(o.x + px(12.5), o.y + px(7.5)));
builder.move_to(point(o.x + px(5.5), o.y + px(10.5)));
builder.line_to(point(o.x + px(9.0), o.y + px(14.0)));
builder.line_to(point(o.x + px(12.5), o.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,
palette: Palette,
view: &V,
cx: &mut Context<V>,
) -> impl IntoElement {
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(format!("{id}-ratio"), ratio)
} else {
state.tween(format!("{id}-ratio"), ratio, MOVE)
};
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();
this.track_dragged(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) {
this.track_dragged(id, at, cx);
}
window.focus_next(cx);
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(
ElementId::Name(format!("{id}-thumb").into()),
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().track_bounds.insert(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,
palette: Palette,
view: &V,
cx: &mut Context<V>,
on_toggle: impl Fn(&mut V, bool, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
const BOX: f32 = 15.0;
let dark = palette.is_dark;
let tick: gpui::Hsla = crate::color::to_hsla(palette.control_label);
let label: Option<SharedString> = label.map(|text| text.to_string().into());
let on_toggle = Rc::new(on_toggle);
let id: ElementId = id.into();
let box_id = id.clone();
let on = view.control_state().blend(
&ElementId::Name(format!("{box_id}-state").into()),
checked,
SWITCH_SLIDE,
);
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 o = bounds.origin;
let scale = 0.6 + 0.4 * on;
let at = |x: f32, y: f32| {
point(
o.x + px(7.5 + (x - 7.5) * scale),
o.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(
ElementId::Name(format!("{box_id}-ring").into()),
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,
palette: Palette,
view: &V,
cx: &mut Context<V>,
on_select: impl Fn(&mut V, usize, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
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_bounds
.get(id)
.zip(state.slot_bounds.get(id))
.and_then(|(group, slots)| {
let slot = slots.get(selected)?;
let x = f32::from(slot.origin.x) - f32::from(group.origin.x);
Some((x, f32::from(slot.size.width)))
})
.map(|(x, width)| {
(
state.tween(format!("{id}-pill-x"), x, MOVE),
state.tween(format!("{id}-pill-w"), 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(
&ElementId::NamedInteger(format!("{id}-segment-on").into(), index as u64),
active,
SWITCH_SLIDE,
);
let segment_arrows = if active { arrows.take() } else { None };
segments.push(
div()
.id(ElementId::NamedInteger(
format!("{id}-segment").into(),
index as u64,
))
.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.clone()))
.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| {
let slots = host.control_state_mut().slot_bounds.entry(id).or_default();
if slots.len() <= slot {
slots.resize(slot + 1, bounds);
}
slots[slot] = bounds;
});
}
},
|_bounds, _state, _window, _cx| {},
)
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
}
pub(crate) fn measure_probe<V: ControlHost>(
key: ElementId,
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()
.measured
.insert(key.clone(), 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().group_bounds.insert(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 icon_id = id.clone();
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(
ElementId::Name(format!("{icon_id}-ring").into()),
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,
palette: Palette,
view: &V,
cx: &mut Context<V>,
) -> gpui::AnyElement {
use crate::scroll::{apply_scroll_drag, scrollbar_geometry};
let Some(geometry) = scrollbar_geometry(handle, axis) else {
return div().absolute().into_any_element();
};
let shown =
view.control_state()
.tween_from(format!("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(ElementId::Name(format!("scrollbar-{id}").into()))
.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().scroll_drag = Some(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,
palette: Palette,
view: &V,
cx: &mut Context<V>,
on_click: impl Fn(&mut V, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
let dark = palette.is_dark;
let text: SharedString = label.to_string().into();
let on_click = Rc::new(on_click);
let id: ElementId = id.into();
let chip_id = id.clone();
let on = view.control_state().blend(
&ElementId::Name(format!("{chip_id}-state").into()),
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(
ElementId::Name(format!("{chip_id}-ring").into()),
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,
palette: Palette,
view: &V,
cx: &mut Context<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 cx: &mut Context<V> = &mut *cx;
let on_select = on_select.clone();
chips.push(
chip(
ElementId::NamedInteger(format!("{id}-chip").into(), index as u64),
option,
selected.holds(index),
enabled,
palette,
view,
cx,
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
}
}
#[allow(clippy::too_many_arguments)]
pub fn radio_group<V: ControlHost>(
id: &'static str,
choices: &[Choice],
selected: usize,
enabled: bool,
palette: Palette,
view: &V,
cx: &mut Context<V>,
on_select: impl Fn(&mut V, usize, &mut Window, &mut Context<V>) + 'static,
) -> impl IntoElement {
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 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;
};
if let Some(moved) = keyboard::step(key, Orientation::Vertical, here, live.len()) {
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(
&ElementId::NamedInteger(format!("{id}-choice-on").into(), index as u64),
active,
SWITCH_SLIDE,
);
let dot_arrows = if active { arrows.take() } else { None };
rows.push(
div()
.id(ElementId::NamedInteger(
format!("{id}-choice").into(),
index as u64,
))
.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(ElementId::NamedInteger(
format!("{id}-dot").into(),
index as u64,
))
.relative()
.when(active, |el| {
el.child(
keyboard::ring_for(&focus, 7.5, palette)
.when_some(dot_arrows, |el, arrows| el.on_key_down(arrows)),
)
})
.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)),
)
}),
)
.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 o = bounds.origin;
let mut builder = PathBuilder::stroke(px(1.3));
let (cx_, cy, r) = (o.x + px(6.0), o.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(o.x + px(9.2), o.y + px(9.2)));
builder.line_to(point(o.x + px(13.0), o.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(ElementId::Name(format!("{id}-clear").into()))
.relative()
.child(
keyboard::ring(
ElementId::Name(format!("{id}-clear-ring").into()),
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| 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()
.text_size(px(11.0))
.text_color(palette.text_secondary)
.hover(move |style| style.bg(palette.row_hover))
.on_click(cx.listener(move |_host, _event, _window, cx| {
clear_input.update(cx, |input, cx| input.set_text("", cx));
cx.notify();
}))
.child("\u{2715}"),
)
})
}
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 phase = 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 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| {
let o = bounds.origin;
let centre = point(o.x + px(size / 2.0), o.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.to_string()))
}
#[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);
}
}