Pick a value from a range by dragging the thumb, clicking the track, or using the arrow keys.
use gpui::{div, prelude::*, px, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::slider::Slider;
pub struct VolumeSettings {
volume: f32,
}
// Starts at half volume, so `Default` is written out instead of derived.
impl Default for VolumeSettings {
fn default() -> Self {
Self { volume: 50.0 }
}
}
impl Render for VolumeSettings {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
div()
.flex()
.flex_col()
.gap_3()
.w(px(320.0))
.child(
div()
.flex()
.justify_between()
.text_sm()
.child("Volume")
.child(
div()
.text_color(theme.muted_foreground)
.child(format!("{}%", self.volume)),
),
)
.child(
Slider::new("volume", self.volume)
.max(100.0)
.step(5.0)
.on_change(cx.listener(|this, value: &f32, _, cx| {
this.volume = *value;
cx.notify();
})),
)
}
}Installation
Copies src/ui/slider.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/slider.rs.src/ui/slider.rs use std::rc::Rc; use gpui::{ div, prelude::*, px, relative, AnimationExt, App, Bounds, ElementId, EmptyView, FocusHandle, KeyDownEvent, MouseButton, Pixels, Point, SpringAnimation, SpringConfig, SpringPlayback, Window, }; use crate::theme::{focus_visible, ActiveTheme, FocusRing}; type ChangeHandler = Rc<dyn Fn(&f32, &mut Window, &mut App) + 'static>; type ValuesChangeHandler = Rc<dyn Fn(&Vec<f32>, &mut Window, &mut App) + 'static>; const THUMB: Pixels = px(16.0); const TRACK_HEIGHT: Pixels = px(6.0); const RING: Pixels = px(4.0); /// Critically damped and quick (~150ms), like shadcn's `transition-[color,box-shadow]`; also /// carries the thumb and fill to a clicked or keyed value. const EASE: SpringConfig = SpringConfig::new(900.0, 60.0, 1.0); /// The direction the track runs in. #[derive(Clone, Copy, Default, PartialEq)] pub enum SliderOrientation { /// Left to right, filling the parent's width. #[default] Horizontal, /// Bottom to top, filling the parent's height. Give the parent a height. Vertical, } /// A controlled slider: the parent view owns `value` and updates it in `on_change`. /// Drag the thumb, click the track, or use the arrow, Home and End keys once focused. /// Pass several values with `values` for a range or more thumbs. #[derive(IntoElement)] pub struct Slider { id: ElementId, values: Vec<f32>, min: f32, max: f32, step: f32, disabled: bool, orientation: SliderOrientation, focus_handle: Option<FocusHandle>, on_change: Option<ChangeHandler>, on_values_change: Option<ValuesChangeHandler>, } /// Drag payload. `on_drag_move` fires for every listener of this type, so the id /// keeps one slider's drag from moving the others on the page. struct SliderDrag(ElementId); /// Kept across frames because a mouse-down event carries no element bounds: the /// last laid-out track bounds are what turn a click position into a value. struct SliderState { track: Bounds<Pixels>, focus: FocusHandle, /// The thumb that the last click or drag grabbed, and that the keyboard moves. active: usize, /// The thumb under the pointer, which shows its ring. hovered: Option<usize>, } #[derive(Clone, Copy)] struct Scale { min: f32, max: f32, step: f32, vertical: bool, } impl Scale { fn fraction(self, value: f32) -> f32 { if self.max <= self.min { return 0.0; } ((value - self.min) / (self.max - self.min)).clamp(0.0, 1.0) } fn snap(self, value: f32) -> f32 { if self.max <= self.min { return self.min; } let value = value.clamp(self.min, self.max); if self.step <= 0.0 { return value; } let snapped = self.min + ((value - self.min) / self.step).round() * self.step; snapped.clamp(self.min, self.max) } /// The thumb travels `length - THUMB` so it never overhangs the track ends; the /// pointer maps over the same span so the thumb stays centered under the cursor. /// Vertical sliders put `min` at the bottom. fn value_at(self, position: Point<Pixels>, track: Bounds<Pixels>) -> f32 { let (length, offset) = if self.vertical { (track.size.height, track.bottom() - position.y - THUMB / 2.0) } else { (track.size.width, position.x - track.origin.x - THUMB / 2.0) }; let span = f32::from(length - THUMB); if span <= 0.0 { return self.min; } let offset = f32::from(offset); self.snap(self.min + (offset / span).clamp(0.0, 1.0) * (self.max - self.min)) } } /// The thumb a click at `value` should grab: the nearest one. Among thumbs stacked on the /// same value, a click above them takes the last and a click below takes the first, so /// they can always be pulled apart. fn nearest_thumb(values: &[f32], value: f32) -> usize { let mut best = 0; for (ix, &thumb) in values.iter().enumerate() { let distance = (thumb - value).abs(); let best_distance = (values[best] - value).abs(); if distance < best_distance || (distance == best_distance && value > thumb) { best = ix; } } best } impl Slider { pub fn new(id: impl Into<ElementId>, value: f32) -> Self { Self { id: id.into(), values: vec![value], min: 0.0, max: 100.0, step: 1.0, disabled: false, orientation: SliderOrientation::default(), focus_handle: None, on_change: None, on_values_change: None, } } /// Replaces the single value with one thumb per value, in ascending order. Two values /// make a range slider and the track fills between them. A thumb can't be dragged past /// its neighbours. Read changes with `on_values_change`. pub fn values(mut self, values: impl IntoIterator<Item = f32>) -> Self { let values: Vec<f32> = values.into_iter().collect(); if !values.is_empty() { self.values = values; } self } pub fn min(mut self, min: f32) -> Self { self.min = min; self } pub fn max(mut self, max: f32) -> Self { self.max = max; self } /// Values snap to multiples of `step` from `min`. Zero or less disables snapping. pub fn step(mut self, step: f32) -> Self { self.step = step; self } pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; self } /// Runs the track horizontally (the default) or vertically, with `min` at the bottom. pub fn orientation(mut self, orientation: SliderOrientation) -> Self { self.orientation = orientation; self } /// Receives the next value, already snapped and clamped. Only called when it changes. /// With several thumbs it receives the value of the thumb that moved. /// Focus the slider through this handle, such as `form.focus_handle(..)` or one from /// `cx.focus_handle()`, to move focus to it from code. Without one it keeps its own. pub fn focus_handle(mut self, handle: FocusHandle) -> Self { self.focus_handle = Some(handle); self } pub fn on_change(mut self, handler: impl Fn(&f32, &mut Window, &mut App) + 'static) -> Self { self.on_change = Some(Rc::new(handler)); self } /// Receives every thumb's value, in order, whenever one of them changes. pub fn on_values_change( mut self, handler: impl Fn(&Vec<f32>, &mut Window, &mut App) + 'static, ) -> Self { self.on_values_change = Some(Rc::new(handler)); self } } impl RenderOnce for Slider { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let vertical = self.orientation == SliderOrientation::Vertical; let scale = Scale { min: self.min, max: self.max, step: self.step, vertical, }; let values = Rc::new(self.values); let disabled = self.disabled; let state = window.use_keyed_state(self.id.clone(), cx, |_, cx| SliderState { track: Bounds::default(), focus: cx.focus_handle(), active: 0, hovered: None, }); let (focus, active, hovered) = { let state = state.read(cx); (state.focus.clone(), state.active.min(values.len() - 1), state.hovered) }; let focus = self.focus_handle.unwrap_or(focus).tab_stop(!disabled); // Like CSS `:focus-visible`: for keyboard use and after the form moves focus here. let keyboard_focused = focus_visible(&focus, window, cx); let theme = cx.theme(); let ring = theme.ring.opacity(0.5); let primary = theme.primary; // Clicks and keys glide the thumb and fill to the new value; a drag follows the pointer // exactly. let playback = if cx.has_active_drag() { SpringPlayback::Completed } else { SpringPlayback::Running }; let glide = move |to: f32| SpringAnimation::new(EASE).to(to).playback(playback); // A lone thumb fills from `min`; several fill between the outermost thumbs. let (fill_from, fill_to) = if values.len() == 1 { (0.0, scale.fraction(values[0])) } else { let lowest = values.iter().copied().fold(f32::INFINITY, f32::min); let highest = values.iter().copied().fold(f32::NEG_INFINITY, f32::max); (scale.fraction(lowest), scale.fraction(highest)) }; // Moves one thumb, kept between its neighbours. Only real changes are reported, so a // drag that stays on one step doesn't re-render the parent. let has_handler = self.on_change.is_some() || self.on_values_change.is_some(); let emit = (has_handler && !disabled).then(|| { let on_change = self.on_change; let on_values_change = self.on_values_change; let values = values.clone(); Rc::new(move |thumb: usize, next: f32, window: &mut Window, cx: &mut App| { let low = thumb.checked_sub(1).map_or(scale.min, |ix| values[ix]); let high = values.get(thumb + 1).copied().unwrap_or(scale.max); let next = next.clamp(low, high); if next == values[thumb] { return; } if let Some(handler) = &on_change { handler(&next, window, cx); } if let Some(handler) = &on_values_change { let mut all = (*values).clone(); all[thumb] = next; handler(&all, window, cx); } }) }); // The ring is its own circle behind the thumb: a spread box shadow keeps the // thumb's corner radius and comes out as a rounded square. It grows in on hover or // keyboard focus. let thumbs = values.iter().enumerate().map(|(ix, &value)| { let fraction = scale.fraction(value); let ringed = !disabled && (hovered == Some(ix) || (keyboard_focused && ix == active)); let state = state.clone(); div() .id(("thumb", ix)) .absolute() .size(THUMB) .on_hover(move |hovered, _, cx| { state.update(cx, |state, cx| { let next = match *hovered { true => Some(ix), false if state.hovered == Some(ix) => None, false => state.hovered, }; if state.hovered != next { state.hovered = next; cx.notify(); } }) }) .child(div().with_spring( "ring", SpringAnimation::new(EASE).to(ringed), move |this, phase| { let spread = RING * phase.interpolate_clamped(0.0, 1.0); this.absolute() .top(-spread) .left(-spread) .size(THUMB + spread * 2.0) .rounded_full() .bg(ring) }, )) .child( div() .absolute() .top_0() .left_0() .size(THUMB) .rounded_full() .border_1() .border_color(primary) .bg(theme.background) .shadow_sm(), ) .with_spring(("thumb-at", ix), glide(fraction), move |this, fraction| { if vertical { this.left_0().top(relative(1.0 - fraction)) } else { this.top_0().left(relative(fraction)) } }) }); // Each end of the fill glides with its thumb. let fill = div().absolute().top_0().left_0().size_full().with_spring( "fill-from", glide(fill_from), move |this, from| { this.child(div().absolute().rounded_full().bg(primary).with_spring( "fill-to", glide(fill_to), move |this, to| { let length = relative((to - from).max(0.0)); if vertical { this.left_0().right_0().bottom(relative(from)).h(length) } else { this.top_0().bottom_0().left(relative(from)).w(length) } }, )) }, ); let track = div() .relative() .rounded_full() .bg(theme.muted) .when(vertical, |this| this.h_full().w(TRACK_HEIGHT)) .when(!vertical, |this| this.w_full().h(TRACK_HEIGHT)) .child(fill); // Inset by one thumb so `relative(fraction)` lands the thumb's leading edge on // `fraction * (length - THUMB)`, keeping it inside the track at both ends. let thumb_lane = div() .absolute() .top_0() .left_0() .when(vertical, |this| this.right_0().bottom(THUMB)) .when(!vertical, |this| this.bottom_0().right(THUMB)) .children(thumbs); div() .on_children_prepainted({ let state = state.clone(); move |bounds, _, cx| { if let Some(track) = bounds.first().copied() { state.update(cx, |state, _| state.track = track); } } }) .id(self.id.clone()) .when(!disabled, |this| this.track_focus(&focus).end_visible_focus_on_press(&focus, cx)) .relative() .flex() .items_center() .justify_center() .when(vertical, |this| this.h_full().w(THUMB).flex_col()) .when(!vertical, |this| this.w_full().h(THUMB)) .when(disabled, |this| this.opacity(0.5).cursor_not_allowed()) .when(!disabled, |this| this.cursor_pointer()) .child(track) .child(thumb_lane) .when_some(emit, |this, emit| { let id = self.id.clone(); this.on_mouse_down(MouseButton::Left, { let emit = emit.clone(); let state = state.clone(); let values = values.clone(); move |event, window, cx| { let track = state.read(cx).track; let next = scale.value_at(event.position, track); let thumb = nearest_thumb(&values, next); state.update(cx, |state, _| state.active = thumb); emit(thumb, next, window, cx); } }) .on_drag(SliderDrag(id.clone()), |_, _, _, cx| cx.new(|_| EmptyView)) .on_drag_move::<SliderDrag>({ let emit = emit.clone(); let state = state.clone(); move |event, window, cx| { if event.drag(cx).0 == id { let thumb = state.read(cx).active; emit(thumb, scale.value_at(event.event.position, event.bounds), window, cx); } } }) .on_key_down(move |event: &KeyDownEvent, window, cx| { let value = values[active]; let step = if scale.step > 0.0 { scale.step } else { (scale.max - scale.min) / 100.0 }; let next = match event.keystroke.key.as_str() { "left" | "down" => value - step, "right" | "up" => value + step, "pagedown" => value - step * 10.0, "pageup" => value + step * 10.0, "home" => scale.min, "end" => scale.max, "tab" if values.len() > 1 => { // Tab walks the thumbs before leaving the slider. let next = if event.keystroke.modifiers.shift { active.checked_sub(1) } else { Some(active + 1).filter(|&ix| ix < values.len()) }; let Some(next) = next else { return }; cx.stop_propagation(); state.update(cx, |state, _| state.active = next); window.refresh(); return; } _ => return, }; cx.stop_propagation(); emit(active, scale.snap(next), window, cx); }) }) } }Register the module
// src/ui/mod.rs pub mod slider;
Usage
use crate::ui::slider::*;Examples
Range
Pass two values to values for a range slider. The track fills between the thumbs.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::slider::Slider;
pub struct SliderRange {
values: Vec<f32>,
}
// Starts with a range already picked, so `Default` is written out instead of derived.
impl Default for SliderRange {
fn default() -> Self {
Self { values: vec![25.0, 50.0] }
}
}
impl Render for SliderRange {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(320.0)).child(
Slider::new("slider-range", 0.0)
.values(self.values.clone())
.step(5.0)
.on_values_change(cx.listener(|this, values: &Vec<f32>, _, cx| {
this.values = values.clone();
cx.notify();
})),
)
}
}Multiple Thumbs
values takes any number of thumbs. Clicking the track moves the nearest one, and no thumb can pass its neighbours.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::slider::Slider;
pub struct SliderMultipleThumbs {
values: Vec<f32>,
}
// Starts with three thumbs spread out, so `Default` is written out instead of derived.
impl Default for SliderMultipleThumbs {
fn default() -> Self {
Self { values: vec![10.0, 20.0, 70.0] }
}
}
impl Render for SliderMultipleThumbs {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(320.0)).child(
Slider::new("slider-multiple", 0.0)
.values(self.values.clone())
.step(10.0)
.on_values_change(cx.listener(|this, values: &Vec<f32>, _, cx| {
this.values = values.clone();
cx.notify();
})),
)
}
}Vertical
SliderOrientation::Vertical runs the track bottom to top and fills the parent's height.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::slider::{Slider, SliderOrientation};
pub struct SliderVertical {
level: f32,
range: Vec<f32>,
}
// Starts part way up, so `Default` is written out instead of derived.
impl Default for SliderVertical {
fn default() -> Self {
Self {
level: 50.0,
range: vec![25.0, 75.0],
}
}
}
impl Render for SliderVertical {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.gap_12()
.h(px(160.0))
.child(
Slider::new("slider-vertical", self.level)
.orientation(SliderOrientation::Vertical)
.on_change(cx.listener(|this, value: &f32, _, cx| {
this.level = *value;
cx.notify();
})),
)
.child(
Slider::new("slider-vertical-range", 0.0)
.values(self.range.clone())
.orientation(SliderOrientation::Vertical)
.on_values_change(cx.listener(|this, values: &Vec<f32>, _, cx| {
this.range = values.clone();
cx.notify();
})),
)
}
}Controlled
The view owns the values and shows them beside the label as the thumbs move.
use gpui::{div, prelude::*, px, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::slider::Slider;
pub struct SliderControlled {
temperature: Vec<f32>,
}
// Starts at a 0.3 to 0.7 range, so `Default` is written out instead of derived.
impl Default for SliderControlled {
fn default() -> Self {
Self { temperature: vec![0.3, 0.7] }
}
}
impl Render for SliderControlled {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let shown = self
.temperature
.iter()
.map(|value| format!("{value:.1}"))
.collect::<Vec<_>>()
.join(", ");
div()
.flex()
.flex_col()
.gap_3()
.w(px(320.0))
.child(
div()
.flex()
.justify_between()
.text_sm()
.child(div().font_weight(FontWeight::MEDIUM).child("Temperature"))
.child(div().text_color(theme.muted_foreground).child(shown)),
)
.child(
Slider::new("slider-controlled", 0.0)
.values(self.temperature.clone())
.max(1.0)
.step(0.1)
.on_values_change(cx.listener(|this, values: &Vec<f32>, _, cx| {
this.temperature = values.clone();
cx.notify();
})),
)
}
}Disabled
disabled(true) dims the slider and ignores pointer and keyboard input.
use gpui::{div, prelude::*, px};
use crate::ui::slider::Slider;
pub fn slider_disabled() -> impl IntoElement {
div()
.w(px(320.0))
.child(Slider::new("slider-disabled", 50.0).disabled(true))
}API Reference
SliderOrientation
The direction the track runs in.
SliderOrientation::HorizontalLeft to right, filling the parent's width.
SliderOrientation::VerticalBottom to top, filling the parent's height. Give the parent a height.
Slider
A controlled slider: the parent view owns value and updates it in on_change. Drag the thumb, click the track, or use the arrow, Home and End keys once focused. Pass several values with values for a range or more thumbs.
Slider::new(id: impl Into<ElementId>, value: f32) -> Self.values(values: impl IntoIterator<Item = f32>)Replaces the single value with one thumb per value, in ascending order. Two values make a range slider and the track fills between them. A thumb can't be dragged past its neighbours. Read changes with on_values_change.
.min(min: f32).max(max: f32).step(step: f32)Values snap to multiples of step from min. Zero or less disables snapping.
.disabled(disabled: bool).orientation(orientation: SliderOrientation)Runs the track horizontally (the default) or vertically, with min at the bottom.
.focus_handle(handle: FocusHandle)Receives the next value, already snapped and clamped. Only called when it changes. With several thumbs it receives the value of the thumb that moved. Focus the slider through this handle, such as form.focus_handle(..) or one from cx.focus_handle(), to move focus to it from code. Without one it keeps its own.
.on_change(handler: impl Fn(&f32, &mut Window, &mut App) + 'static).on_values_change(handler: impl Fn(&Vec<f32>, &mut Window, &mut App) + 'static)Receives every thumb's value, in order, whenever one of them changes.