1use std::{cell::RefCell, rc::Rc};
25
26use arc_motion::{
27 DragTracker, InertiaConfig, InertiaSolver, arc_spring_with_options, is_reduced_motion,
28 motion_now, rubber_band_signed, spring::SpringOptions,
29};
30use arc_tokens::{ActiveArcTheme as _, Spacing, SpringSpec, Typography, oklab_mix};
31use gpui_kit::{
32 App, Bounds, Corners, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
33 MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, RenderOnce, Role,
34 ScrollEvent, SharedString, Styled, TestSupportExt as _, Window, base::StyledExt as _, canvas,
35 div, prelude::*, px, quad,
36};
37
38use super::slider::{RollingNumber, render_rolling_number};
39
40type RulerHandler = Rc<dyn Fn(&f32, &mut Window, &mut App)>;
41
42pub const RULER_STRETCH_PX: f32 = 44.0;
44pub const RULER_TAP_SLOP_PX: f32 = 4.0;
46pub const RULER_POWER: f64 = 0.42;
48pub const RULER_TIME_CONSTANT_MS: f64 = 260.0;
50pub const RULER_WHEEL_SETTLE_SECS: f64 = 0.12;
52
53pub const fn ruler_glide_spring() -> SpringSpec {
56 let root = std::f64::consts::TAU / (0.26 * 1.2);
57 SpringSpec::physics((root * root) as f32, (2.0 * root) as f32)
58}
59
60#[derive(Clone)]
61enum RulerMotion {
62 Idle,
63 Dragging,
64 Coasting(InertiaSolver, f64),
66}
67
68#[derive(Clone)]
69struct RulerInternal {
70 uncontrolled: f32,
71 pos: f32,
73 motion: RulerMotion,
74 wheel_settle_at: Option<f64>,
76 displayed_pos: f32,
78 tracker: DragTracker,
79 drag_start_px: f32,
80 drag_from_value: f32,
81 moved: bool,
82 viewport_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
83 focus_handle: FocusHandle,
84}
85
86impl RulerInternal {
87 fn new(initial: f32, cx: &mut App) -> Self {
88 Self {
89 uncontrolled: initial,
90 pos: initial,
91 motion: RulerMotion::Idle,
92 wheel_settle_at: None,
93 displayed_pos: initial,
94 tracker: DragTracker::new(0.0),
95 drag_start_px: 0.0,
96 drag_from_value: initial,
97 moved: false,
98 viewport_bounds: Rc::new(RefCell::new(None)),
99 focus_handle: cx.focus_handle(),
100 }
101 }
102}
103
104fn decimals_of(value: f32) -> usize {
105 let text = format!("{value}");
106 text.split('.')
107 .nth(1)
108 .map_or(0, |frac| frac.trim_end_matches('0').len())
109}
110
111pub fn ruler_snap(input: f32, min: f32, max: f32, step: f32, decimals: usize) -> f32 {
112 let step = if step > 0.0 { step } else { 1.0 };
113 let factor = 10.0_f32.powi(decimals as i32);
114 let snapped = min + ((input - min) / step).round() * step;
115 ((snapped * factor).round() / factor).clamp(min, max)
116}
117
118pub fn ruler_format_default(value: f64, decimals: usize) -> String {
119 let rounded = format!("{value:.decimals$}");
120 let (sign, rest) = rounded
121 .strip_prefix('-')
122 .map(|r| ("-", r))
123 .unwrap_or(("", rounded.as_str()));
124 let (whole, frac) = match rest.split_once('.') {
125 Some((w, f)) => (w, Some(f)),
126 None => (rest, None),
127 };
128 let mut grouped = String::new();
129 let len = whole.len();
130 for (idx, ch) in whole.chars().enumerate() {
131 grouped.push(ch);
132 let rem = len - 1 - idx;
133 if rem > 0 && rem % 3 == 0 {
134 grouped.push(',');
135 }
136 }
137 match frac {
138 Some(f) => format!("{sign}{grouped}.{f}"),
139 None => format!("{sign}{grouped}"),
140 }
141}
142
143#[derive(IntoElement)]
145pub struct RulerSlider {
146 id: ElementId,
147 label: SharedString,
148 value: Option<f32>,
149 default_value: Option<f32>,
150 min: f32,
151 max: f32,
152 step: f32,
153 large_step: Option<f32>,
154 major_every: usize,
155 spacing: f32,
156 format: Option<Rc<dyn Fn(f64) -> String>>,
157 unit: Option<SharedString>,
158 disabled: bool,
159 width: Option<Pixels>,
160 on_value_change: Option<RulerHandler>,
161 on_value_commit: Option<RulerHandler>,
162}
163
164impl RulerSlider {
165 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
166 Self {
167 id: id.into(),
168 label: label.into(),
169 value: None,
170 default_value: None,
171 min: 0.0,
172 max: 100.0,
173 step: 1.0,
174 large_step: None,
175 major_every: 10,
176 spacing: 10.0,
177 format: None,
178 unit: None,
179 disabled: false,
180 width: None,
181 on_value_change: None,
182 on_value_commit: None,
183 }
184 }
185
186 pub fn value(mut self, value: f32) -> Self {
187 self.value = Some(value);
188 self
189 }
190
191 pub fn default_value(mut self, value: f32) -> Self {
192 self.default_value = Some(value);
193 self
194 }
195
196 pub fn min(mut self, min: f32) -> Self {
197 self.min = min;
198 self
199 }
200
201 pub fn max(mut self, max: f32) -> Self {
202 self.max = max;
203 self
204 }
205
206 pub fn step(mut self, step: f32) -> Self {
208 self.step = step;
209 self
210 }
211
212 pub fn large_step(mut self, large_step: f32) -> Self {
214 self.large_step = Some(large_step);
215 self
216 }
217
218 pub fn major_every(mut self, major_every: usize) -> Self {
220 self.major_every = major_every.max(1);
221 self
222 }
223
224 pub fn spacing(mut self, spacing: f32) -> Self {
226 self.spacing = spacing.max(1.0);
227 self
228 }
229
230 pub fn format(mut self, format: impl Fn(f64) -> String + 'static) -> Self {
231 self.format = Some(Rc::new(format));
232 self
233 }
234
235 pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
237 self.unit = Some(unit.into());
238 self
239 }
240
241 pub fn disabled(mut self, disabled: bool) -> Self {
242 self.disabled = disabled;
243 self
244 }
245
246 pub fn width(mut self, width: impl Into<Pixels>) -> Self {
247 self.width = Some(width.into());
248 self
249 }
250
251 pub fn on_value_change(
252 mut self,
253 handler: impl Fn(&f32, &mut Window, &mut App) + 'static,
254 ) -> Self {
255 self.on_value_change = Some(Rc::new(handler));
256 self
257 }
258
259 pub fn on_value_commit(
261 mut self,
262 handler: impl Fn(&f32, &mut Window, &mut App) + 'static,
263 ) -> Self {
264 self.on_value_commit = Some(Rc::new(handler));
265 self
266 }
267}
268
269impl RenderOnce for RulerSlider {
270 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
271 let theme = cx.arc_theme().clone();
272 let colors = theme.colors;
273 let reduced = is_reduced_motion(cx);
274 let now = motion_now(cx);
275
276 let min = self.min;
277 let max = self.max;
278 let step = if self.step > 0.0 { self.step } else { 1.0 };
279 let decimals = decimals_of(step).max(decimals_of(min));
280 let per_unit = self.spacing / step;
281 let large = self.large_step.unwrap_or(step * self.major_every as f32);
282 let format_value: Rc<dyn Fn(f64) -> String> = self
283 .format
284 .clone()
285 .unwrap_or_else(|| Rc::new(move |v| ruler_format_default(v, decimals)));
286
287 let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-ruler-state".into());
288 let internal = window.use_keyed_state(state_id, cx, |_, cx| {
289 let initial = ruler_snap(
290 self.value.or(self.default_value).unwrap_or(min),
291 min,
292 max,
293 step,
294 decimals,
295 );
296 RulerInternal::new(initial, cx)
297 });
298
299 if let Some(ext) = self.value {
301 let snapped = ruler_snap(ext, min, max, step, decimals);
302 let cur = internal.read(cx).uncontrolled;
303 if (snapped - cur).abs() > f32::EPSILON {
304 internal.update(cx, |s, _| {
305 s.uncontrolled = snapped;
306 });
307 }
308 }
309
310 let snap_state = internal.read(cx).clone();
311 let current = self.value.map_or(snap_state.uncontrolled, |v| {
312 ruler_snap(v, min, max, step, decimals)
313 });
314
315 let is_disabled = self.disabled;
316 let is_controlled = self.value.is_some();
317 let on_change = self.on_value_change.clone();
318 let on_commit = self.on_value_commit.clone();
319
320 let mut target = current;
323 let mut opts = SpringOptions::new(ruler_glide_spring())
324 .with_rest_thresholds(step / 200.0, step / 20.0);
325 let mut pos_now = snap_state.pos;
326 let mut idle = matches!(snap_state.motion, RulerMotion::Idle);
327 match &snap_state.motion {
328 RulerMotion::Dragging => {
329 pos_now = snap_state.pos;
330 target = pos_now;
331 opts = opts.with_initial_value(pos_now).with_travel(false);
332 }
333 RulerMotion::Coasting(solver, started_at) => {
334 let started_at = *started_at;
335 let mut solver = solver.clone();
336 let sample = solver.sample_ms((now - started_at) * 1000.0);
337 let stretch_units = RULER_STRETCH_PX / per_unit.max(1e-4);
338 let raw_val = if sample.value.is_finite() {
339 sample.value
340 } else {
341 current
342 };
343 pos_now = raw_val.clamp(min - stretch_units, max + stretch_units);
344 if sample.done {
345 let next = ruler_snap(pos_now, min, max, step, decimals);
346 internal.update(cx, |s, _| {
347 s.motion = RulerMotion::Idle;
348 s.pos = next;
349 s.displayed_pos = next;
350 if !is_controlled {
351 s.uncontrolled = next;
352 }
353 });
354 pos_now = next;
355 target = next;
356 opts = opts.with_initial_value(next).with_travel(false);
357 idle = true;
358 if let Some(handler) = on_commit.clone() {
359 window.defer(cx, move |window, cx| {
360 handler(&next, window, cx);
361 });
362 }
363 } else {
364 window.request_animation_frame();
365 let tick = ruler_snap(pos_now, min, max, step, decimals);
367 let tick_changed = (tick - current).abs() > f32::EPSILON;
368 internal.update(cx, |s, _| {
369 s.motion = RulerMotion::Coasting(solver, started_at);
370 s.pos = pos_now;
371 s.displayed_pos = pos_now;
372 if !is_controlled && tick_changed {
373 s.uncontrolled = tick;
374 }
375 });
376 if tick_changed && let Some(handler) = on_change.clone() {
377 window.defer(cx, move |window, cx| {
378 handler(&tick, window, cx);
379 });
380 }
381 target = pos_now;
382 opts = opts.with_initial_value(pos_now).with_travel(false);
383 }
384 }
385 RulerMotion::Idle => {}
386 }
387
388 if let Some(settle_at) = snap_state.wheel_settle_at
390 && now >= settle_at
391 {
392 let next = ruler_snap(pos_now, min, max, step, decimals);
393 internal.update(cx, |s, _| {
394 s.wheel_settle_at = None;
395 if !is_controlled {
396 s.uncontrolled = next;
397 }
398 });
399 target = next;
400 if let Some(handler) = on_commit.clone() {
401 window.defer(cx, move |window, cx| {
402 handler(&next, window, cx);
403 });
404 }
405 }
406
407 if (pos_now - snap_state.displayed_pos).abs() > f32::EPSILON && !idle {
408 opts = opts.with_initial_value(pos_now);
409 }
410 let pos_sample =
411 arc_spring_with_options((self.id.clone(), "pos"), target, opts, window, cx);
412 let stretch_units_cap = RULER_STRETCH_PX / per_unit.max(1e-4);
413 let raw_pos = if idle { pos_sample.value } else { pos_now };
414 let pos = if raw_pos.is_finite() {
415 raw_pos.clamp(min - stretch_units_cap, max + stretch_units_cap)
416 } else {
417 current.clamp(min, max)
418 };
419 if idle {
420 internal.update(cx, |s, _| s.displayed_pos = pos);
421 }
422
423 let tick_spacing = self.spacing;
424 let viewport_width = snap_state
426 .viewport_bounds
427 .borrow()
428 .map_or(280.0_f32, |b| f32::from(b.size.width).max(1.0));
429 let tape_x = -((pos - min) * per_unit);
430 let major_every = self.major_every.max(1) as i64;
431 let half_every = if major_every % 2 == 0 {
432 Some(major_every / 2)
433 } else {
434 None
435 };
436 let origin_px_for_labels = viewport_width * 0.5 + tape_x;
437 let total_ticks_for_labels = ((max - min) / step).round().max(0.0) as i64;
438 let label_index_min = (((-origin_px_for_labels - 40.0) / tick_spacing.max(1.0)).floor()
439 as i64)
440 .clamp(0, total_ticks_for_labels);
441 let label_index_max = (((viewport_width - origin_px_for_labels + 40.0)
442 / tick_spacing.max(1.0))
443 .ceil() as i64)
444 .clamp(0, total_ticks_for_labels);
445 let mut major_label_els: Vec<gpui_kit::AnyElement> = Vec::new();
446 for i in label_index_min..=label_index_max {
447 if i % major_every != 0 {
448 continue;
449 }
450 let x_rel = origin_px_for_labels + i as f32 * tick_spacing;
451 if x_rel < -24.0 || x_rel > viewport_width + 24.0 {
452 continue;
453 }
454 let value = ruler_snap(min + i as f32 * step, min, max, step, decimals);
455 let text = SharedString::from(format_value(f64::from(value)));
456 major_label_els.push(
457 div()
458 .absolute()
459 .top(px(36.0))
460 .left(px(x_rel - 24.0))
461 .w(px(48.0))
462 .flex()
463 .items_center()
464 .justify_center()
465 .text_size(Typography::TEXT_XS)
466 .text_color(colors.text_muted)
467 .child(text)
468 .into_any_element(),
469 );
470 }
471
472 let st_down = internal.clone();
474 let focus_down = snap_state.focus_handle.clone();
475 let per_unit_down = per_unit;
476
477 let viewport = div()
478 .id(ElementId::NamedChild(
479 self.id.clone().into(),
480 "viewport".into(),
481 ))
482 .test_support()
483 .role(Role::Slider)
484 .aria_label(self.label.clone())
485 .aria_value(format!(
486 "{}{}",
487 format_value(f64::from(current)),
488 self.unit
489 .as_ref()
490 .map(|u| format!(" {u}"))
491 .unwrap_or_default()
492 ))
493 .track_focus(&focus_down)
494 .relative()
495 .w_full()
496 .h(px(72.0))
497 .rounded(px(8.0))
498 .border_1()
499 .border_color(colors.border)
500 .bg(colors.surface)
501 .overflow_hidden()
502 .when(is_disabled, |this| this.opacity(0.5))
503 .on_mouse_down(
504 MouseButton::Left,
505 move |event: &MouseDownEvent, window, cx| {
506 if is_disabled {
507 return;
508 }
509 let now_d = motion_now(cx);
510 st_down.update(cx, |s, _| {
512 s.motion = RulerMotion::Dragging;
513 s.drag_start_px = f32::from(event.position.x);
514 s.drag_from_value = s.displayed_pos;
515 s.moved = false;
516 s.wheel_settle_at = None;
517 s.tracker = DragTracker::new(0.0);
518 s.tracker
519 .begin(s.displayed_pos, 0.0, s.displayed_pos, now_d);
520 });
521 window.focus(&focus_down, cx);
522 window.refresh();
523 },
524 )
525 .on_scroll({
526 let st_wheel = internal.clone();
527 let is_ctrl_w = is_controlled;
528 let ch_w = on_change.clone();
529 move |event: &ScrollEvent, window, cx| {
530 if is_disabled {
531 return;
532 }
533 let delta = event.delta.pixel_delta(px(20.0));
534 let mut dx = f32::from(delta.x);
535 if dx.abs() <= f32::EPSILON && event.modifiers.shift {
536 dx = f32::from(delta.y);
537 }
538 if dx.abs() <= f32::EPSILON {
539 return;
540 }
541 cx.stop_propagation();
542 let now_w = motion_now(cx);
543 let cur_pos = st_wheel.read(cx).displayed_pos;
544 let next = (cur_pos + dx / per_unit_down).clamp(min, max);
545 let tick = ruler_snap(next, min, max, step, decimals);
546 st_wheel.update(cx, |s, _| {
547 s.pos = next;
548 s.displayed_pos = next;
549 s.wheel_settle_at = Some(now_w + RULER_WHEEL_SETTLE_SECS);
550 if !is_ctrl_w {
551 s.uncontrolled = tick;
552 }
553 });
554 if let Some(handler) = &ch_w {
555 handler(&tick, window, cx);
556 }
557 window.refresh();
558 }
559 })
560 .on_key_down({
561 let st_key = internal.clone();
562 let is_ctrl_k = is_controlled;
563 let ch_k = on_change.clone();
564 let cm_k = on_commit.clone();
565 move |event: &KeyDownEvent, window, cx| {
566 if is_disabled {
567 return;
568 }
569 let now_v = st_key.read(cx).uncontrolled;
570 let key = event.keystroke.key.as_str();
571 let shift = event.keystroke.modifiers.shift;
572 let wanted: f32 = match key {
573 "right" | "arrowright" | "up" | "arrowup" => {
574 now_v + if shift { large } else { step }
575 }
576 "left" | "arrowleft" | "down" | "arrowdown" => {
577 now_v - if shift { large } else { step }
578 }
579 "pageup" => now_v + large,
580 "pagedown" => now_v - large,
581 "home" => min,
582 "end" => max,
583 _ => return,
584 };
585 let next = ruler_snap(wanted, min, max, step, decimals);
586 if (next - now_v).abs() <= f32::EPSILON {
587 return;
588 }
589 st_key.update(cx, |s, _| {
590 s.motion = RulerMotion::Idle;
591 s.wheel_settle_at = None;
592 if !is_ctrl_k {
593 s.uncontrolled = next;
594 }
595 s.pos = s.displayed_pos;
596 });
597 if let Some(handler) = &ch_k {
598 handler(&next, window, cx);
599 }
600 if let Some(handler) = &cm_k {
601 handler(&next, window, cx);
602 }
603 window.refresh();
604 }
605 })
606 .child(
608 canvas(
609 {
610 let vp_ref = snap_state.viewport_bounds.clone();
611 move |rect, _, _| {
612 *vp_ref.borrow_mut() = Some(rect);
613 }
614 },
615 move |rect, _, window, _| {
616 let tick_minor = oklab_mix(colors.foreground, colors.surface, 0.20);
617 let tick_half = oklab_mix(colors.foreground, colors.surface, 0.28);
618 let tick_major = oklab_mix(colors.foreground, colors.surface, 0.52);
619 let w = f32::from(rect.size.width);
620 let h = f32::from(rect.size.height);
621 if w <= 1.0 || h <= 1.0 || step <= 0.0 || tick_spacing <= 0.0 {
622 return;
623 }
624 let origin_px = w * 0.5 + tape_x;
626 let spacing_px = tick_spacing;
627 let total_ticks = ((max - min) / step).round().max(0.0) as i64;
628 let tick_index_min = (((-origin_px - 20.0) / spacing_px).floor() as i64)
629 .clamp(0, total_ticks);
630 let tick_index_max = (((w - origin_px + 20.0) / spacing_px).ceil() as i64)
631 .clamp(0, total_ticks);
632 for i in tick_index_min..=tick_index_max {
633 let is_major = i % major_every == 0;
634 let is_half = !is_major
635 && half_every.is_some_and(|half| half > 0 && i % half == 0);
636 let x_rel = origin_px + i as f32 * spacing_px;
637 if x_rel < -4.0 || x_rel > w + 4.0 {
638 continue;
639 }
640 let x = rect.origin.x + px(x_rel);
641 let (tick_h, tick_w, color) = if is_major {
642 (28.0, 1.0, tick_major)
643 } else if is_half {
644 (20.0, 1.0, tick_half)
645 } else {
646 (12.0, 1.0, tick_minor)
647 };
648 window.paint_quad(quad(
649 Bounds {
650 origin: gpui_kit::point(x - px(tick_w * 0.5), rect.origin.y),
651 size: gpui_kit::size(px(tick_w), px(tick_h)),
652 },
653 Corners::all(px(0.5)),
654 color,
655 gpui_kit::Edges::default(),
656 Hsla::transparent_black(),
657 gpui_kit::BorderStyle::Solid,
658 ));
659 }
660 },
661 )
662 .absolute()
663 .inset_0(),
664 )
665 .children(major_label_els)
666 .child(
667 canvas(|_, _, _| {}, {
668 let st_paint = internal.clone();
669 let vp_ref = snap_state.viewport_bounds.clone();
670 let is_ctrl_p = is_controlled;
671 let ch_p = on_change.clone();
672 let cm_p = on_commit.clone();
673 move |_, _, window, cx| {
674 let _ = &vp_ref;
675 if matches!(st_paint.read(cx).motion, RulerMotion::Dragging) && !is_disabled
677 {
678 let st_move = st_paint.clone();
679 let ch_m = ch_p.clone();
680 let per_unit_m = per_unit;
681 window.on_mouse_event(
682 move |event: &MouseMoveEvent, phase, window, cx| {
683 if !phase.bubble()
684 || !matches!(st_move.read(cx).motion, RulerMotion::Dragging)
685 {
686 return;
687 }
688 let now_m = motion_now(cx);
689 let dx = f32::from(event.position.x)
690 - st_move.read(cx).drag_start_px;
691 let moved =
692 st_move.read(cx).moved || dx.abs() >= RULER_TAP_SLOP_PX;
693 let from = st_move.read(cx).drag_from_value;
694 let raw = from - dx / per_unit_m;
695 let edge = raw.clamp(min, max);
696 let placed = if reduced {
697 edge
698 } else {
699 edge + rubber_band_signed(
700 (raw - edge) * per_unit_m,
701 RULER_STRETCH_PX,
702 ) / per_unit_m
703 };
704 let tick = ruler_snap(edge, min, max, step, decimals);
705 let prev_tick = st_move.read(cx).uncontrolled;
706 st_move.update(cx, |s, _| {
707 s.moved = moved;
708 s.pos = placed;
709 s.displayed_pos = placed;
710 s.tracker.update_x(placed, 0.0, now_m, false);
711 if !is_ctrl_p && moved {
712 s.uncontrolled = tick;
713 }
714 });
715 if moved
716 && (tick - prev_tick).abs() > f32::EPSILON
717 && let Some(handler) = &ch_m
718 {
719 handler(&tick, window, cx);
720 }
721 window.refresh();
722 },
723 );
724 let st_up = st_paint.clone();
725 let cm_u = cm_p.clone();
726 let is_ctrl_u = is_controlled;
727 let per_unit_u = per_unit;
728 let ch_u = ch_p.clone();
729 window.on_mouse_event(
730 move |event: &MouseUpEvent, phase, window, cx| {
731 if !phase.bubble()
732 || event.button != MouseButton::Left
733 || !matches!(st_up.read(cx).motion, RulerMotion::Dragging)
734 {
735 return;
736 }
737 let now_u = motion_now(cx);
738 let was_moved = st_up.read(cx).moved;
739 if !was_moved {
740 let Some(vp) = *st_up.read(cx).viewport_bounds.borrow()
743 else {
744 return;
745 };
746 let tap_offset = (f32::from(event.position.x)
747 - (f32::from(vp.origin.x)
748 + f32::from(vp.size.width) / 2.0))
749 / per_unit_u;
750 let next = ruler_snap(
751 st_up.read(cx).displayed_pos + tap_offset,
752 min,
753 max,
754 step,
755 decimals,
756 );
757 st_up.update(cx, |s, _| {
758 s.motion = RulerMotion::Idle;
759 if !is_ctrl_u {
760 s.uncontrolled = next;
761 }
762 });
763 if let Some(handler) = &ch_u {
764 handler(&next, window, cx);
765 }
766 if let Some(handler) = &cm_u {
767 handler(&next, window, cx);
768 }
769 window.refresh();
770 return;
771 }
772 let velocity = st_up.read(cx).tracker.release_velocity(now_u);
773 let release = st_up.read(cx).pos;
774 if reduced {
775 let next = ruler_snap(release, min, max, step, decimals);
776 st_up.update(cx, |s, _| {
777 s.motion = RulerMotion::Idle;
778 s.pos = next;
779 s.displayed_pos = next;
780 if !is_ctrl_u {
781 s.uncontrolled = next;
782 }
783 });
784 if let Some(handler) = &ch_u {
785 handler(&next, window, cx);
786 }
787 if let Some(handler) = &cm_u {
788 handler(&next, window, cx);
789 }
790 window.refresh();
791 return;
792 }
793 let clamped = release.clamp(min, max);
794 if (release - clamped).abs() > f32::EPSILON {
795 let next = ruler_snap(clamped, min, max, step, decimals);
798 let solver = InertiaSolver::new(
799 f64::from(release),
800 f64::from(velocity),
801 InertiaConfig {
802 power: RULER_POWER,
803 time_constant_ms: RULER_TIME_CONSTANT_MS,
804 bounce_stiffness: 420.0,
805 bounce_damping: 36.0,
806 min: Some(f64::from(min)),
807 max: Some(f64::from(max)),
808 rest_delta: f64::from(step / 200.0),
809 },
810 );
811 st_up.update(cx, |s, _| {
812 s.motion = RulerMotion::Coasting(solver, now_u);
813 if !is_ctrl_u {
814 s.uncontrolled = next;
815 }
816 });
817 if let Some(handler) = &ch_u {
818 handler(&next, window, cx);
819 }
820 window.refresh();
821 return;
822 }
823 let solver = InertiaSolver::new(
825 f64::from(release),
826 f64::from(velocity),
827 InertiaConfig {
828 power: RULER_POWER,
829 time_constant_ms: RULER_TIME_CONSTANT_MS,
830 bounce_stiffness: 420.0,
831 bounce_damping: 36.0,
832 min: Some(f64::from(min)),
833 max: Some(f64::from(max)),
834 rest_delta: f64::from(step / 200.0),
835 },
836 );
837 st_up.update(cx, |s, _| {
838 s.motion = RulerMotion::Coasting(solver, now_u);
839 });
840 window.refresh();
841 },
842 );
843 }
844 }
845 })
846 .absolute()
847 .inset_0(),
848 )
849 .child(
851 div()
852 .absolute()
853 .left(px(viewport_width / 2.0 - 1.0))
854 .top_0()
855 .h(px(36.0))
856 .w(px(2.0))
857 .rounded_full()
858 .bg(colors.accent),
859 );
860
861 let font_px = f32::from(Typography::TEXT_2XL);
863 let readout_text = format_value(f64::from(current));
864 let readout = render_rolling_number(
865 &self.id,
866 &RollingNumber {
867 where_key: "ruler-readout".into(),
868 },
869 f64::from(current),
870 &readout_text,
871 font_px,
872 colors.foreground,
873 reduced,
874 window,
875 cx,
876 );
877
878 div()
879 .id(self.id)
880 .test_support()
881 .when_some(self.width, |this, w| this.w(w))
882 .when(self.width.is_none(), |this| this.w_full())
883 .flex()
884 .flex_col()
885 .gap(Spacing::S2)
886 .when(is_disabled, |this| this.opacity(0.5))
887 .child(
888 div()
889 .w_full()
890 .flex()
891 .flex_row()
892 .items_baseline()
893 .justify_between()
894 .gap(Spacing::S3)
895 .child(
896 div()
897 .text_size(Typography::TEXT_SM)
898 .font_medium()
899 .text_color(colors.text_secondary)
900 .child(self.label.clone()),
901 )
902 .child(
903 div()
904 .flex()
905 .flex_row()
906 .items_baseline()
907 .gap(px(4.0))
908 .child(readout)
909 .when_some(self.unit.clone(), |this, unit| {
910 this.child(
911 div()
912 .text_size(Typography::TEXT_SM)
913 .font_medium()
914 .text_color(colors.text_muted)
915 .child(unit),
916 )
917 }),
918 ),
919 )
920 .child(viewport)
921 }
922}
923
924#[cfg(test)]
925mod tests {
926 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
927 use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
928
929 use super::*;
930
931 #[test]
932 fn ruler_snap_lands_on_ticks_within_bounds() {
933 assert!((ruler_snap(52.4, 0.0, 100.0, 1.0, 0) - 52.0).abs() < 1e-4);
934 assert!((ruler_snap(2.34, 0.0, 10.0, 0.5, 1) - 2.5).abs() < 1e-4);
935 assert!((ruler_snap(-5.0, 0.0, 100.0, 1.0, 0) - 0.0).abs() < 1e-4);
936 assert!((ruler_snap(150.0, 0.0, 100.0, 1.0, 0) - 100.0).abs() < 1e-4);
937 }
938
939 #[test]
940 fn ruler_format_default_groups_and_decimates() {
941 assert_eq!(ruler_format_default(1234.5, 1), "1,234.5");
942 assert_eq!(ruler_format_default(0.25, 2), "0.25");
943 }
944
945 #[test]
946 fn ruler_constants_match_upstream() {
947 assert!((RULER_STRETCH_PX - 44.0).abs() < 1e-5);
948 assert!((RULER_TAP_SLOP_PX - 4.0).abs() < 1e-5);
949 assert!((RULER_POWER - 0.42).abs() < 1e-5);
950 assert!((RULER_TIME_CONSTANT_MS - 260.0).abs() < 1e-5);
951 }
952
953 struct RulerHost {
954 value: f32,
955 events: Rc<RefCell<Vec<String>>>,
956 commits: Rc<RefCell<Vec<String>>>,
957 disabled: bool,
958 }
959
960 impl Render for RulerHost {
961 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
962 let events = self.events.clone();
963 let commits = self.commits.clone();
964 div().w(px(480.0)).p(px(16.0)).child(
965 RulerSlider::new("ruler-test", "Height")
966 .min(0.0)
967 .max(200.0)
968 .step(1.0)
969 .major_every(10)
970 .unit("cm")
971 .value(self.value)
972 .disabled(self.disabled)
973 .on_value_change(cx.listener({
974 let events = events.clone();
975 move |this, v: &f32, _, cx| {
976 events.borrow_mut().push(format!("{v}"));
977 this.value = *v;
978 cx.notify();
979 }
980 }))
981 .on_value_commit(cx.listener({
982 let commits = commits.clone();
983 move |this, v: &f32, _, cx| {
984 commits.borrow_mut().push(format!("{v}"));
985 this.value = *v;
986 cx.notify();
987 }
988 })),
989 )
990 }
991 }
992
993 fn ruler_element(name: &str) -> ElementId {
994 ElementId::NamedChild(ElementId::Name("ruler-test".into()).into(), name.into())
995 }
996
997 #[gpui_kit::test]
998 fn ruler_keyboard_steps_and_commits(cx: &mut TestAppContext) {
999 cx.update(|cx| {
1000 gpui_kit::init(cx);
1001 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
1002 });
1003
1004 let host = RulerHost {
1005 value: 100.0,
1006 events: Rc::new(RefCell::new(Vec::new())),
1007 commits: Rc::new(RefCell::new(Vec::new())),
1008 disabled: false,
1009 };
1010 let events = host.events.clone();
1011 let commits = host.commits.clone();
1012 let (view, cx) = cx.add_window_view(|_, _| host);
1013
1014 cx.update(|window, cx| {
1015 window.render_frame(cx);
1016 let vp = window.find(ruler_element("viewport"));
1017 assert_eq!(vp.role(), Some(Role::Slider));
1018
1019 window.click(ruler_element("viewport"), cx);
1021 window.press("right", cx);
1022 });
1023 assert_eq!(events.borrow().last().map(String::as_str), Some("101"));
1024 assert_eq!(commits.borrow().last().map(String::as_str), Some("101"));
1025
1026 cx.update(|window, cx| {
1027 window.press("shift-right", cx);
1029 });
1030 assert_eq!(events.borrow().last().map(String::as_str), Some("111"));
1031
1032 cx.update(|window, cx| {
1033 window.press("home", cx);
1035 });
1036 assert_eq!(events.borrow().last().map(String::as_str), Some("0"));
1037
1038 view.update(cx, |host, cx| {
1040 host.disabled = true;
1041 cx.notify();
1042 });
1043 cx.update(|window, cx| {
1044 window.render_frame(cx);
1045 window.press("right", cx);
1046 });
1047 assert_eq!(events.borrow().last().map(String::as_str), Some("0"));
1048 }
1049
1050 #[gpui_kit::test]
1051 fn ruler_reduced_motion_steps_instantly(cx: &mut TestAppContext) {
1052 cx.update(|cx| {
1053 gpui_kit::init(cx);
1054 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
1055 arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
1056 });
1057
1058 let host = RulerHost {
1059 value: 50.0,
1060 events: Rc::new(RefCell::new(Vec::new())),
1061 commits: Rc::new(RefCell::new(Vec::new())),
1062 disabled: false,
1063 };
1064 let events = host.events.clone();
1065 let (_view, cx) = cx.add_window_view(|_, _| host);
1066
1067 cx.update(|window, cx| {
1068 window.render_frame(cx);
1069 window.click(ruler_element("viewport"), cx);
1070 window.press("up", cx);
1071 });
1072 assert_eq!(events.borrow().last().map(String::as_str), Some("51"));
1073 }
1074}