use std::{cell::RefCell, rc::Rc};
use arc_motion::{
ArcPresence, ArcPresenceConfig, BlurFallback, DragTracker, Transform2D, TransformOrigin,
arc_spring, arc_spring_with_options, arc_transition, is_reduced_motion, motion_now,
rubber_band_signed, scaled_bounds, spring::SpringOptions,
};
use arc_tokens::{
ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix,
};
use gpui_kit::{
App, BorderStyle, Bounds, Edges, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
MouseButton, MouseMoveEvent, MouseUpEvent, Orientation, ParentElement, Pixels, RenderOnce,
Role, SharedString, Styled, TestSupportExt as _, Window, assets::IconName, bounds, canvas, div,
point, prelude::*, px, quad, size,
};
const THUMB_SIZE: f32 = 18.0;
const TRACK_HEIGHT: f32 = 6.0;
const STRETCH: f32 = 22.0;
const DETENT_PX: f32 = 7.0;
const BUMP_PX: f32 = 260.0;
const LINGER_SECS: f64 = 0.7;
type ValueHandler = Rc<dyn Fn(&f32, &mut Window, &mut App)>;
type Formatter = Rc<dyn Fn(f32) -> SharedString>;
#[derive(Clone, Debug, PartialEq)]
pub struct ElasticSliderMark {
pub value: f32,
pub label: Option<SharedString>,
}
impl ElasticSliderMark {
pub fn new(value: f32) -> Self {
Self { value, label: None }
}
pub fn labelled(value: f32, label: impl Into<SharedString>) -> Self {
Self {
value,
label: Some(label.into()),
}
}
}
#[derive(Clone)]
struct ElasticSliderState {
uncontrolled_value: f32,
dragging: bool,
keyed: bool,
linger_until_secs: f64,
drag_raw_pct: f32,
drag_over_px: f32,
grab_offset_pct: f32,
active_detent: Option<f32>,
tracker: DragTracker,
pos_impulse: Option<f32>,
over_impulse: Option<f32>,
pulsed_mark: Option<(f32, f64)>,
rail_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
focus_handle: FocusHandle,
}
impl ElasticSliderState {
fn new(initial: f32, focus_handle: FocusHandle) -> Self {
Self {
uncontrolled_value: initial,
dragging: false,
keyed: false,
linger_until_secs: f64::NEG_INFINITY,
drag_raw_pct: 0.0,
drag_over_px: 0.0,
grab_offset_pct: 0.0,
active_detent: None,
tracker: DragTracker::new(0.0),
pos_impulse: None,
over_impulse: None,
pulsed_mark: None,
rail_bounds: Rc::new(RefCell::new(None)),
focus_handle,
}
}
}
fn decimal_places(step: f32) -> usize {
let s = format!("{step}");
s.split('.')
.nth(1)
.map_or(0, |frac| frac.trim_end_matches('0').len())
}
fn snap_value(input: f32, min: f32, max: f32, step: f32) -> f32 {
let step = if step > 0.0 { step } else { 1.0 };
let decimals = decimal_places(step).max(decimal_places(min));
let factor = 10.0_f32.powi(decimals as i32);
let snapped = min + ((input - min) / step).round() * step;
((snapped * factor).round() / factor).clamp(min, max)
}
fn pct_of(value: f32, min: f32, span: f32) -> f32 {
(((value - min) / span) * 100.0).clamp(0.0, 100.0)
}
fn detent_at(
percent: f32,
min: f32,
span: f32,
width: f32,
marks: &[ElasticSliderMark],
) -> Option<f32> {
let mut best = None;
let mut best_gap = DETENT_PX + 1.0;
for mark in marks {
let mark_pct = pct_of(mark.value, min, span);
let dist = ((percent - mark_pct) / 100.0 * width).abs();
if dist <= DETENT_PX && dist < best_gap {
best = Some(mark.value);
best_gap = dist;
}
}
best
}
#[derive(IntoElement)]
pub struct ElasticSlider {
id: ElementId,
label: SharedString,
value: Option<f32>,
default_value: Option<f32>,
min: f32,
max: f32,
step: f32,
large_step: Option<f32>,
marks: Vec<ElasticSliderMark>,
format: Option<Formatter>,
show_value: bool,
start_icon: Option<IconName>,
end_icon: Option<IconName>,
disabled: bool,
on_value_change: Option<ValueHandler>,
on_value_commit: Option<ValueHandler>,
}
impl ElasticSlider {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
value: None,
default_value: None,
min: 0.0,
max: 100.0,
step: 1.0,
large_step: None,
marks: Vec::new(),
format: None,
show_value: true,
start_icon: None,
end_icon: None,
disabled: false,
on_value_change: None,
on_value_commit: None,
}
}
pub fn value(mut self, value: f32) -> Self {
self.value = Some(value);
self
}
pub fn default_value(mut self, default_value: f32) -> Self {
self.default_value = Some(default_value);
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
}
pub fn step(mut self, step: f32) -> Self {
self.step = if step > 0.0 { step } else { 1.0 };
self
}
pub fn large_step(mut self, large_step: f32) -> Self {
self.large_step = Some(large_step);
self
}
pub fn marks(mut self, marks: impl IntoIterator<Item = ElasticSliderMark>) -> Self {
self.marks = marks.into_iter().collect();
self
}
pub fn format(mut self, formatter: impl Fn(f32) -> SharedString + 'static) -> Self {
self.format = Some(Rc::new(formatter));
self
}
pub fn show_value(mut self, show_value: bool) -> Self {
self.show_value = show_value;
self
}
pub fn start_icon(mut self, icon: IconName) -> Self {
self.start_icon = Some(icon);
self
}
pub fn end_icon(mut self, icon: IconName) -> Self {
self.end_icon = Some(icon);
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn on_value_change(
mut self,
handler: impl Fn(&f32, &mut Window, &mut App) + 'static,
) -> Self {
self.on_value_change = Some(Rc::new(handler));
self
}
pub fn on_value_commit(
mut self,
handler: impl Fn(&f32, &mut Window, &mut App) + 'static,
) -> Self {
self.on_value_commit = Some(Rc::new(handler));
self
}
}
impl RenderOnce for ElasticSlider {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let min = self.min;
let max = self.max;
let step = if self.step > 0.0 { self.step } else { 1.0 };
let span = if (max - min).abs() > f32::EPSILON {
max - min
} else {
1.0
};
let decimals = decimal_places(step).max(decimal_places(min));
let initial = self.default_value.unwrap_or(min).clamp(min, max);
let valid_marks: Vec<ElasticSliderMark> = self
.marks
.into_iter()
.filter(|m| m.value >= min && m.value <= max)
.collect();
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-elastic-slider-state".into());
let state = window.use_keyed_state(state_id, cx, |_, cx| {
ElasticSliderState::new(initial, cx.focus_handle())
});
let snapshot = state.read(cx).clone();
let current = self
.value
.unwrap_or(snapshot.uncontrolled_value)
.clamp(min, max);
let is_controlled = self.value.is_some();
let thumb_spring = motion.spring.snappy.as_physical();
let snap_back_spring = SpringSpec::visual(0.5, 0.42).as_physical();
let bubble_trail_spring = SpringSpec::physics_with_mass(420.0, 30.0, 0.7);
let rail_width = snapshot
.rail_bounds
.borrow()
.map_or(240.0_f32, |b| f32::from(b.size.width).max(1.0));
let target_pct = if snapshot.dragging {
snapshot.drag_raw_pct
} else {
pct_of(current, min, span)
};
let target_over = if snapshot.dragging && !reduced {
snapshot.drag_over_px
} else {
0.0
};
let pos_impulse = snapshot.pos_impulse;
let over_impulse = snapshot.over_impulse;
if pos_impulse.is_some() || over_impulse.is_some() {
state.update(cx, |s, _| {
s.pos_impulse = None;
s.over_impulse = None;
});
}
let mut pos_opts = SpringOptions::new(thumb_spring)
.with_travel(!snapshot.dragging || snapshot.active_detent.is_some())
.with_rest_thresholds(0.002, 0.02);
if let Some(v) = pos_impulse {
pos_opts = pos_opts.with_initial_velocity(v);
}
let pos_sample =
arc_spring_with_options((self.id.clone(), "pos"), target_pct, pos_opts, window, cx);
let shown_pct = pos_sample.value.clamp(0.0, 100.0);
let mut over_opts = SpringOptions::new(snap_back_spring)
.with_travel(!snapshot.dragging)
.with_rest_thresholds(0.05, 0.5);
if let Some(v) = over_impulse {
over_opts = over_opts.with_initial_velocity(v);
}
let over_sample = arc_spring_with_options(
(self.id.clone(), "over"),
target_over,
over_opts,
window,
cx,
);
let over_px = if reduced { 0.0 } else { over_sample.value };
let press = arc_spring(
(self.id.clone(), "press"),
if snapshot.dragging { 1.0 } else { 0.0 },
motion.spring.snappy,
window,
cx,
);
let thumb_scale = arc_spring(
(self.id.clone(), "thumb-scale"),
if snapshot.dragging && !reduced {
1.28
} else {
1.0
},
motion.spring.snappy,
window,
cx,
);
let trail_sample = arc_spring_with_options(
(self.id.clone(), "bubble-trail"),
shown_pct,
SpringOptions::new(bubble_trail_spring).with_travel(!reduced),
window,
cx,
);
let bubble_at_pct = if reduced {
shown_pct
} else {
trail_sample.value.clamp(0.0, 100.0)
};
let bubble_rotate_deg = if reduced {
0.0
} else {
((-trail_sample.velocity / 100.0) * rail_width * 0.009).clamp(-11.0, 11.0)
};
let bubble_swing = Transform2D::IDENTITY
.rotate_deg(bubble_rotate_deg)
.origin(TransformOrigin::new(0.5, 1.3))
.pivot_swing_offset(px(28.0));
let linger_active = now < snapshot.linger_until_secs;
if linger_active {
window.request_animation_frame();
}
let bubble_visible = snapshot.dragging || snapshot.keyed || linger_active;
let bubble_presence =
ArcPresence::new((self.id.clone(), "bubble-presence"), bubble_visible)
.animate_initial(false)
.config(ArcPresenceConfig {
enter_duration: motion.duration.fast,
enter_ease: motion.ease.enter,
exit_duration: motion.duration.instant,
exit_ease: motion.ease.standard,
fade_on_reduced_motion: true,
})
.sample(window, cx);
let bubble_blur = BlurFallback::evaluate(
px((1.0 - bubble_presence.progress) * f32::from(motion.blur.subtle)),
reduced,
);
let readout_opacity = arc_transition(
(self.id.clone(), "readout-opacity"),
if bubble_visible { 0.0 } else { 1.0 },
motion.duration.fast,
motion.ease.standard,
window,
cx,
);
let scale_x = 1.0 + over_px.abs() / rail_width;
let scale_y = (1.0 + press * 0.45) * (1.0 - (over_px.abs() / STRETCH) * 0.32);
let track_origin = if over_px < 0.0 {
TransformOrigin::RIGHT_CENTER
} else {
TransformOrigin::LEFT_CENTER
};
let start_shift = over_px.min(0.0);
let end_shift = over_px.max(0.0);
let formatted: SharedString = if let Some(fmt) = &self.format {
fmt(current)
} else {
SharedString::from(format!("{current:.decimals$}"))
};
let disabled = self.disabled;
let marks_rc = Rc::new(valid_marks.clone());
let on_change_rc = self.on_value_change.clone();
let on_commit_rc = self.on_value_commit.clone();
let state_down = state.clone();
let marks_down = marks_rc.clone();
let on_change_down = on_change_rc.clone();
let focus_down = snapshot.focus_handle.clone();
let state_move = state.clone();
let marks_move = marks_rc.clone();
let on_change_move = on_change_rc.clone();
let state_up = state.clone();
let on_change_up = on_change_rc.clone();
let on_commit_up = on_commit_rc.clone();
let state_key = state.clone();
let marks_key = marks_rc.clone();
let on_change_key = on_change_rc.clone();
let on_commit_key = on_commit_rc.clone();
let large_step = self
.large_step
.unwrap_or_else(|| step.max(snap_value(min + span / 10.0, min, max, step) - min));
let rail_bounds_ref = snapshot.rail_bounds.clone();
let track_color = colors.control_track;
let fill_color = colors.control_fill;
let tick_off_color = oklab_mix(colors.foreground, Hsla::transparent_black(), 0.32);
let tick_on_color = oklab_mix(colors.control_glyph, Hsla::transparent_black(), 0.60);
let inner_marks: Vec<f32> = valid_marks
.iter()
.filter(|m| m.value > min && m.value < max)
.map(|m| m.value)
.collect();
let pulsed_mark = snapshot.pulsed_mark;
let is_dragging = snapshot.dragging;
let track_canvas = canvas(
move |rect, _, _| {
*rail_bounds_ref.borrow_mut() = Some(rect);
},
move |rect, _, window, _| {
if is_dragging && !disabled {
let st_move = state_move.clone();
let mk_move = marks_move.clone();
let ch_move = on_change_move.clone();
window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
if !phase.bubble() || !st_move.read(cx).dragging {
return;
}
let Some(rail_rect) = *st_move.read(cx).rail_bounds.borrow() else {
return;
};
let w = f32::from(rail_rect.size.width).max(1.0);
let now_move = motion_now(cx);
let at_pct =
((f32::from(event.position.x) - f32::from(rail_rect.origin.x)) / w)
* 100.0;
let prev_detent = st_move.read(cx).active_detent;
let prev_val = if is_controlled {
current
} else {
st_move.read(cx).uncontrolled_value
};
let grab = st_move.read(cx).grab_offset_pct;
let raw = at_pct - grab;
let edge = raw.clamp(0.0, 100.0);
let over = if is_reduced_motion(cx) {
0.0
} else {
rubber_band_signed((raw - edge) / 100.0 * w, STRETCH)
};
let detent = detent_at(edge, min, span, w, &mk_move);
let placed = detent.map_or(edge, |d| pct_of(d, min, span));
let next_val = detent.unwrap_or_else(|| {
snap_value(min + (edge / 100.0) * span, min, max, step)
});
st_move.update(cx, |s, _| {
s.drag_raw_pct = placed;
s.drag_over_px = over;
if detent != prev_detent
&& let Some(d) = detent
{
s.pulsed_mark = Some((d, now_move));
}
s.active_detent = detent;
s.tracker.update_x(placed, 0.0, now_move, false);
if !is_controlled {
s.uncontrolled_value = next_val;
}
});
if (next_val - prev_val).abs() > f32::EPSILON
&& let Some(handler) = &ch_move
{
handler(&next_val, window, cx);
}
window.refresh();
});
let st_up = state_up.clone();
let ch_up = on_change_up.clone();
let cm_up = on_commit_up.clone();
window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
if !phase.bubble()
|| event.button != MouseButton::Left
|| !st_up.read(cx).dragging
{
return;
}
let now_up = motion_now(cx);
let (next_val, vel) = {
let s = st_up.read(cx);
let v = s.tracker.release_velocity(now_up);
let next = s.active_detent.unwrap_or_else(|| {
snap_value(min + (s.drag_raw_pct / 100.0) * span, min, max, step)
});
(next, v)
};
st_up.update(cx, |s, _| {
s.dragging = false;
s.linger_until_secs = now_up + LINGER_SECS;
s.pos_impulse = Some(vel);
s.drag_over_px = 0.0;
if !is_controlled {
s.uncontrolled_value = next_val;
}
});
if let Some(handler) = &ch_up {
handler(&next_val, window, cx);
}
if let Some(handler) = &cm_up {
handler(&next_val, window, cx);
}
window.refresh();
});
}
let stretched = scaled_bounds(rect, scale_x, scale_y, track_origin);
window.paint_quad(quad(
stretched,
Radii::pill_for_size(stretched.size),
track_color,
Edges::default(),
Hsla::transparent_black(),
BorderStyle::Solid,
));
let fill_w = (f32::from(stretched.size.width) * (shown_pct / 100.0)).max(0.0);
if fill_w > 0.5 {
let fill_rect =
bounds(stretched.origin, size(px(fill_w), stretched.size.height));
window.paint_quad(quad(
fill_rect,
Radii::pill_for_size(fill_rect.size),
fill_color,
Edges::default(),
Hsla::transparent_black(),
BorderStyle::Solid,
));
}
let rail_w = f32::from(rect.size.width);
let mid_y = f32::from(rect.origin.y) + f32::from(rect.size.height) * 0.5;
for &m_val in &inner_marks {
let m_pct = pct_of(m_val, min, span);
let mut tick_scale = 1.0_f32;
if let Some((pm, started)) = pulsed_mark
&& !reduced
&& (pm - m_val).abs() < 1e-4
{
let dt = (now - started).max(0.0);
if dt < 0.34 {
let u = (dt / 0.34) as f32;
tick_scale = 1.0 + 1.1 * (u * std::f32::consts::PI).sin();
window.request_animation_frame();
}
}
let d = 4.0 * tick_scale;
let cx_pos = f32::from(rect.origin.x) + rail_w * (m_pct / 100.0);
let tick_rect = bounds(
point(px(cx_pos - d * 0.5), px(mid_y - d * 0.5)),
size(px(d), px(d)),
);
let col = if m_val <= current {
tick_on_color
} else {
tick_off_color
};
window.paint_quad(quad(
tick_rect,
Radii::pill_for_size(tick_rect.size),
col,
Edges::default(),
Hsla::transparent_black(),
BorderStyle::Solid,
));
}
},
)
.w_full()
.h(px(TRACK_HEIGHT));
let thumb_px_size = THUMB_SIZE * thumb_scale;
let thumb_center_x = (THUMB_SIZE * 0.5) + rail_width * (shown_pct / 100.0) + over_px;
let bubble_min_x = 24.0_f32.min((rail_width + THUMB_SIZE) * 0.5);
let bubble_max_x = (rail_width + THUMB_SIZE - 24.0).max(bubble_min_x);
let bubble_center_x = ((THUMB_SIZE * 0.5) + rail_width * (bubble_at_pct / 100.0) + over_px)
.clamp(bubble_min_x, bubble_max_x)
+ f32::from(bubble_swing.x);
let bubble_y_offset =
(1.0 - bubble_presence.progress) * 6.0 + f32::from(bubble_blur.offset_y);
let bubble_opacity =
(bubble_presence.progress * bubble_blur.opacity_multiplier).clamp(0.0, 1.0);
let labelled_marks: Vec<ElasticSliderMark> = valid_marks
.iter()
.filter(|m| m.label.is_some())
.cloned()
.collect();
let thumb_id = ElementId::NamedChild(self.id.clone().into(), "thumb".into());
let control_id = ElementId::NamedChild(self.id.clone().into(), "control".into());
let focus_handle = snapshot.focus_handle.clone();
let is_focused = focus_handle.is_focused(window);
let focus_outline = colors.focus_outline;
let control_row = div()
.id(control_id)
.test_support()
.relative()
.flex_1()
.h(ControlHeights::MD)
.flex()
.items_center()
.when(!disabled, |this| {
this.cursor(if snapshot.dragging {
gpui_kit::CursorStyle::ClosedHand
} else {
gpui_kit::CursorStyle::PointingHand
})
})
.on_mouse_down(MouseButton::Left, move |event, window, cx| {
if disabled {
return;
}
let Some(rect) = *state_down.read(cx).rail_bounds.borrow() else {
return;
};
let w = f32::from(rect.size.width).max(1.0);
let at_pct = ((f32::from(event.position.x) - f32::from(rect.origin.x)) / w) * 100.0;
let now_down = motion_now(cx);
let current_val = if is_controlled {
current
} else {
state_down.read(cx).uncontrolled_value
};
let from_pct = pct_of(current_val, min, span);
let grabbed_thumb = ((at_pct - from_pct) / 100.0 * w).abs() <= THUMB_SIZE * 0.75;
let grab = if grabbed_thumb {
at_pct - from_pct
} else {
0.0
};
let raw = at_pct - grab;
let edge = raw.clamp(0.0, 100.0);
let over = if is_reduced_motion(cx) {
0.0
} else {
rubber_band_signed((raw - edge) / 100.0 * w, STRETCH)
};
let detent = detent_at(edge, min, span, w, &marks_down);
let placed = detent.map_or(edge, |d| pct_of(d, min, span));
let next_val = detent
.unwrap_or_else(|| snap_value(min + (edge / 100.0) * span, min, max, step));
state_down.update(cx, |s, _| {
s.dragging = true;
s.keyed = false;
s.linger_until_secs = f64::NEG_INFINITY;
s.grab_offset_pct = grab;
s.drag_raw_pct = placed;
s.drag_over_px = over;
s.active_detent = detent;
s.tracker.begin(placed, 0.0, placed, now_down);
if !is_controlled {
s.uncontrolled_value = next_val;
}
});
window.focus(&focus_down, cx);
if (next_val - current_val).abs() > f32::EPSILON
&& let Some(handler) = &on_change_down
{
handler(&next_val, window, cx);
}
window.refresh();
})
.child(
div()
.w_full()
.px(px(THUMB_SIZE * 0.5))
.flex()
.items_center()
.child(track_canvas),
)
.when(bubble_presence.should_render(), |this| {
this.child(
div()
.absolute()
.left(px(bubble_center_x - 24.0))
.bottom(px(ControlHeights::MD.as_f32() * 0.5
+ THUMB_SIZE * 0.5
+ 10.0
- bubble_y_offset))
.min_w(px(48.0))
.h(px(28.0))
.px(Spacing::S3)
.flex()
.items_center()
.justify_center()
.rounded(Radii::PILL)
.bg(colors.foreground)
.text_color(colors.background)
.text_size(Typography::TEXT_SM)
.shadow(Shadows::raised(theme.mode))
.opacity(bubble_opacity)
.child(formatted.clone()),
)
})
.child(
div()
.id(thumb_id)
.test_support()
.track_focus(&focus_handle.tab_stop(!disabled))
.role(Role::Slider)
.aria_label(self.label.clone())
.aria_min_numeric_value(f64::from(min))
.aria_max_numeric_value(f64::from(max))
.aria_numeric_value(f64::from(current))
.aria_numeric_value_step(f64::from(step))
.aria_value(formatted.clone())
.aria_orientation(Orientation::Horizontal)
.absolute()
.left(px(thumb_center_x - thumb_px_size * 0.5))
.top(px((ControlHeights::MD.as_f32() - thumb_px_size) * 0.5))
.w(px(thumb_px_size))
.h(px(thumb_px_size))
.rounded(Radii::PILL)
.bg(colors.control_thumb)
.when(is_focused, |this| {
this.border_2().border_color(focus_outline)
})
.shadow(Shadows::control_thumb(theme.mode))
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if disabled {
return;
}
let now_val = if is_controlled {
current
} else {
state_key.read(cx).uncontrolled_value
};
let shift = event.keystroke.modifiers.shift;
let wanted = match event.keystroke.key.as_str() {
"right" | "up" => now_val + if shift { large_step } else { step },
"left" | "down" => now_val - if shift { large_step } else { step },
"pageup" => now_val + large_step,
"pagedown" => now_val - large_step,
"home" => min,
"end" => max,
_ => return,
};
let now_k = motion_now(cx);
let next = snap_value(wanted, min, max, step);
if (next - now_val).abs() <= f32::EPSILON {
let toward = (wanted - now_val).signum();
if toward != 0.0 && !is_reduced_motion(cx) {
state_key.update(cx, |s, _| {
s.keyed = true;
s.linger_until_secs = now_k + LINGER_SECS;
s.over_impulse = Some(toward * BUMP_PX);
});
window.refresh();
}
return;
}
state_key.update(cx, |s, _| {
s.keyed = true;
s.linger_until_secs = now_k + LINGER_SECS;
if !is_controlled {
s.uncontrolled_value = next;
}
if marks_key.iter().any(|m| (m.value - next).abs() < 1e-4) {
s.pulsed_mark = Some((next, now_k));
}
});
if let Some(handler) = &on_change_key {
handler(&next, window, cx);
}
if let Some(handler) = &on_commit_key {
handler(&next, window, cx);
}
window.refresh();
}),
);
let mut root = div()
.id(self.id.clone())
.w_full()
.flex()
.flex_col()
.gap(Spacing::S2)
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.when(disabled, |this| this.opacity(0.5))
.child(
div()
.w_full()
.flex()
.items_baseline()
.justify_between()
.gap(Spacing::S4)
.child(self.label.clone())
.when(self.show_value, |this| {
this.child(
div()
.text_color(colors.text_secondary)
.opacity(readout_opacity)
.child(formatted),
)
}),
)
.child(
div()
.w_full()
.flex()
.flex_row()
.items_center()
.when_some(self.start_icon, |this, icon| {
this.child(
div()
.mr(Spacing::S3)
.ml(px(start_shift))
.text_color(colors.text_muted)
.child(icon),
)
})
.child(control_row)
.when_some(self.end_icon, |this, icon| {
this.child(
div()
.ml(px(f32::from(Spacing::S3) + end_shift))
.text_color(colors.text_muted)
.child(icon),
)
}),
);
if !labelled_marks.is_empty() {
let mut marks_row = div()
.relative()
.w_full()
.h(px(20.0))
.px(px(THUMB_SIZE * 0.5))
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted);
for (idx, mark) in labelled_marks.into_iter().enumerate() {
let m_val = mark.value;
let m_label = mark.label.unwrap_or_default();
let is_on = (m_val - current).abs() < 1e-4;
let m_pct = pct_of(m_val, min, span);
let left_px = (THUMB_SIZE * 0.5) + rail_width * (m_pct / 100.0);
let st_click = state.clone();
let ch_click = self.on_value_change.clone();
let cm_click = self.on_value_commit.clone();
let mark_id = ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("mark-{idx}")),
);
marks_row = marks_row.child(
div()
.id(mark_id)
.test_support()
.absolute()
.top_0()
.left(px((left_px - 16.0).clamp(0.0, rail_width)))
.text_color(if is_on {
colors.foreground
} else {
colors.text_muted
})
.when(!disabled, |this| this.cursor_pointer())
.on_click(move |_, window, cx| {
if disabled {
return;
}
let now_m = motion_now(cx);
st_click.update(cx, |s, _| {
if !is_controlled {
s.uncontrolled_value = m_val;
}
s.pulsed_mark = Some((m_val, now_m));
});
if let Some(handler) = &ch_click {
handler(&m_val, window, cx);
}
if let Some(handler) = &cm_click {
handler(&m_val, window, cx);
}
window.refresh();
})
.child(m_label),
);
}
root = root.child(marks_row);
}
root
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, rc::Rc};
use arc_motion::{CurveTrace, SpringSolver, max_curve_error_pct, rubber_band_signed};
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, MouseButton, Render, Role, TestAppContext, div, point, px,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
struct SliderHost {
value: f32,
commits: Rc<Cell<usize>>,
}
impl Render for SliderHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let commits = self.commits.clone();
div().w(px(360.0)).p(Spacing::S6).child(
ElasticSlider::new("volume", "Volume")
.value(self.value)
.min(0.0)
.max(100.0)
.step(5.0)
.marks([
ElasticSliderMark::labelled(0.0, "0%"),
ElasticSliderMark::labelled(50.0, "50%"),
ElasticSliderMark::labelled(100.0, "100%"),
])
.on_value_change(cx.listener(|this, v: &f32, _, cx| {
this.value = *v;
cx.notify();
}))
.on_value_commit(cx.listener(move |_, _: &f32, _, _| {
commits.set(commits.get() + 1);
})),
)
}
}
#[gpui_kit::test]
fn elastic_slider_drag_keyboard_and_commit_work(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Blue, cx);
});
let commits = Rc::new(Cell::new(0usize));
let (view, cx) = cx.add_window_view(|_, _| SliderHost {
value: 20.0,
commits: commits.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let slider = window.find_by_label("Volume");
assert_eq!(slider.role(), Some(Role::Slider));
let control = window.find(ElementId::NamedChild(
ElementId::from("volume").into(),
"control".into(),
));
let ctrl_bounds = control.bounds();
let mid = point(
ctrl_bounds.left() + ctrl_bounds.size.width * 0.5,
ctrl_bounds.center().y,
);
let far_right = point(ctrl_bounds.right() + px(40.0), ctrl_bounds.center().y);
window.pointer_down(mid, MouseButton::Left, cx);
window.pointer_move(far_right, Some(MouseButton::Left), cx);
window.pointer_up(far_right, MouseButton::Left, cx);
assert_eq!(commits.get(), 1);
window.press("home", cx);
window.press("right", cx);
});
assert_eq!(view.read_with(cx, |v, _| v.value), 5.0);
assert_eq!(commits.get(), 3);
}
#[gpui_kit::test]
fn elastic_slider_painted_track_has_visible_geometry(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
});
let (_, cx) = cx.add_window_view(|_, _| SliderHost {
value: 65.0,
commits: Rc::new(Cell::new(0)),
});
for mode in [ThemeMode::Light, ThemeMode::Dark] {
cx.update(|window, cx| {
install_arc_theme(mode, Accent::Neutral, cx);
window.render_frame(cx);
let colors = cx.arc_theme().colors;
let quads = window.painted_quads();
for color in [colors.control_track, colors.control_fill] {
let painted = quads
.iter()
.find(|q| q.background == color.into())
.expect("轨道及填充必须提交到绘制场景");
let width = painted.bounds.size.width.as_f32();
let height = painted.bounds.size.height.as_f32();
assert!(width > 0.0 && height > 0.0, "轨道不能塌缩");
assert!(
painted.corner_radii.top_left.as_f32() <= width.min(height) * 0.5,
"原生绘制不会像 CSS 自动限制圆角,超大半径会使轨道消失: {painted:?}"
);
}
});
}
}
#[test]
fn elastic_snap_back_and_rubber_band_match_arc_formula() {
assert!(rubber_band_signed(500.0, STRETCH) < STRETCH);
assert!(
(rubber_band_signed(-50.0, STRETCH) + rubber_band_signed(50.0, STRETCH)).abs() < 1e-5
);
let snap_back = SpringSpec::visual(0.5, 0.42).as_physical();
let solver = SpringSolver::new(snap_back, 26.0, 0.0, 0.0);
let mut actual = CurveTrace::new("elastic-slider", "over_px");
let mut expected = CurveTrace::new("elastic-slider", "over_px");
let phys = snap_back.resolve();
let omega0 = f64::from(phys.stiffness).sqrt();
let zeta = f64::from(phys.damping) / (2.0 * omega0);
let decay = zeta * omega0;
let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
let mut saw_overshoot = false;
for frame in 0..=60 {
let t_ms = frame as f64 * 16.0;
let t = t_ms / 1000.0;
let env = (-decay * t).exp();
let ref_v =
env * (26.0 * (omega_d * t).cos() + (decay * 26.0 / omega_d) * (omega_d * t).sin());
let s = solver.sample(t);
if s.value < -0.5 {
saw_overshoot = true;
}
expected.push(t_ms, ref_v);
actual.push(t_ms, f64::from(s.value));
}
assert!(
saw_overshoot,
"bounce=0.42 snapBack spring must visibly overshoot"
);
let err = max_curve_error_pct(&actual, &expected);
assert!(
err < 5.0,
"ElasticSlider snapBack curve error {err:.3}% >= 5%"
);
}
}