1use std::{cell::RefCell, rc::Rc};
26
27use arc_motion::{
28 DragTracker, arc_spring, arc_spring_with_options, is_reduced_motion, motion_now,
29 rubber_band_signed, spring::SpringOptions,
30};
31use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix};
32use gpui_kit::{
33 App, Bounds, Corners, Edges, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
34 MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, RenderOnce,
35 Role, SharedString, Styled, TestSupportExt as _, Window, base::StyledExt as _, canvas, div,
36 prelude::*, px, quad,
37};
38
39type RangeHistogramHandler = Rc<dyn Fn(&(f32, f32), &mut Window, &mut App)>;
40
41pub const RANGE_HISTOGRAM_STRETCH_PX: f32 = 10.0;
43pub const RANGE_HISTOGRAM_BIN_SNAP_PX: f32 = 9.0;
45pub const RANGE_HISTOGRAM_BUMP_PX: f32 = 150.0;
47
48pub const fn range_histogram_thumb_spring() -> SpringSpec {
50 let root = std::f64::consts::TAU / (0.26 * 1.2);
51 SpringSpec::physics((root * root) as f32, (2.0 * root) as f32)
52}
53
54pub fn range_histogram(data: &[f32], min: f32, max: f32, bins: usize) -> Vec<u32> {
56 let mut counts = vec![0_u32; bins.max(1)];
57 let width = (max - min) / bins.max(1) as f32;
58 let width = if width > 0.0 { width } else { 1.0 };
59 for item in data {
60 if *item >= min && *item <= max {
61 let idx = (((item - min) / width) as usize).min(bins.max(1) - 1);
62 counts[idx] += 1;
63 }
64 }
65 counts
66}
67
68#[derive(Clone)]
69struct RangeHistogramInternal {
70 uncontrolled: [f32; 2],
71 dragging: Option<usize>,
72 press_seed: Option<(usize, f32)>,
73 last_active: usize,
74 kick_impulse: Option<f32>,
75 tracker: DragTracker,
76 grab_offset_pct: f32,
77 drag_raw_pct: f32,
78 drag_over_px: f32,
79 rail_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
80 focus_handles: [FocusHandle; 2],
81}
82
83impl RangeHistogramInternal {
84 fn new(initial: [f32; 2], cx: &mut App) -> Self {
85 Self {
86 uncontrolled: initial,
87 dragging: None,
88 press_seed: None,
89 last_active: 1,
90 kick_impulse: None,
91 tracker: DragTracker::new(0.0),
92 grab_offset_pct: 0.0,
93 drag_raw_pct: 0.0,
94 drag_over_px: 0.0,
95 rail_bounds: Rc::new(RefCell::new(None)),
96 focus_handles: [cx.focus_handle(), cx.focus_handle()],
97 }
98 }
99}
100
101fn decimals_of(value: f32) -> usize {
102 let text = format!("{value}");
103 text.split('.')
104 .nth(1)
105 .map_or(0, |frac| frac.trim_end_matches('0').len())
106}
107
108pub fn range_histogram_snap(input: f32, min: f32, max: f32, step: f32, decimals: usize) -> f32 {
109 let step = if step > 0.0 { step } else { 1.0 };
110 let factor = 10.0_f32.powi(decimals as i32);
111 let snapped = min + ((input - min) / step).round() * step;
112 ((snapped * factor).round() / factor).clamp(min, max)
113}
114
115pub fn range_histogram_pct_of(value: f32, min: f32, span: f32) -> f32 {
116 (((value - min) / span) * 100.0).clamp(0.0, 100.0)
117}
118
119pub fn range_histogram_format_default(value: f64, decimals: usize) -> String {
121 let rounded = format!("{value:.decimals$}");
122 let (sign, rest) = rounded
123 .strip_prefix('-')
124 .map(|r| ("-", r))
125 .unwrap_or(("", rounded.as_str()));
126 let (whole, frac) = match rest.split_once('.') {
127 Some((w, f)) => (w, Some(f)),
128 None => (rest, None),
129 };
130 let mut grouped = String::new();
131 let len = whole.len();
132 for (idx, ch) in whole.chars().enumerate() {
133 grouped.push(ch);
134 let rem = len - 1 - idx;
135 if rem > 0 && rem % 3 == 0 {
136 grouped.push(',');
137 }
138 }
139 match frac {
140 Some(f) => format!("{sign}{grouped}.{f}"),
141 None => format!("{sign}{grouped}"),
142 }
143}
144
145#[derive(IntoElement)]
147pub struct RangeHistogramSlider {
148 id: ElementId,
149 label: SharedString,
150 data: Vec<f32>,
151 value: Option<(f32, f32)>,
152 default_value: Option<(f32, f32)>,
153 min: Option<f32>,
154 max: Option<f32>,
155 step: f32,
156 bins: usize,
157 snap_to_bins: bool,
158 min_steps_between_thumbs: f32,
159 format: Option<Rc<dyn Fn(f64) -> String>>,
160 thumb_labels: Option<[SharedString; 2]>,
161 disabled: bool,
162 width: Option<Pixels>,
163 on_value_change: Option<RangeHistogramHandler>,
164 on_value_commit: Option<RangeHistogramHandler>,
165}
166
167impl RangeHistogramSlider {
168 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
169 Self {
170 id: id.into(),
171 label: label.into(),
172 data: Vec::new(),
173 value: None,
174 default_value: None,
175 min: None,
176 max: None,
177 step: 1.0,
178 bins: 32,
179 snap_to_bins: true,
180 min_steps_between_thumbs: 1.0,
181 format: None,
182 thumb_labels: None,
183 disabled: false,
184 width: None,
185 on_value_change: None,
186 on_value_commit: None,
187 }
188 }
189
190 pub fn data<I>(mut self, data: I) -> Self
192 where
193 I: IntoIterator<Item = f32>,
194 {
195 self.data = data.into_iter().collect();
196 self
197 }
198
199 pub fn value(mut self, value: (f32, f32)) -> Self {
200 self.value = Some(value);
201 self
202 }
203
204 pub fn default_value(mut self, value: (f32, f32)) -> Self {
205 self.default_value = Some(value);
206 self
207 }
208
209 pub fn min(mut self, min: f32) -> Self {
211 self.min = Some(min);
212 self
213 }
214
215 pub fn max(mut self, max: f32) -> Self {
216 self.max = Some(max);
217 self
218 }
219
220 pub fn step(mut self, step: f32) -> Self {
221 self.step = step;
222 self
223 }
224
225 pub fn bins(mut self, bins: usize) -> Self {
227 self.bins = bins.max(1);
228 self
229 }
230
231 pub fn snap_to_bins(mut self, snap: bool) -> Self {
233 self.snap_to_bins = snap;
234 self
235 }
236
237 pub fn min_steps_between_thumbs(mut self, steps: f32) -> Self {
239 self.min_steps_between_thumbs = steps;
240 self
241 }
242
243 pub fn format(mut self, format: impl Fn(f64) -> String + 'static) -> Self {
244 self.format = Some(Rc::new(format));
245 self
246 }
247
248 pub fn thumb_labels(mut self, labels: [&str; 2]) -> Self {
249 self.thumb_labels = Some([labels[0].into(), labels[1].into()]);
250 self
251 }
252
253 pub fn disabled(mut self, disabled: bool) -> Self {
254 self.disabled = disabled;
255 self
256 }
257
258 pub fn width(mut self, width: impl Into<Pixels>) -> Self {
259 self.width = Some(width.into());
260 self
261 }
262
263 pub fn on_value_change(
264 mut self,
265 handler: impl Fn(&(f32, f32), &mut Window, &mut App) + 'static,
266 ) -> Self {
267 self.on_value_change = Some(Rc::new(handler));
268 self
269 }
270
271 pub fn on_value_commit(
273 mut self,
274 handler: impl Fn(&(f32, f32), &mut Window, &mut App) + 'static,
275 ) -> Self {
276 self.on_value_commit = Some(Rc::new(handler));
277 self
278 }
279}
280
281impl RenderOnce for RangeHistogramSlider {
282 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
283 let theme = cx.arc_theme().clone();
284 let colors = theme.colors;
285 let motion = theme.motion;
286 let reduced = is_reduced_motion(cx);
287
288 let step = if self.step > 0.0 { self.step } else { 1.0 };
289 let min = self
290 .min
291 .unwrap_or_else(|| self.data.iter().copied().fold(0.0_f32, f32::min).floor());
292 let max = self
293 .max
294 .unwrap_or_else(|| self.data.iter().copied().fold(min + step, f32::max).ceil());
295 let span = (max - min).max(1.0);
296 let decimals = decimals_of(step).max(decimals_of(min));
297 let gap = self.min_steps_between_thumbs * step;
298 let format_value: Rc<dyn Fn(f64) -> String> = self
299 .format
300 .clone()
301 .unwrap_or_else(|| Rc::new(move |v| range_histogram_format_default(v, decimals)));
302
303 let counts = range_histogram(&self.data, min, max, self.bins);
304 let tallest = counts.iter().copied().fold(1_u32, u32::max);
305 let bins = self.bins;
306 let bin_span = span / bins.max(1) as f32;
307 let bin_pct = 100.0 / bins.max(1) as f32;
308
309 let state_id =
310 ElementId::NamedChild(self.id.clone().into(), "__arc-range-histogram-state".into());
311 let internal = window.use_keyed_state(state_id, cx, |_, cx| {
312 let initial = self.value.or(self.default_value).unwrap_or((min, max));
313 RangeHistogramInternal::new([initial.0, initial.1], cx)
314 });
315
316 if let Some((ext_lo, ext_hi)) = self.value {
317 let cur = internal.read(cx).uncontrolled;
318 if [ext_lo, ext_hi] != cur {
319 internal.update(cx, |s, _| s.uncontrolled = [ext_lo, ext_hi]);
320 }
321 }
322
323 let snap_state = internal.read(cx).clone();
324 let values: [f32; 2] = self
325 .value
326 .map_or(snap_state.uncontrolled, |(lo, hi)| [lo, hi]);
327
328 let low_of = move |index: usize, cur: &[f32; 2]| -> f32 {
329 if index == 1 {
330 (cur[0] + gap).clamp(min, max)
331 } else {
332 min
333 }
334 };
335 let high_of = move |index: usize, cur: &[f32; 2]| -> f32 {
336 if index == 0 {
337 (cur[1] - gap).clamp(min, max)
338 } else {
339 max
340 }
341 };
342 let settle = move |index: usize, input: f32, cur: &[f32; 2]| -> f32 {
343 let lo = low_of(index, cur);
344 let hi = high_of(index, cur).max(lo);
345 range_histogram_snap(input.clamp(min, max), min, max, step, decimals).clamp(lo, hi)
346 };
347
348 let thumb_spring = range_histogram_thumb_spring();
349 let rail_width = snap_state
350 .rail_bounds
351 .borrow()
352 .map_or(240.0_f32, |b| f32::from(b.size.width).max(1.0));
353
354 let dragging_index = snap_state.dragging;
355 let kick_impulse = snap_state.kick_impulse;
356 if kick_impulse.is_some() {
357 internal.update(cx, |s, _| s.kick_impulse = None);
358 }
359
360 let mut shown_pcts: Vec<f32> = Vec::with_capacity(2);
361 for (index, value_here) in values.iter().enumerate() {
362 let _ = value_here;
363 let target_pct = if dragging_index == Some(index) {
364 snap_state.drag_raw_pct
365 } else {
366 range_histogram_pct_of(values[index], min, span)
367 };
368 let mut opts = SpringOptions::new(thumb_spring)
369 .with_travel(dragging_index != Some(index))
370 .with_rest_thresholds(0.002, 0.02);
371 if let Some(seed) = snap_state.press_seed
372 && seed.0 == index
373 {
374 opts = opts.with_initial_value(seed.1);
375 internal.update(cx, |s, _| s.press_seed = None);
376 }
377 if let Some(v) = kick_impulse
378 && dragging_index.is_none()
379 {
380 opts = opts.with_initial_velocity(v);
381 }
382 let sample = arc_spring_with_options(
383 (self.id.clone(), SharedString::from(format!("pos-{index}"))),
384 target_pct,
385 opts,
386 window,
387 cx,
388 );
389 shown_pcts.push(sample.value);
390 }
391
392 let thumb_scale = arc_spring(
393 (self.id.clone(), "thumb-scale"),
394 if dragging_index.is_some() && !reduced {
395 1.18
396 } else {
397 1.0
398 },
399 motion.spring.snappy,
400 window,
401 cx,
402 );
403
404 let is_disabled = self.disabled;
405 let is_controlled = self.value.is_some();
406 let on_change = self.on_value_change.clone();
407 let on_commit = self.on_value_commit.clone();
408
409 let st_down = internal.clone();
411 let focus_down = snap_state.focus_handles.clone();
412
413 let control = div()
414 .id(ElementId::NamedChild(
415 self.id.clone().into(),
416 "control".into(),
417 ))
418 .test_support()
419 .relative()
420 .w_full()
421 .flex()
422 .flex_col()
423 .gap(px(8.0))
424 .when(!is_disabled, |this| this.cursor_pointer())
425 .on_mouse_down(
426 MouseButton::Left,
427 move |event: &MouseDownEvent, window, cx| {
428 if is_disabled {
429 return;
430 }
431 let Some(rail) = *st_down.read(cx).rail_bounds.borrow() else {
432 return;
433 };
434 let w = f32::from(rail.size.width).max(1.0);
435 let now_d = motion_now(cx);
436 let at_pct =
437 ((f32::from(event.position.x) - f32::from(rail.origin.x)) / w) * 100.0;
438 let current = st_down.read(cx).uncontrolled;
439 let hit_radius_pct = (16.0 / w) * 100.0;
441 let mut grabbed: Option<usize> = None;
442 for (i, v) in current.iter().enumerate() {
443 let dist = (at_pct - range_histogram_pct_of(*v, min, span)).abs();
444 if dist <= hit_radius_pct
445 && grabbed.is_none_or(|g| {
446 dist < (at_pct - range_histogram_pct_of(current[g], min, span))
447 .abs()
448 })
449 {
450 grabbed = Some(i);
451 }
452 }
453 let low = (at_pct - range_histogram_pct_of(current[0], min, span)).abs();
454 let high = (at_pct - range_histogram_pct_of(current[1], min, span)).abs();
455 let index = if low <= high { 0 } else { 1 };
456 let from_pct = range_histogram_pct_of(current[index], min, span);
457 st_down.update(cx, |s, _| {
458 s.dragging = Some(index);
459 s.last_active = index;
460 s.tracker = DragTracker::new(at_pct);
461 s.tracker.update_x(at_pct, 0.0, now_d, true);
462 if let Some(g) = grabbed {
463 s.grab_offset_pct =
464 at_pct - range_histogram_pct_of(current[g], min, span);
465 s.press_seed = None;
466 } else {
467 s.grab_offset_pct = 0.0;
468 s.press_seed = Some((index, from_pct));
469 }
470 s.drag_raw_pct = at_pct - s.grab_offset_pct;
471 });
472 window.focus(&focus_down[index], cx);
473 window.refresh();
474 },
475 )
476 .child(
478 div().relative().h(px(48.0)).child(
479 canvas(|_, _, _| {}, {
480 let shown_pcts = shown_pcts.clone();
481 move |rect, _, window, _| {
482 let chart_color =
483 oklab_mix(colors.foreground, colors.control_track, 0.14);
484 let lit_color = colors.control_fill;
485 let w = f32::from(rect.size.width);
486 let chart_h = f32::from(rect.size.height);
487 let bar_w = w / bins.max(1) as f32;
488 let from_pct = shown_pcts[0].clamp(0.0, 100.0);
489 let to_pct = shown_pcts[1].clamp(0.0, 100.0);
490 for (idx, count) in counts.iter().enumerate() {
491 if *count == 0 {
492 continue;
493 }
494 let h = ((*count as f32 / tallest as f32) * chart_h)
495 .max(4.0)
496 .min(chart_h);
497 let x = rect.origin.x + px(idx as f32 * bar_w + bar_w * 0.12);
498 let center_pct = (idx as f32 + 0.5) * bar_w / w * 100.0;
499 let lit = center_pct >= from_pct && center_pct <= to_pct;
500 window.paint_quad(quad(
501 Bounds {
502 origin: gpui_kit::point(x, rect.origin.y + px(chart_h - h)),
503 size: gpui_kit::size(px(bar_w * 0.76), px(h)),
504 },
505 Corners::all(px(2.0)),
506 if lit { lit_color } else { chart_color },
507 Edges::default(),
508 Hsla::transparent_black(),
509 gpui_kit::BorderStyle::Solid,
510 ));
511 }
512 }
513 })
514 .absolute()
515 .inset_0(),
516 ),
517 )
518 .child(
520 div()
521 .relative()
522 .h(px(20.0))
523 .child(
524 canvas(
525 {
526 let rail_ref = snap_state.rail_bounds.clone();
527 move |rect, _, _| {
528 *rail_ref.borrow_mut() = Some(rect);
529 }
530 },
531 {
532 let shown_pcts = shown_pcts.clone();
533 move |rect, _, window, _| {
534 let track_color = colors.control_track;
535 let fill_color = colors.control_fill;
536 let y = rect.origin.y
537 + px((f32::from(rect.size.height) - 4.0) / 2.0);
538 let track_bounds = Bounds {
539 origin: gpui_kit::point(rect.origin.x, y),
540 size: gpui_kit::size(rect.size.width, px(4.0)),
541 };
542 window.paint_quad(quad(
543 track_bounds,
544 Corners::all(Radii::PILL),
545 track_color,
546 Edges::default(),
547 Hsla::transparent_black(),
548 gpui_kit::BorderStyle::Solid,
549 ));
550 let from_pct = shown_pcts[0].clamp(0.0, 100.0);
551 let to_pct = shown_pcts[1].clamp(0.0, 100.0);
552 let w = f32::from(rect.size.width);
553 let fill_x = track_bounds.origin.x + px(from_pct / 100.0 * w);
554 let fill_w = ((to_pct - from_pct) / 100.0 * w).max(0.0);
555 if fill_w > 0.0 {
556 window.paint_quad(quad(
557 Bounds {
558 origin: gpui_kit::point(fill_x, y),
559 size: gpui_kit::size(px(fill_w), px(4.0)),
560 },
561 Corners::all(Radii::PILL),
562 fill_color,
563 Edges::default(),
564 Hsla::transparent_black(),
565 gpui_kit::BorderStyle::Solid,
566 ));
567 }
568 }
569 },
570 )
571 .absolute()
572 .inset_0(),
573 )
574 .child(
575 canvas(|_, _, _| {}, {
576 let st = internal.clone();
577 let is_ctrl = is_controlled;
578 let snap_bins = self.snap_to_bins;
579 let ch_up = on_change.clone();
580 let cm_up = on_commit.clone();
581 move |_, _, window, cx| {
582 if !is_disabled {
585 let st_up = st.clone();
586 let ch_up = ch_up.clone();
587 let cm_up = cm_up.clone();
588 window.on_mouse_event(
589 move |event: &MouseUpEvent, phase, window, cx| {
590 if !phase.bubble()
591 || event.button != MouseButton::Left
592 || st_up.read(cx).dragging.is_none()
593 {
594 return;
595 }
596 let now_u = motion_now(cx);
597 let index = st_up.read(cx).dragging.unwrap_or(0);
598 let cur = st_up.read(cx).uncontrolled;
599 let vel =
600 st_up.read(cx).tracker.release_velocity(now_u);
601 let raw = st_up.read(cx).drag_raw_pct;
602 let carry = range_histogram_project(vel)
605 .clamp(-bin_pct, bin_pct);
606 let landing = (raw + carry).clamp(0.0, 100.0);
607 let mut target = min + landing / 100.0 * span;
608 if snap_bins {
609 let edge_value = min
610 + ((target - min) / bin_span).round()
611 * bin_span;
612 let edge_px = ((range_histogram_pct_of(
613 edge_value, min, span,
614 ) - landing)
615 .abs()
616 / 100.0)
617 * rail_width;
618 if edge_px <= RANGE_HISTOGRAM_BIN_SNAP_PX {
619 target = edge_value;
620 }
621 }
622 let next_val = settle(index, target, &cur);
623 st_up.update(cx, |s, _| {
624 s.dragging = None;
625 s.kick_impulse = Some(vel);
626 s.drag_over_px = 0.0;
627 if !is_ctrl {
628 s.uncontrolled[index] = next_val;
629 }
630 });
631 if (next_val - cur[index]).abs() > f32::EPSILON
632 && let Some(handler) = &ch_up
633 {
634 let mut updated = cur;
635 updated[index] = next_val;
636 let v = (updated[0], updated[1]);
637 handler(&v, window, cx);
638 }
639 if let Some(handler) = &cm_up {
640 let final_cur = st_up.read(cx).uncontrolled;
641 let v = (final_cur[0], final_cur[1]);
642 handler(&v, window, cx);
643 }
644 window.refresh();
645 },
646 );
647 }
648 if st.read(cx).dragging.is_none() || is_disabled {
649 return;
650 }
651 let st_move = st.clone();
653 let ch_m = ch_up.clone();
654 window.on_mouse_event(
655 move |event: &MouseMoveEvent, phase, window, cx| {
656 if !phase.bubble() || st_move.read(cx).dragging.is_none() {
657 return;
658 }
659 let Some(rail) = *st_move.read(cx).rail_bounds.borrow()
660 else {
661 return;
662 };
663 let w = f32::from(rail.size.width).max(1.0);
664 let now_m = motion_now(cx);
665 let index = st_move.read(cx).dragging.unwrap_or(0);
666 let cur = st_move.read(cx).uncontrolled;
667 let grab = st_move.read(cx).grab_offset_pct;
668 let at_pct = ((f32::from(event.position.x)
669 - f32::from(rail.origin.x))
670 / w)
671 * 100.0;
672 let raw = at_pct - grab;
673 let low_pct =
674 range_histogram_pct_of(low_of(index, &cur), min, span);
675 let high_pct =
676 range_histogram_pct_of(high_of(index, &cur), min, span)
677 .max(low_pct);
678 let edge = raw.clamp(low_pct, high_pct);
679 let over = if reduced {
680 0.0
681 } else {
682 rubber_band_signed(
683 (raw - edge) / 100.0 * w,
684 RANGE_HISTOGRAM_STRETCH_PX,
685 ) / w
686 * 100.0
687 };
688 let placed = edge + over;
689 let next_val =
690 settle(index, min + (edge / 100.0) * span, &cur);
691 st_move.update(cx, |s, _| {
692 s.drag_raw_pct = placed;
693 s.drag_over_px = (raw - edge) / 100.0 * w;
694 s.tracker.update_x(placed, 0.0, now_m, false);
695 if !is_ctrl {
696 s.uncontrolled[index] = next_val;
697 }
698 });
699 if (next_val - cur[index]).abs() > f32::EPSILON
700 && let Some(handler) = &ch_m
701 {
702 let mut updated = cur;
703 updated[index] = next_val;
704 let v = (updated[0], updated[1]);
705 handler(&v, window, cx);
706 }
707 window.refresh();
708 },
709 );
710 }
711 })
712 .absolute()
713 .inset_0(),
714 )
715 .children((0..2).map({
717 let shown_pcts = shown_pcts.clone();
718 let focus_all = snap_state.focus_handles;
719 let label_all = self.label.clone();
720 let id_all = self.id.clone();
721 let fmt_all = format_value.clone();
722 let labels_all = self.thumb_labels.clone();
723 move |index| {
724 let shown = shown_pcts[index];
725 let value_here = values[index];
726 let text_here = fmt_all(f64::from(value_here));
727 let thumb_id = ElementId::NamedChild(
728 id_all.clone().into(),
729 SharedString::from(format!("thumb-{index}")),
730 );
731 let focus_here = focus_all[index].clone();
732 let st_key = internal.clone();
733 let ch_key = on_change.clone();
734 let cm_key = on_commit.clone();
735 div()
736 .id(thumb_id)
737 .test_support()
738 .role(Role::Slider)
739 .aria_label(if index == 0 {
740 labels_all.clone().map(|l| l[0].clone()).unwrap_or_else(|| {
741 SharedString::from(format!("{}, minimum", label_all))
742 })
743 } else {
744 labels_all.clone().map(|l| l[1].clone()).unwrap_or_else(|| {
745 SharedString::from(format!("{}, maximum", label_all))
746 })
747 })
748 .aria_value(text_here.clone())
749 .track_focus(&focus_here)
750 .on_key_down(move |event: &KeyDownEvent, window, cx| {
751 if is_disabled {
752 return;
753 }
754 let cur = st_key.read(cx).uncontrolled;
755 let now_v = cur[index];
756 let key = event.keystroke.key.as_str();
757 let shift = event.keystroke.modifiers.shift;
758 let edge_from = move |direction: f32, from: f32| -> f32 {
760 let at = (from - min) / bin_span;
761 let next = if direction > 0.0 {
762 (at + 1e-6).floor() + 1.0
763 } else {
764 (at - 1e-6).ceil() - 1.0
765 };
766 min + next * bin_span
767 };
768 let wanted: f32 = match key {
769 "right" | "arrowright" | "up" | "arrowup" => {
770 if shift {
771 edge_from(1.0, now_v)
772 } else {
773 now_v + step
774 }
775 }
776 "left" | "arrowleft" | "down" | "arrowdown" => {
777 if shift {
778 edge_from(-1.0, now_v)
779 } else {
780 now_v - step
781 }
782 }
783 "pageup" => edge_from(1.0, edge_from(1.0, now_v)),
784 "pagedown" => edge_from(-1.0, edge_from(-1.0, now_v)),
785 "home" => low_of(index, &cur),
786 "end" => high_of(index, &cur),
787 _ => return,
788 };
789 let next_v = settle(index, wanted, &cur);
790 st_key.update(cx, |s, _| s.last_active = index);
791 if (next_v - now_v).abs() <= f32::EPSILON {
792 let toward = (wanted - now_v).signum();
793 if toward != 0.0 && !reduced {
794 let bump =
795 (RANGE_HISTOGRAM_BUMP_PX / rail_width) * 100.0;
796 st_key.update(cx, |s, _| {
797 s.kick_impulse = Some(toward * bump)
798 });
799 window.refresh();
800 }
801 return;
802 }
803 let mut updated = cur;
804 updated[index] = next_v;
805 st_key.update(cx, |s, _| {
806 if !is_controlled {
807 s.uncontrolled = updated;
808 }
809 });
810 let v = (updated[0], updated[1]);
811 if let Some(handler) = &ch_key {
812 handler(&v, window, cx);
813 }
814 if let Some(handler) = &cm_key {
815 handler(&v, window, cx);
816 }
817 window.refresh();
818 })
819 .absolute()
820 .left(px(shown / 100.0 * rail_width))
821 .top(px(4.0 - (thumb_scale - 1.0) * 6.0))
822 .ml(px(-6.0))
823 .size(px(12.0 * thumb_scale))
824 .rounded_full()
825 .bg(colors.surface)
826 .border_1()
827 .border_color(colors.control_fill)
828 .shadow(Shadows::control_thumb(theme.mode))
829 .when(is_disabled, |this| this.opacity(0.5))
830 .into_any_element()
831 }
832 })),
833 );
834 let header = div()
835 .flex()
836 .flex_row()
837 .items_center()
838 .justify_between()
839 .mb(Spacing::S2)
840 .child(
841 div()
842 .text_size(Typography::TEXT_SM)
843 .font_medium()
844 .text_color(colors.foreground)
845 .child(self.label.clone()),
846 )
847 .child(
848 div()
849 .text_size(Typography::TEXT_SM)
850 .text_color(colors.text_secondary)
851 .child(SharedString::from(format!(
852 "{} – {}",
853 format_value(f64::from(values[0])),
854 format_value(f64::from(values[1]))
855 ))),
856 );
857
858 div()
859 .id(self.id)
860 .test_support()
861 .when_some(self.width, |this, w| this.w(w))
862 .when(self.width.is_none(), |this| this.w_full())
863 .flex()
864 .flex_col()
865 .when(is_disabled, |this| this.opacity(0.5))
866 .child(header)
867 .child(control)
868 }
869}
870
871pub fn range_histogram_project(velocity_pct_per_sec: f32) -> f32 {
873 velocity_pct_per_sec * 0.099
874}
875
876#[cfg(test)]
877mod tests {
878 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
879 use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
880
881 use super::*;
882
883 #[test]
884 fn range_histogram_counts_values_into_equal_bars() {
885 let counts = range_histogram(&[1.0, 2.0, 3.0, 7.0, 12.0], 0.0, 12.0, 4);
886 assert_eq!(counts, vec![2, 1, 1, 1]);
887 let counts = range_histogram(&[5.9, 6.0, 99.0, -1.0], 0.0, 6.0, 3);
889 assert_eq!(counts, vec![0, 0, 2]);
890 }
891
892 #[test]
893 fn range_histogram_settle_respects_gap_and_bin_edges() {
894 let low_of = move |index: usize, cur: &[f32; 2]| -> f32 {
895 if index == 1 { cur[0] + 4.0 } else { 0.0 }
896 };
897 let settle = move |index: usize, input: f32, cur: &[f32; 2]| -> f32 {
898 let (low, high) = if index == 1 {
899 (low_of(index, cur), 100.0)
900 } else {
901 (0.0, cur[1] - 4.0)
902 };
903 range_histogram_snap(input, 0.0, 100.0, 2.0, 0).clamp(low, high)
904 };
905 assert!((settle(1, 10.0, &[20.0, 80.0]) - 24.0).abs() < 1e-4);
906 assert!((settle(0, 90.0, &[20.0, 80.0]) - 76.0).abs() < 1e-4);
907 }
908
909 #[test]
910 fn range_histogram_momentum_carries_at_most_one_bar() {
911 assert!((range_histogram_project(500.0) - 49.5).abs() < 1e-3);
912 let bin_pct = 100.0 / 32.0;
913 let carry = range_histogram_project(500.0).clamp(-bin_pct, bin_pct);
914 assert!((carry - bin_pct).abs() < 1e-4);
915 }
916
917 struct HistHost {
918 value: (f32, f32),
919 events: Rc<RefCell<Vec<String>>>,
920 commits: Rc<RefCell<Vec<String>>>,
921 disabled: bool,
922 }
923
924 impl Render for HistHost {
925 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
926 let events = self.events.clone();
927 let commits = self.commits.clone();
928 div().w(px(480.0)).p(px(16.0)).child(
929 RangeHistogramSlider::new("hist-test", "Price range")
930 .data([10.0, 20.0, 30.0, 45.0, 60.0, 75.0, 80.0, 90.0])
931 .min(0.0)
932 .max(100.0)
933 .step(5.0)
934 .bins(10)
935 .value(self.value)
936 .disabled(self.disabled)
937 .on_value_change(cx.listener({
938 let events = events.clone();
939 move |this, v: &(f32, f32), _, cx| {
940 events.borrow_mut().push(format!("{}/{}", v.0, v.1));
941 this.value = *v;
942 cx.notify();
943 }
944 }))
945 .on_value_commit(cx.listener({
946 let commits = commits.clone();
947 move |this, v: &(f32, f32), _, cx| {
948 commits.borrow_mut().push(format!("{}/{}", v.0, v.1));
949 this.value = *v;
950 cx.notify();
951 }
952 })),
953 )
954 }
955 }
956
957 fn hist_element(name: &str) -> ElementId {
958 ElementId::NamedChild(ElementId::Name("hist-test".into()).into(), name.into())
959 }
960
961 #[gpui_kit::test]
962 fn range_histogram_keys_walk_bars_and_disabled_blocks(cx: &mut TestAppContext) {
963 cx.update(|cx| {
964 gpui_kit::init(cx);
965 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
966 });
967
968 let host = HistHost {
969 value: (25.0, 75.0),
970 events: Rc::new(RefCell::new(Vec::new())),
971 commits: Rc::new(RefCell::new(Vec::new())),
972 disabled: false,
973 };
974 let events = host.events.clone();
975 let commits = host.commits.clone();
976 let (view, cx) = cx.add_window_view(|_, _| host);
977
978 cx.update(|window, cx| {
979 window.render_frame(cx);
980 let thumb = window.find(hist_element("thumb-1"));
981 assert_eq!(thumb.role(), Some(Role::Slider));
982
983 window.click(hist_element("thumb-1"), cx);
985 window.press("left", cx);
986 });
987 assert_eq!(events.borrow().last().map(String::as_str), Some("25/70"));
988
989 cx.update(|window, cx| {
990 window.press("shift-left", cx);
992 });
993 assert_eq!(events.borrow().last().map(String::as_str), Some("25/60"));
994
995 view.update(cx, |host, cx| {
997 host.disabled = true;
998 cx.notify();
999 });
1000 cx.update(|window, cx| {
1001 window.render_frame(cx);
1002 window.press("left", cx);
1003 });
1004 assert_eq!(events.borrow().last().map(String::as_str), Some("25/60"));
1005 assert_eq!(commits.borrow().last().map(String::as_str), Some("25/60"));
1006 }
1007
1008 #[gpui_kit::test]
1009 fn range_histogram_reduced_motion_steps_instantly(cx: &mut TestAppContext) {
1010 cx.update(|cx| {
1011 gpui_kit::init(cx);
1012 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
1013 arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
1014 });
1015
1016 let host = HistHost {
1017 value: (25.0, 75.0),
1018 events: Rc::new(RefCell::new(Vec::new())),
1019 commits: Rc::new(RefCell::new(Vec::new())),
1020 disabled: false,
1021 };
1022 let events = host.events.clone();
1023 let (_view, cx) = cx.add_window_view(|_, _| host);
1024
1025 cx.update(|window, cx| {
1026 window.render_frame(cx);
1027 window.click(hist_element("thumb-0"), cx);
1028 window.press("right", cx);
1029 });
1030 assert_eq!(events.borrow().last().map(String::as_str), Some("30/75"));
1031 }
1032}