Skip to main content

arc_ui/inputs/
scrub_input.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/scrub-input/scrub-input.tsx` & `.module.css`
3//!
4//! P4 Component #8: `scrub-input`
5//!
6//! - Compact inspector number field (`Md` 36px / `Sm` 30px) with a draggable label handle, inline
7//!   arithmetic expression evaluation (`12*2`, `(100-24)/2`, `50%`), cycleable unit pill, and
8//!   optional progress fill track.
9//! - Scrubbing mechanics:
10//!   - Dragging the handle sideways (`SLOP = 3px`) scrubs the value by one step every
11//!     `pixels_per_step` (`2px` default).
12//!   - Holding `Shift` scrubs/steps `10×` coarser (`coarse_step`) and holding `Alt` scrubs/steps
13//!     `10×` finer (`fine_step`), surfacing a floating `×10` / `×0.1` multiplier tag above the
14//!     handle.
15//!   - Pressing `Escape` mid-scrub cancels the drag and restores the value from when the drag
16//!     started; double-clicking the handle restores `reset_value`.
17//!   - Past `min` or `max` (when `wrap == false`), the shell stretches toward the push with a
18//!     `STRAIN = 12px` asymptotic rubber-band (capped at `OVERSHOOT_CAP = 90px` of stored travel
19//!     so reversing responds immediately) while the body leans by `0.5 * strain`, springing back
20//!     on `settle = physical(0.34, 0)`.
21
22use std::rc::Rc;
23
24use arc_motion::{
25    BlurFallback, CubicBezier, arc_spring, arc_spring_with_options, arc_transition,
26    is_reduced_motion, motion_now, spring::SpringOptions,
27};
28use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, SpringSpec, Typography, oklab_mix};
29use gpui_kit::{
30    App, Bounds, Corners, Edges, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
31    MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, RenderOnce,
32    Role, SharedString, Styled, TestSupportExt as _, Window, assets::IconName,
33    base::StyledExt as _, canvas, component::Icon, deferred, div, point, prelude::*, px, quad,
34    size,
35};
36
37type ScrubValueChangeHandler = Rc<dyn Fn(&f64, &mut Window, &mut App)>;
38type ScrubUnitChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
39
40/// Pointer travel (`3px`) before a handle press becomes an active scrub.
41pub const SCRUB_INPUT_SLOP_PX: f32 = 3.0;
42/// Maximum rubber-band shell stretch (`12px`) past `min` or `max`.
43pub const SCRUB_INPUT_STRAIN_LIMIT_PX: f32 = 12.0;
44/// Maximum stored overshoot travel (`90px`) so reversing direction responds without a long walk back.
45pub const SCRUB_INPUT_OVERSHOOT_CAP_PX: f32 = 90.0;
46
47/// Spring preset matching upstream `settle = physical(0.34, 0)`.
48pub const fn scrub_input_settle_spring() -> SpringSpec {
49    SpringSpec::visual(0.34, 0.0)
50}
51
52/// iOS-style asymptotic rubber-band resistance (`limit = 12px` by default).
53pub fn scrub_input_rubber(distance: f32, limit: f32) -> f32 {
54    if distance.abs() < 1e-5 || limit <= 0.0 {
55        return 0.0;
56    }
57    distance.signum() * (1.0 - 1.0 / (distance.abs() * 0.55 / limit + 1.0)) * limit
58}
59
60/// Rounds `value` to `places` decimal digits and normalizes `-0.0` to `0.0`.
61pub fn scrub_round_to(value: f64, places: usize) -> f64 {
62    let f = 10_f64.powi(places as i32);
63    let r = (value * f).round() / f;
64    if r.abs() < 1e-12 { 0.0 } else { r }
65}
66
67/// Formats `value` rounded to `places` decimal digits, stripping trailing zeroes after a decimal point.
68pub fn format_scrub_number(value: f64, places: usize) -> String {
69    let r = scrub_round_to(value, places);
70    if places == 0 {
71        format!("{:.0}", r)
72    } else {
73        let s = format!("{:.*}", places, r);
74        let trimmed = s.trim_end_matches('0').trim_end_matches('.');
75        if trimmed == "-0" || trimmed.is_empty() {
76            "0".to_string()
77        } else {
78            trimmed.to_string()
79        }
80    }
81}
82
83#[derive(Clone, Debug, PartialEq)]
84enum ExprToken {
85    Number(f64),
86    Unit(String),
87    Op(char),
88}
89
90fn tokenize_scrub_expr(source: &str) -> Option<Vec<ExprToken>> {
91    let normalized = source
92        .trim()
93        .replace(',', ".")
94        .replace('÷', "/")
95        .replace('−', "-");
96    if normalized.is_empty() {
97        return None;
98    }
99    let chars: Vec<char> = normalized.chars().collect();
100    let mut tokens = Vec::new();
101    let mut i = 0;
102    while i < chars.len() {
103        let c = chars[i];
104        if c.is_whitespace() {
105            i += 1;
106            continue;
107        }
108        // Treat `×` or `x`/`X` before a digit/paren/dot as multiplication `*`.
109        if c == '×'
110            || ((c == 'x' || c == 'X') && {
111                let mut j = i + 1;
112                while j < chars.len() && chars[j].is_whitespace() {
113                    j += 1;
114                }
115                j < chars.len() && (chars[j].is_ascii_digit() || chars[j] == '(' || chars[j] == '.')
116            })
117        {
118            tokens.push(ExprToken::Op('*'));
119            i += 1;
120            continue;
121        }
122        if matches!(c, '+' | '-' | '*' | '/' | '(' | ')') {
123            tokens.push(ExprToken::Op(c));
124            i += 1;
125            continue;
126        }
127        if c.is_ascii_digit() || c == '.' {
128            let start = i;
129            let mut seen_dot = c == '.';
130            i += 1;
131            while i < chars.len() {
132                if chars[i].is_ascii_digit() {
133                    i += 1;
134                } else if chars[i] == '.' && !seen_dot {
135                    seen_dot = true;
136                    i += 1;
137                } else if (chars[i] == 'e' || chars[i] == 'E') && i + 1 < chars.len() {
138                    i += 1;
139                    if chars[i] == '+' || chars[i] == '-' {
140                        i += 1;
141                    }
142                } else {
143                    break;
144                }
145            }
146            let slice: String = chars[start..i].iter().collect();
147            let val: f64 = slice.parse().ok()?;
148            tokens.push(ExprToken::Number(val));
149            continue;
150        }
151        if c.is_ascii_alphabetic() || c == '%' || c == '°' {
152            let start = i;
153            i += 1;
154            while i < chars.len()
155                && (chars[i].is_ascii_alphabetic() || chars[i] == '%' || chars[i] == '°')
156            {
157                i += 1;
158            }
159            let unit_str: String = chars[start..i].iter().collect();
160            tokens.push(ExprToken::Unit(unit_str));
161            continue;
162        }
163        return None;
164    }
165    if tokens.is_empty() {
166        None
167    } else {
168        Some(tokens)
169    }
170}
171
172/// Evaluates arithmetic expressions (`+`, `-`, `*`, `/`, unary `+/-`, parentheses `(...)`) over
173/// numbers that may carry a unit from `units` (with `°` ↔ `deg` alias matching).
174/// Returns `None` for invalid syntax, division by zero (`!is_finite()`), or unknown units.
175pub fn evaluate_scrub_expression(
176    text: &str,
177    units: &[SharedString],
178) -> Option<(f64, Option<SharedString>)> {
179    let tokens = tokenize_scrub_expr(text)?;
180    let known_lower: Vec<String> = units.iter().map(|u| u.to_lowercase()).collect();
181
182    struct Parser<'a> {
183        tokens: &'a [ExprToken],
184        idx: usize,
185        units: &'a [SharedString],
186        known_lower: &'a [String],
187        matched_unit: Option<SharedString>,
188        bad: bool,
189    }
190
191    impl<'a> Parser<'a> {
192        fn peek(&self) -> Option<&'a ExprToken> {
193            self.tokens.get(self.idx)
194        }
195
196        fn primary(&mut self) -> f64 {
197            let Some(tok) = self.tokens.get(self.idx) else {
198                self.bad = true;
199                return 0.0;
200            };
201            self.idx += 1;
202            match tok {
203                ExprToken::Op('(') => {
204                    let inner = self.sum();
205                    match self.tokens.get(self.idx) {
206                        Some(ExprToken::Op(')')) => self.idx += 1,
207                        _ => self.bad = true,
208                    }
209                    inner
210                }
211                ExprToken::Op('-') => -self.primary(),
212                ExprToken::Op('+') => self.primary(),
213                ExprToken::Number(n) => {
214                    if let Some(ExprToken::Unit(u)) = self.peek() {
215                        self.idx += 1;
216                        let word = u.to_lowercase();
217                        let alias = if word == "°" {
218                            "deg"
219                        } else if word == "deg" {
220                            "°"
221                        } else {
222                            word.as_str()
223                        };
224                        let found = self
225                            .known_lower
226                            .iter()
227                            .position(|k| k == &word)
228                            .or_else(|| self.known_lower.iter().position(|k| k == alias));
229                        match found {
230                            Some(pos) => self.matched_unit = Some(self.units[pos].clone()),
231                            None => self.bad = true,
232                        }
233                    }
234                    *n
235                }
236                _ => {
237                    self.bad = true;
238                    0.0
239                }
240            }
241        }
242
243        fn product(&mut self) -> f64 {
244            let mut left = self.primary();
245            while let Some(ExprToken::Op(op @ ('*' | '/'))) = self.peek() {
246                let op = *op;
247                self.idx += 1;
248                let right = self.primary();
249                left = if op == '*' {
250                    left * right
251                } else {
252                    left / right
253                };
254            }
255            left
256        }
257
258        fn sum(&mut self) -> f64 {
259            let mut left = self.product();
260            while let Some(ExprToken::Op(op @ ('+' | '-'))) = self.peek() {
261                let op = *op;
262                self.idx += 1;
263                let right = self.product();
264                left = if op == '+' {
265                    left + right
266                } else {
267                    left - right
268                };
269            }
270            left
271        }
272    }
273
274    let mut parser = Parser {
275        tokens: &tokens,
276        idx: 0,
277        units,
278        known_lower: &known_lower,
279        matched_unit: None,
280        bad: false,
281    };
282    let val = parser.sum();
283    if parser.bad || parser.idx != tokens.len() || !val.is_finite() {
284        None
285    } else {
286        Some((val, parser.matched_unit))
287    }
288}
289
290/// Sampled `(enter_opacity, enter_y_px, exit_opacity, exit_y_px)` for the cycleable unit label swap.
291pub fn scrub_unit_swap_sample(elapsed: f64, reduced: bool) -> (f32, f32, f32, f32) {
292    if reduced {
293        let t = (elapsed / 0.12).clamp(0.0, 1.0) as f32;
294        return (t, 0.0, 1.0 - t, 0.0);
295    }
296    let t_in = (elapsed / 0.22).clamp(0.0, 1.0) as f32;
297    let e_in = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t_in);
298    let blur_in = BlurFallback::evaluate(px(2.0 * (1.0 - e_in)), false);
299    let enter_op = (e_in * blur_in.opacity_multiplier).clamp(0.0, 1.0);
300    let enter_y = 6.0 * (1.0 - e_in);
301
302    let t_out = (elapsed / 0.12).clamp(0.0, 1.0) as f32;
303    let e_out = CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t_out);
304    let exit_op = (1.0 - e_out).clamp(0.0, 1.0);
305    let exit_y = -6.0 * e_out;
306
307    (enter_op, enter_y, exit_op, exit_y)
308}
309
310/// Size preset for [`ScrubInput`].
311#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
312pub enum ScrubInputSize {
313    Sm,
314    #[default]
315    Md,
316}
317
318impl ScrubInputSize {
319    pub fn height(self) -> Pixels {
320        match self {
321            Self::Sm => px(26.0),
322            Self::Md => ControlHeights::SM,
323        }
324    }
325
326    pub fn radius(self) -> Pixels {
327        match self {
328            Self::Sm => px(6.0),
329            Self::Md => Radii::CONTROL,
330        }
331    }
332
333    pub fn text_size(self) -> Pixels {
334        match self {
335            Self::Sm => Typography::TEXT_XS,
336            Self::Md => Typography::TEXT_SM,
337        }
338    }
339}
340
341#[derive(Clone, Copy, Debug, PartialEq, Eq)]
342enum ScrubModifier {
343    Fine,
344    Coarse,
345}
346
347#[derive(Clone)]
348struct ScrubInputInternal {
349    uncontrolled_value: f64,
350    uncontrolled_unit: SharedString,
351    previous_unit: Option<SharedString>,
352    unit_changed_at_secs: f64,
353    pressing: bool,
354    scrubbing: bool,
355    last_x: f32,
356    travel_px: f32,
357    raw_value: f64,
358    start_value: f64,
359    strain_target: f32,
360    bump_direction: i8,
361    bump_at_secs: f64,
362    invalid_until_secs: f64,
363    modifier: Option<ScrubModifier>,
364    last_click_at_secs: f64,
365    root_hovered: bool,
366    handle_hovered: bool,
367    was_focused: bool,
368    draft: String,
369    select_all: bool,
370    focus_handle: FocusHandle,
371}
372
373impl ScrubInputInternal {
374    fn new(
375        initial_val: f64,
376        initial_text: SharedString,
377        initial_unit: SharedString,
378        now: f64,
379        focus_handle: FocusHandle,
380    ) -> Self {
381        Self {
382            uncontrolled_value: initial_val,
383            uncontrolled_unit: initial_unit,
384            previous_unit: None,
385            unit_changed_at_secs: now - 10.0,
386            pressing: false,
387            scrubbing: false,
388            last_x: 0.0,
389            travel_px: 0.0,
390            raw_value: initial_val,
391            start_value: initial_val,
392            strain_target: 0.0,
393            bump_direction: 0,
394            bump_at_secs: now - 10.0,
395            invalid_until_secs: f64::NEG_INFINITY,
396            modifier: None,
397            last_click_at_secs: f64::NEG_INFINITY,
398            root_hovered: false,
399            handle_hovered: false,
400            was_focused: false,
401            draft: initial_text.to_string(),
402            select_all: false,
403            focus_handle,
404        }
405    }
406}
407
408/// Arc `ScrubInput` — compact inspector scrub field with arithmetic expression parsing, cycleable
409/// units, progress fill track, `Shift` / `Alt` speed modifiers, and `12px` rubber-band limit strain.
410#[derive(IntoElement)]
411pub struct ScrubInput {
412    id: ElementId,
413    label: SharedString,
414    icon: Option<IconName>,
415    value: Option<f64>,
416    default_value: f64,
417    min: f64,
418    max: f64,
419    step: f64,
420    fine_step: Option<f64>,
421    coarse_step: Option<f64>,
422    precision: Option<usize>,
423    pixels_per_step: f32,
424    wrap: bool,
425    unit: Option<SharedString>,
426    default_unit: Option<SharedString>,
427    units: Vec<SharedString>,
428    reset_value: Option<f64>,
429    track: Option<bool>,
430    size: ScrubInputSize,
431    disabled: bool,
432    width: Option<Pixels>,
433    on_value_change: Option<ScrubValueChangeHandler>,
434    on_unit_change: Option<ScrubUnitChangeHandler>,
435}
436
437impl ScrubInput {
438    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
439        Self {
440            id: id.into(),
441            label: label.into(),
442            icon: None,
443            value: None,
444            default_value: 0.0,
445            min: f64::NEG_INFINITY,
446            max: f64::INFINITY,
447            step: 1.0,
448            fine_step: None,
449            coarse_step: None,
450            precision: None,
451            pixels_per_step: 2.0,
452            wrap: false,
453            unit: None,
454            default_unit: None,
455            units: Vec::new(),
456            reset_value: None,
457            track: None,
458            size: ScrubInputSize::Md,
459            disabled: false,
460            width: None,
461            on_value_change: None,
462            on_unit_change: None,
463        }
464    }
465
466    pub fn icon(mut self, icon: IconName) -> Self {
467        self.icon = Some(icon);
468        self
469    }
470
471    pub fn value(mut self, value: f64) -> Self {
472        self.value = Some(value);
473        self
474    }
475
476    pub fn default_value(mut self, value: f64) -> Self {
477        self.default_value = value;
478        self
479    }
480
481    pub fn min(mut self, min: f64) -> Self {
482        self.min = min;
483        self
484    }
485
486    pub fn max(mut self, max: f64) -> Self {
487        self.max = max;
488        self
489    }
490
491    pub fn step(mut self, step: f64) -> Self {
492        self.step = if step > 0.0 { step } else { 1.0 };
493        self
494    }
495
496    pub fn fine_step(mut self, fine: f64) -> Self {
497        self.fine_step = Some(fine.max(1e-6));
498        self
499    }
500
501    pub fn coarse_step(mut self, coarse: f64) -> Self {
502        self.coarse_step = Some(coarse.max(self.step));
503        self
504    }
505
506    pub fn precision(mut self, precision: usize) -> Self {
507        self.precision = Some(precision);
508        self
509    }
510
511    pub fn pixels_per_step(mut self, pixels: f32) -> Self {
512        self.pixels_per_step = pixels.max(0.5);
513        self
514    }
515
516    pub fn wrap(mut self, wrap: bool) -> Self {
517        self.wrap = wrap;
518        self
519    }
520
521    pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
522        self.unit = Some(unit.into());
523        self
524    }
525
526    pub fn default_unit(mut self, unit: impl Into<SharedString>) -> Self {
527        self.default_unit = Some(unit.into());
528        self
529    }
530
531    pub fn units<I, S>(mut self, units: I) -> Self
532    where
533        I: IntoIterator<Item = S>,
534        S: Into<SharedString>,
535    {
536        self.units = units.into_iter().map(Into::into).collect();
537        self
538    }
539
540    pub fn reset_value(mut self, reset: f64) -> Self {
541        self.reset_value = Some(reset);
542        self
543    }
544
545    pub fn track(mut self, track: bool) -> Self {
546        self.track = Some(track);
547        self
548    }
549
550    pub fn size(mut self, size: ScrubInputSize) -> Self {
551        self.size = size;
552        self
553    }
554
555    pub fn disabled(mut self, disabled: bool) -> Self {
556        self.disabled = disabled;
557        self
558    }
559
560    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
561        self.width = Some(width.into());
562        self
563    }
564
565    pub fn on_value_change(
566        mut self,
567        handler: impl Fn(&f64, &mut Window, &mut App) + 'static,
568    ) -> Self {
569        self.on_value_change = Some(Rc::new(handler));
570        self
571    }
572
573    pub fn on_unit_change(
574        mut self,
575        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
576    ) -> Self {
577        self.on_unit_change = Some(Rc::new(handler));
578        self
579    }
580}
581
582fn decimals_of(value: f64) -> usize {
583    let text = format!("{value}");
584    if let Some((_, exp)) = text.split_once("e-") {
585        return exp.parse().unwrap_or(0);
586    }
587    text.split('.').nth(1).map(|f| f.len()).unwrap_or(0)
588}
589
590fn constrain_scrub_value(next: f64, min: f64, max: f64, places: usize, can_wrap: bool) -> f64 {
591    let rounded = scrub_round_to(next, places);
592    if can_wrap {
593        let span = max - min;
594        scrub_round_to(((rounded - min).rem_euclid(span)) + min, places)
595    } else {
596        rounded.clamp(min, max)
597    }
598}
599
600impl RenderOnce for ScrubInput {
601    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
602        let theme = cx.arc_theme().clone();
603        let colors = theme.colors;
604        let motion = theme.motion;
605        let reduced = is_reduced_motion(cx);
606        let now = motion_now(cx);
607
608        let step = self.step;
609        let fine = self.fine_step.unwrap_or(step / 10.0);
610        let coarse = self.coarse_step.unwrap_or(step * 10.0);
611        let places = self
612            .precision
613            .unwrap_or_else(|| decimals_of(step).max(decimals_of(fine)));
614        let min_v = self.min;
615        let max_v = self.max;
616        let finite_bounds = min_v.is_finite() && max_v.is_finite() && max_v > min_v;
617        let can_wrap = self.wrap && finite_bounds;
618        let show_track = self.track.unwrap_or(true) && finite_bounds;
619
620        let initial_unit: SharedString = self
621            .default_unit
622            .clone()
623            .or_else(|| self.unit.clone())
624            .or_else(|| self.units.first().cloned())
625            .unwrap_or_default();
626        let initial_val = constrain_scrub_value(
627            self.value.unwrap_or(self.default_value),
628            min_v,
629            max_v,
630            places,
631            can_wrap,
632        );
633        let initial_text = SharedString::from(format_scrub_number(initial_val, places));
634
635        let state_id =
636            ElementId::NamedChild(self.id.clone().into(), "__arc-scrub-input-state".into());
637        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
638            ScrubInputInternal::new(
639                initial_val,
640                initial_text,
641                initial_unit,
642                now,
643                cx.focus_handle(),
644            )
645        });
646
647        let current = constrain_scrub_value(
648            self.value
649                .unwrap_or_else(|| internal.read(cx).uncontrolled_value),
650            min_v,
651            max_v,
652            places,
653            can_wrap,
654        );
655        let current_unit: SharedString = self
656            .unit
657            .clone()
658            .unwrap_or_else(|| internal.read(cx).uncontrolled_unit.clone());
659        let unit_list: Vec<SharedString> = if !self.units.is_empty() {
660            self.units.clone()
661        } else if !current_unit.is_empty() {
662            vec![current_unit.clone()]
663        } else {
664            Vec::new()
665        };
666
667        let formatted_current = SharedString::from(format_scrub_number(current, places));
668        let is_input_focused = internal.read(cx).focus_handle.is_focused(window);
669
670        // If the input just lost focus, commit any typed expression; when not focused, keep the
671        // draft text synced to `formatted_current`.
672        {
673            let was_focused = internal.read(cx).was_focused;
674            if was_focused && !is_input_focused {
675                let raw_text = internal.read(cx).draft.clone();
676                if raw_text.trim() != formatted_current.as_ref() {
677                    if let Some((parsed_val, parsed_unit)) =
678                        evaluate_scrub_expression(&raw_text, &unit_list)
679                    {
680                        let next_v =
681                            constrain_scrub_value(parsed_val, min_v, max_v, places, can_wrap);
682                        let new_fmt = format_scrub_number(next_v, places);
683                        let hit_dir = if !can_wrap && parsed_val > max_v {
684                            1
685                        } else if !can_wrap && parsed_val < min_v {
686                            -1
687                        } else {
688                            0
689                        };
690                        internal.update(cx, |s, _| {
691                            s.uncontrolled_value = next_v;
692                            s.draft = new_fmt;
693                            s.select_all = false;
694                            s.was_focused = false;
695                            if hit_dir != 0 {
696                                s.bump_direction = hit_dir;
697                                s.bump_at_secs = now;
698                            }
699                            if let Some(ref u) = parsed_unit
700                                && u != &s.uncontrolled_unit
701                            {
702                                s.previous_unit = Some(s.uncontrolled_unit.clone());
703                                s.uncontrolled_unit = u.clone();
704                                s.unit_changed_at_secs = now;
705                            }
706                        });
707                        if let Some(ref u) = parsed_unit
708                            && u != &current_unit
709                            && let Some(cb_u) = self.on_unit_change.clone()
710                        {
711                            let u_owned = u.clone();
712                            window.defer(cx, move |window, cx| {
713                                cb_u(&u_owned, window, cx);
714                            });
715                        }
716                        if (next_v - current).abs() > 1e-9
717                            && let Some(cb) = self.on_value_change.clone()
718                        {
719                            window.defer(cx, move |window, cx| {
720                                cb(&next_v, window, cx);
721                            });
722                        }
723                    } else {
724                        internal.update(cx, |s, _| {
725                            s.invalid_until_secs = now + 0.90;
726                            s.bump_direction = -1;
727                            s.bump_at_secs = now;
728                            s.draft = formatted_current.to_string();
729                            s.select_all = false;
730                            s.was_focused = false;
731                        });
732                    }
733                } else {
734                    internal.update(cx, |s, _| {
735                        s.select_all = false;
736                        s.was_focused = false;
737                    });
738                }
739            } else if !is_input_focused {
740                let last_sync = internal.read(cx).draft.clone();
741                if last_sync != formatted_current.as_ref() {
742                    internal.update(cx, |s, _| {
743                        s.draft = formatted_current.to_string();
744                    });
745                }
746            } else if !was_focused && is_input_focused {
747                internal.update(cx, |s, _| {
748                    s.was_focused = true;
749                    s.select_all = true;
750                    s.draft = formatted_current.to_string();
751                });
752            }
753        }
754
755        let snap = internal.read(cx).clone();
756        let is_invalid = now < snap.invalid_until_secs;
757        if is_invalid {
758            window.request_animation_frame();
759        }
760
761        // Strain & bump calculation (`settle = physical(0.34, 0)`).
762        let bump_elapsed = (now - snap.bump_at_secs).max(0.0);
763        let bump_impulse = if !reduced && snap.bump_direction != 0 && bump_elapsed < 0.34 {
764            window.request_animation_frame();
765            let t = bump_elapsed as f32;
766            let omega = 16.0_f32;
767            let env = (omega * t * std::f32::consts::E * (-omega * t).exp()).clamp(0.0, 1.0);
768            (snap.bump_direction as f32) * 5.0 * env
769        } else {
770            0.0
771        };
772
773        let settle_spec = scrub_input_settle_spring();
774        let spring_strain = if snap.scrubbing {
775            let _ = arc_spring_with_options(
776                (self.id.clone(), "strain"),
777                snap.strain_target,
778                SpringOptions::new(settle_spec).with_initial_value(snap.strain_target),
779                window,
780                cx,
781            );
782            snap.strain_target
783        } else if reduced {
784            0.0
785        } else {
786            arc_spring((self.id.clone(), "strain"), 0.0, settle_spec, window, cx)
787        };
788        let total_strain = spring_strain + bump_impulse;
789        let lean_x = total_strain * 0.5;
790        let stretch_left = (-total_strain).max(0.0);
791        let stretch_right = total_strain.max(0.0);
792
793        // Progress fill track (`0.0..=1.0`).
794        let target_fraction = if show_track {
795            ((current - min_v) / (max_v - min_v)).clamp(0.0, 1.0) as f32
796        } else {
797            0.0
798        };
799        let fill_fraction = if reduced || snap.scrubbing {
800            let _ = arc_spring_with_options(
801                (self.id.clone(), "track-fill"),
802                target_fraction,
803                SpringOptions::new(motion.spring.smooth).with_initial_value(target_fraction),
804                window,
805                cx,
806            );
807            target_fraction
808        } else {
809            arc_spring(
810                (self.id.clone(), "track-fill"),
811                target_fraction,
812                motion.spring.smooth,
813                window,
814                cx,
815            )
816            .clamp(0.0, 1.0)
817        };
818
819        // Shell background & border colors.
820        let shell_bg = if !self.disabled && is_input_focused {
821            colors.surface
822        } else {
823            colors.surface_muted
824        };
825        let shell_border = if is_invalid {
826            colors.danger
827        } else if !self.disabled && (is_input_focused || snap.scrubbing) {
828            colors.border_strong
829        } else if !self.disabled && snap.root_hovered {
830            colors.border
831        } else {
832            gpui_kit::Hsla::transparent_black()
833        };
834        let fill_tint = oklab_mix(
835            colors.foreground,
836            shell_bg,
837            if snap.scrubbing { 0.10 } else { 0.06 },
838        );
839
840        let shell_radius = self.size.radius();
841        let shell_h = self.size.height();
842        let font_sz = self.size.text_size();
843        let disabled = self.disabled;
844
845        // Global scrub drag listener while `snap.pressing` is active.
846        let pressing = snap.pressing;
847        let int_drag = internal.clone();
848        let on_change_drag = self.on_value_change.clone();
849        let pps = self.pixels_per_step;
850
851        let drag_listener = canvas(
852            |_, _, _| {},
853            move |_, _, window, _| {
854                if pressing {
855                    let st_move = int_drag.clone();
856                    let cb_move = on_change_drag.clone();
857                    window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
858                        if !phase.bubble() {
859                            return;
860                        }
861                        if !st_move.read(cx).pressing {
862                            return;
863                        }
864                        let cur_x = f32::from(event.position.x);
865                        let shift = event.modifiers.shift;
866                        let alt = event.modifiers.alt;
867                        let amount = if shift {
868                            coarse
869                        } else if alt {
870                            fine
871                        } else {
872                            step
873                        };
874                        let mode = if shift {
875                            Some(ScrubModifier::Coarse)
876                        } else if alt {
877                            Some(ScrubModifier::Fine)
878                        } else {
879                            None
880                        };
881
882                        let mut emitted_next: Option<f64> = None;
883                        st_move.update(cx, |s, _| {
884                            let dx = cur_x - s.last_x;
885                            s.last_x = cur_x;
886                            s.travel_px += dx;
887                            s.modifier = mode;
888                            if !s.scrubbing {
889                                if s.travel_px.abs() < SCRUB_INPUT_SLOP_PX {
890                                    return;
891                                }
892                                s.scrubbing = true;
893                            }
894                            s.raw_value += (dx / pps) as f64 * amount;
895                            if !can_wrap {
896                                let per_px = amount / (pps as f64);
897                                let over = if max_v.is_finite() && s.raw_value > max_v {
898                                    ((s.raw_value - max_v) / per_px) as f32
899                                } else if min_v.is_finite() && s.raw_value < min_v {
900                                    ((s.raw_value - min_v) / per_px) as f32
901                                } else {
902                                    0.0
903                                };
904                                if over.abs() > SCRUB_INPUT_OVERSHOOT_CAP_PX {
905                                    let edge = if over > 0.0 { max_v } else { min_v };
906                                    s.raw_value = edge
907                                        + (over.signum() * SCRUB_INPUT_OVERSHOOT_CAP_PX) as f64
908                                            * per_px;
909                                }
910                                let clamped_over = over.clamp(
911                                    -SCRUB_INPUT_OVERSHOOT_CAP_PX,
912                                    SCRUB_INPUT_OVERSHOOT_CAP_PX,
913                                );
914                                s.strain_target = if reduced {
915                                    0.0
916                                } else {
917                                    scrub_input_rubber(clamped_over, SCRUB_INPUT_STRAIN_LIMIT_PX)
918                                };
919                            }
920                            let snapped = (s.raw_value / amount).round() * amount;
921                            let next =
922                                constrain_scrub_value(snapped, min_v, max_v, places, can_wrap);
923                            if (next - s.uncontrolled_value).abs() > 1e-9 {
924                                s.uncontrolled_value = next;
925                                emitted_next = Some(next);
926                            }
927                        });
928                        if let Some(next_v) = emitted_next {
929                            let fmt = format_scrub_number(next_v, places);
930                            st_move.update(cx, |s, _| {
931                                s.draft = fmt;
932                                s.select_all = false;
933                            });
934                            if let Some(cb) = &cb_move {
935                                cb(&next_v, window, cx);
936                            }
937                        }
938                        window.refresh();
939                    });
940
941                    let st_up = int_drag.clone();
942                    window.on_mouse_event(move |_: &MouseUpEvent, phase, window, cx| {
943                        if !phase.bubble() {
944                            return;
945                        }
946                        if st_up.read(cx).pressing {
947                            st_up.update(cx, |s, _| {
948                                s.pressing = false;
949                                s.scrubbing = false;
950                                s.strain_target = 0.0;
951                                s.modifier = None;
952                            });
953                            window.refresh();
954                        }
955                    });
956                }
957            },
958        )
959        .absolute()
960        .inset_0();
961
962        // Left scrub handle (`.handle`).
963        let handle_fg = if !disabled && (snap.scrubbing || snap.handle_hovered) {
964            colors.foreground
965        } else {
966            colors.text_muted
967        };
968        let int_h_hover = internal.clone();
969        let int_h_down = internal.clone();
970        let reset_opt = self.reset_value;
971        let on_change_reset = self.on_value_change.clone();
972
973        let handle_el = div()
974            .id(ElementId::NamedChild(
975                self.id.clone().into(),
976                "handle".into(),
977            ))
978            .test_support()
979            .relative()
980            .min_w(px(30.0))
981            .h_full()
982            .pl(px(10.0))
983            .pr(px(4.0))
984            .flex()
985            .flex_row()
986            .items_center()
987            .justify_center()
988            .gap(px(4.0))
989            .text_size(font_sz)
990            .font_medium()
991            .text_color(handle_fg)
992            .when(!disabled, |this| this.cursor_ew_resize())
993            .on_hover(move |hovered, window, cx| {
994                int_h_hover.update(cx, |s, _| s.handle_hovered = *hovered);
995                window.refresh();
996            })
997            .on_mouse_down(
998                MouseButton::Left,
999                move |event: &MouseDownEvent, window, cx| {
1000                    if disabled {
1001                        return;
1002                    }
1003                    let t_now = motion_now(cx);
1004                    let is_double = (t_now - int_h_down.read(cx).last_click_at_secs) < 0.32;
1005                    if is_double && let Some(rst) = reset_opt {
1006                        let next_v = constrain_scrub_value(rst, min_v, max_v, places, can_wrap);
1007                        let fmt = format_scrub_number(next_v, places);
1008                        int_h_down.update(cx, |s, _| {
1009                            s.uncontrolled_value = next_v;
1010                            s.draft = fmt;
1011                            s.select_all = false;
1012                            s.last_click_at_secs = f64::NEG_INFINITY;
1013                            s.pressing = false;
1014                            s.scrubbing = false;
1015                        });
1016                        if let Some(cb) = &on_change_reset {
1017                            cb(&next_v, window, cx);
1018                        }
1019                        window.refresh();
1020                        return;
1021                    }
1022                    int_h_down.update(cx, |s, _| {
1023                        s.last_click_at_secs = t_now;
1024                        s.pressing = true;
1025                        s.scrubbing = false;
1026                        s.last_x = f32::from(event.position.x);
1027                        s.travel_px = 0.0;
1028                        s.raw_value = current;
1029                        s.start_value = current;
1030                        s.strain_target = 0.0;
1031                        s.modifier = if event.modifiers.shift {
1032                            Some(ScrubModifier::Coarse)
1033                        } else if event.modifiers.alt {
1034                            Some(ScrubModifier::Fine)
1035                        } else {
1036                            None
1037                        };
1038                    });
1039                    window.refresh();
1040                },
1041            )
1042            .child(drag_listener)
1043            .when_some(self.icon, |this, ic| {
1044                this.child(Icon::new(ic).text_size(px(14.0)))
1045            })
1046            .when(!self.label.is_empty(), |this| this.child(self.label));
1047
1048        // Trailing unit display or cycle button (`.unit`).
1049        let unit_el = if !current_unit.is_empty() {
1050            let can_cycle = unit_list.len() > 1;
1051            let unit_elapsed = (now - snap.unit_changed_at_secs).max(0.0);
1052            let (u_in_op, u_in_y, u_out_op, u_out_y) = if unit_elapsed < 0.24 {
1053                window.request_animation_frame();
1054                scrub_unit_swap_sample(unit_elapsed, reduced)
1055            } else {
1056                (1.0, 0.0, 0.0, 0.0)
1057            };
1058
1059            let mut unit_text_slot = div()
1060                .relative()
1061                .h(px(18.0))
1062                .overflow_hidden()
1063                .flex()
1064                .items_center()
1065                .justify_center()
1066                .child(
1067                    div()
1068                        .mt(px(u_in_y))
1069                        .opacity(u_in_op)
1070                        .child(current_unit.clone()),
1071                );
1072            if u_out_op > 0.01
1073                && let Some(prev_u) = snap.previous_unit.clone()
1074            {
1075                unit_text_slot = unit_text_slot.child(
1076                    div()
1077                        .absolute()
1078                        .top_0()
1079                        .left_0()
1080                        .mt(px(u_out_y))
1081                        .opacity(u_out_op)
1082                        .child(prev_u),
1083                );
1084            }
1085
1086            if can_cycle {
1087                let int_cycle = internal.clone();
1088                let units_for_cycle = unit_list.clone();
1089                let cur_u_for_cycle = current_unit.clone();
1090                let on_u_change = self.on_unit_change.clone();
1091                let hover_bg = oklab_mix(colors.foreground, shell_bg, 0.07);
1092                let hover_fg = colors.foreground;
1093
1094                Some(
1095                    div()
1096                        .id(ElementId::NamedChild(self.id.clone().into(), "unit".into()))
1097                        .test_support()
1098                        .role(Role::Button)
1099                        .aria_label(SharedString::from(format!(
1100                            "Unit: {current_unit}. Change unit"
1101                        )))
1102                        .on_click(move |_, window, cx| {
1103                            if disabled || units_for_cycle.len() < 2 {
1104                                return;
1105                            }
1106                            let t_now = motion_now(cx);
1107                            let pos = units_for_cycle
1108                                .iter()
1109                                .position(|u| u == &cur_u_for_cycle)
1110                                .unwrap_or(0);
1111                            let next_u = units_for_cycle[(pos + 1) % units_for_cycle.len()].clone();
1112                            int_cycle.update(cx, |s, _| {
1113                                s.previous_unit = Some(cur_u_for_cycle.clone());
1114                                s.uncontrolled_unit = next_u.clone();
1115                                s.unit_changed_at_secs = t_now;
1116                            });
1117                            if let Some(cb) = &on_u_change {
1118                                cb(&next_u, window, cx);
1119                            }
1120                            window.refresh();
1121                        })
1122                        .min_w(px(18.0))
1123                        .h(px(22.0))
1124                        .px(px(4.0))
1125                        .flex_none()
1126                        .flex()
1127                        .items_center()
1128                        .justify_center()
1129                        .rounded(px(6.0))
1130                        .text_size(Typography::TEXT_XS)
1131                        .text_color(colors.text_muted)
1132                        .when(!disabled, |this| {
1133                            this.cursor_pointer()
1134                                .hover(move |s| s.bg(hover_bg).text_color(hover_fg))
1135                        })
1136                        .child(unit_text_slot)
1137                        .into_any_element(),
1138                )
1139            } else {
1140                Some(
1141                    div()
1142                        .min_w(px(18.0))
1143                        .h(px(22.0))
1144                        .px(px(4.0))
1145                        .flex_none()
1146                        .flex()
1147                        .items_center()
1148                        .justify_center()
1149                        .text_size(Typography::TEXT_XS)
1150                        .text_color(colors.text_muted)
1151                        .child(unit_text_slot)
1152                        .into_any_element(),
1153                )
1154            }
1155        } else {
1156            None
1157        };
1158
1159        // Floating speed multiplier tag (`×10` / `×0.1`) when `Shift` or `Alt` is held while scrubbing.
1160        let multiplier_text: Option<SharedString> = match snap.modifier {
1161            Some(ScrubModifier::Coarse) => Some(SharedString::from(format!(
1162                "×{}",
1163                format_scrub_number(coarse / step, 2)
1164            ))),
1165            Some(ScrubModifier::Fine) => Some(SharedString::from(format!(
1166                "×{}",
1167                format_scrub_number(fine / step, 3)
1168            ))),
1169            None => None,
1170        };
1171        let show_tag = snap.scrubbing && multiplier_text.is_some();
1172        let tag_op = arc_transition(
1173            (self.id.clone(), "tag-op"),
1174            if show_tag { 1.0 } else { 0.0 },
1175            motion.duration.instant,
1176            motion.ease.standard,
1177            window,
1178            cx,
1179        );
1180        let tag_y = if reduced {
1181            0.0
1182        } else {
1183            arc_spring(
1184                (self.id.clone(), "tag-y"),
1185                if show_tag { 0.0 } else { 4.0 },
1186                motion.spring.snappy,
1187                window,
1188                cx,
1189            )
1190        };
1191
1192        let tag_el = if tag_op > 0.01 {
1193            let txt = multiplier_text.unwrap_or_else(|| "×10".into());
1194            Some(
1195                deferred(
1196                    div()
1197                        .absolute()
1198                        .bottom_full()
1199                        .left(px(6.0))
1200                        .mb(px(6.0 - tag_y))
1201                        .px(px(7.0))
1202                        .py(px(2.0))
1203                        .rounded(Radii::PILL)
1204                        .bg(colors.foreground)
1205                        .text_color(colors.background)
1206                        .text_size(Typography::TEXT_XS)
1207                        .opacity(tag_op)
1208                        .child(txt),
1209                )
1210                .with_priority(25),
1211            )
1212        } else {
1213            None
1214        };
1215
1216        // Keyboard handling (`ArrowUp` / `ArrowDown` with `Shift` / `Alt`, `Enter` to evaluate
1217        // arithmetic expression, `Escape` to cancel scrub or revert draft).
1218        let int_root_hover = internal.clone();
1219        let int_key = internal.clone();
1220        let int_field_click = internal.clone();
1221        let units_for_key = unit_list;
1222        let cur_u_for_key = current_unit;
1223        let on_change_key = self.on_value_change.clone();
1224        let on_u_change_key = self.on_unit_change.clone();
1225        let focus_handle = snap.focus_handle.clone();
1226        let focus_for_click = snap.focus_handle.clone();
1227        let formatted_for_click = formatted_current.clone();
1228        let value_input_id = ElementId::NamedChild(self.id.clone().into(), "value-input".into());
1229        let shown_text: SharedString = if is_input_focused {
1230            SharedString::from(snap.draft.clone())
1231        } else {
1232            formatted_current.clone()
1233        };
1234        let caret_color = colors.control_fill;
1235        let select_bg = oklab_mix(colors.control_fill, shell_bg, 0.22);
1236
1237        div()
1238            .id(self.id)
1239            .test_support()
1240            .role(Role::SpinButton)
1241            .track_focus(&focus_handle)
1242            .relative()
1243            .when_some(self.width, |this, w| this.w(w))
1244            .when(self.width.is_none(), |this| this.w(px(148.0)))
1245            .h(shell_h)
1246            .flex()
1247            .flex_row()
1248            .items_center()
1249            .opacity(if disabled { 0.5 } else { 1.0 })
1250            .on_hover(move |hovered, window, cx| {
1251                int_root_hover.update(cx, |s, _| s.root_hovered = *hovered);
1252                window.refresh();
1253            })
1254            .on_key_down(move |event: &KeyDownEvent, window, cx| {
1255                if disabled {
1256                    return;
1257                }
1258                let t_now = motion_now(cx);
1259
1260                match event.keystroke.key.as_str() {
1261                    "escape" => {
1262                        if int_key.read(cx).scrubbing {
1263                            let restore_v = int_key.read(cx).start_value;
1264                            let fmt = format_scrub_number(restore_v, places);
1265                            int_key.update(cx, |s, _| {
1266                                s.uncontrolled_value = restore_v;
1267                                s.draft = fmt;
1268                                s.select_all = false;
1269                                s.pressing = false;
1270                                s.scrubbing = false;
1271                                s.strain_target = 0.0;
1272                                s.modifier = None;
1273                            });
1274                            if let Some(cb) = &on_change_key {
1275                                cb(&restore_v, window, cx);
1276                            }
1277                            window.refresh();
1278                        } else {
1279                            int_key.update(cx, |s, _| {
1280                                s.draft = formatted_current.to_string();
1281                                s.select_all = true;
1282                            });
1283                            window.refresh();
1284                        }
1285                    }
1286                    "enter" => {
1287                        let raw_text = int_key.read(cx).draft.clone();
1288                        if let Some((parsed_val, parsed_unit)) =
1289                            evaluate_scrub_expression(&raw_text, &units_for_key)
1290                        {
1291                            let next_v =
1292                                constrain_scrub_value(parsed_val, min_v, max_v, places, can_wrap);
1293                            let fmt = format_scrub_number(next_v, places);
1294                            let hit_dir = if !can_wrap && parsed_val > max_v {
1295                                1
1296                            } else if !can_wrap && parsed_val < min_v {
1297                                -1
1298                            } else {
1299                                0
1300                            };
1301                            int_key.update(cx, |s, _| {
1302                                s.uncontrolled_value = next_v;
1303                                s.draft = fmt;
1304                                s.select_all = true;
1305                                if hit_dir != 0 {
1306                                    s.bump_direction = hit_dir;
1307                                    s.bump_at_secs = t_now;
1308                                }
1309                                if let Some(ref u) = parsed_unit
1310                                    && u != &s.uncontrolled_unit
1311                                {
1312                                    s.previous_unit = Some(s.uncontrolled_unit.clone());
1313                                    s.uncontrolled_unit = u.clone();
1314                                    s.unit_changed_at_secs = t_now;
1315                                }
1316                            });
1317                            if let Some(ref u) = parsed_unit
1318                                && u != &cur_u_for_key
1319                                && let Some(cb_u) = &on_u_change_key
1320                            {
1321                                cb_u(u, window, cx);
1322                            }
1323                            if (next_v - current).abs() > 1e-9
1324                                && let Some(cb) = &on_change_key
1325                            {
1326                                cb(&next_v, window, cx);
1327                            }
1328                        } else {
1329                            int_key.update(cx, |s, _| {
1330                                s.invalid_until_secs = t_now + 0.90;
1331                                s.bump_direction = -1;
1332                                s.bump_at_secs = t_now;
1333                                s.draft = formatted_current.to_string();
1334                                s.select_all = true;
1335                            });
1336                        }
1337                        window.refresh();
1338                    }
1339                    "up" | "arrowup" | "down" | "arrowdown" => {
1340                        let dir: f64 = if matches!(event.keystroke.key.as_str(), "up" | "arrowup") {
1341                            1.0
1342                        } else {
1343                            -1.0
1344                        };
1345                        let shift = event.keystroke.modifiers.shift;
1346                        let alt = event.keystroke.modifiers.alt;
1347                        let amount = if shift {
1348                            coarse
1349                        } else if alt {
1350                            fine
1351                        } else {
1352                            step
1353                        };
1354                        if !can_wrap
1355                            && ((dir > 0.0 && current >= max_v) || (dir < 0.0 && current <= min_v))
1356                        {
1357                            int_key.update(cx, |s, _| {
1358                                s.bump_direction = dir as i8;
1359                                s.bump_at_secs = t_now;
1360                            });
1361                            window.refresh();
1362                            return;
1363                        }
1364                        let snapped = if shift {
1365                            let grid = if dir > 0.0 {
1366                                (current / amount + 1e-9).floor() + 1.0
1367                            } else {
1368                                (current / amount - 1e-9).ceil() - 1.0
1369                            };
1370                            grid * amount
1371                        } else {
1372                            current + dir * amount
1373                        };
1374                        let next_v = constrain_scrub_value(snapped, min_v, max_v, places, can_wrap);
1375                        let fmt = format_scrub_number(next_v, places);
1376                        int_key.update(cx, |s, _| {
1377                            s.uncontrolled_value = next_v;
1378                            s.draft = fmt;
1379                            s.select_all = true;
1380                        });
1381                        if (next_v - current).abs() > 1e-9
1382                            && let Some(cb) = &on_change_key
1383                        {
1384                            cb(&next_v, window, cx);
1385                        }
1386                        window.refresh();
1387                    }
1388                    "backspace" | "delete" => {
1389                        int_key.update(cx, |s, _| {
1390                            if s.select_all {
1391                                s.draft.clear();
1392                                s.select_all = false;
1393                            } else {
1394                                s.draft.pop();
1395                            }
1396                        });
1397                        window.refresh();
1398                    }
1399                    "a" if event.keystroke.modifiers.control
1400                        || event.keystroke.modifiers.platform =>
1401                    {
1402                        int_key.update(cx, |s, _| {
1403                            if !s.draft.is_empty() {
1404                                s.select_all = true;
1405                            }
1406                        });
1407                        window.refresh();
1408                    }
1409                    "v" if event.keystroke.modifiers.control
1410                        || event.keystroke.modifiers.platform =>
1411                    {
1412                        let pasted = cx
1413                            .read_from_clipboard()
1414                            .and_then(|item| item.text())
1415                            .unwrap_or_default();
1416                        let trimmed = pasted.trim();
1417                        if !trimmed.is_empty() {
1418                            int_key.update(cx, |s, _| {
1419                                if s.select_all {
1420                                    s.draft = trimmed.to_string();
1421                                    s.select_all = false;
1422                                } else {
1423                                    s.draft.push_str(trimmed);
1424                                }
1425                            });
1426                            window.refresh();
1427                        }
1428                    }
1429                    k => {
1430                        let ch_opt = event
1431                            .keystroke
1432                            .key_char
1433                            .as_deref()
1434                            .and_then(|kc| {
1435                                (kc.chars().count() == 1)
1436                                    .then(|| kc.chars().next())
1437                                    .flatten()
1438                            })
1439                            .or_else(|| {
1440                                (k.chars().count() == 1).then(|| k.chars().next()).flatten()
1441                            });
1442                        if let Some(ch) = ch_opt
1443                            && !event.keystroke.modifiers.control
1444                            && !event.keystroke.modifiers.platform
1445                            && (ch.is_ascii_alphanumeric()
1446                                || matches!(
1447                                    ch,
1448                                    '.' | '+' | '-' | '*' | '/' | '(' | ')' | '%' | '°' | ' '
1449                                ))
1450                        {
1451                            int_key.update(cx, |s, _| {
1452                                if s.select_all {
1453                                    s.draft.clear();
1454                                    s.select_all = false;
1455                                }
1456                                s.draft.push(ch);
1457                            });
1458                            window.refresh();
1459                        }
1460                    }
1461                }
1462            })
1463            .child(
1464                // Background `.shell` that stretches past limits without distorting the text.
1465                // Painted via canvas with `with_content_mask` so the fill bar shares the exact
1466                // rounded corners of the shell and sits underneath the 1px shell border.
1467                canvas(
1468                    |_, _, _| {},
1469                    move |rect, _, window, _| {
1470                        let shell_corners = Corners::all(shell_radius);
1471                        window.paint_quad(quad(
1472                            rect,
1473                            shell_corners,
1474                            shell_bg,
1475                            Edges::default(),
1476                            Hsla::transparent_black(),
1477                            gpui_kit::BorderStyle::Solid,
1478                        ));
1479                        if show_track && fill_fraction > 0.001 {
1480                            let fill_w = f32::from(rect.size.width) * fill_fraction.clamp(0.0, 1.0);
1481                            if fill_w > 0.5 {
1482                                let mask = gpui_kit::ContentMask {
1483                                    bounds: Bounds {
1484                                        origin: rect.origin,
1485                                        size: size(px(fill_w), rect.size.height),
1486                                    },
1487                                };
1488                                window.with_content_mask(Some(mask), |window| {
1489                                    window.paint_quad(quad(
1490                                        rect,
1491                                        shell_corners,
1492                                        fill_tint,
1493                                        Edges::default(),
1494                                        Hsla::transparent_black(),
1495                                        gpui_kit::BorderStyle::Solid,
1496                                    ));
1497                                });
1498                            }
1499                        }
1500                        window.paint_quad(quad(
1501                            rect,
1502                            shell_corners,
1503                            Hsla::transparent_black(),
1504                            Edges::all(px(1.0)),
1505                            shell_border,
1506                            gpui_kit::BorderStyle::Solid,
1507                        ));
1508                    },
1509                )
1510                .absolute()
1511                .top_0()
1512                .bottom_0()
1513                .left(px(-stretch_left))
1514                .right(px(-stretch_right)),
1515            )
1516            .child(handle_el)
1517            .child(
1518                div()
1519                    .flex_1()
1520                    .min_w_0()
1521                    .h_full()
1522                    .pr(px(10.0))
1523                    .ml(px(lean_x))
1524                    .flex()
1525                    .flex_row()
1526                    .items_center()
1527                    .gap(px(2.0))
1528                    .child(
1529                        div()
1530                            .id(value_input_id)
1531                            .flex_1()
1532                            .min_w_0()
1533                            .h_full()
1534                            .pl(px(4.0))
1535                            .flex()
1536                            .flex_row()
1537                            .items_center()
1538                            .overflow_hidden()
1539                            .text_size(font_sz)
1540                            .text_color(colors.foreground)
1541                            .when(!disabled, |this| {
1542                                this.cursor_text().on_mouse_down(
1543                                    MouseButton::Left,
1544                                    move |_, window, cx| {
1545                                        let already_focused = focus_for_click.is_focused(window);
1546                                        window.focus(&focus_for_click, cx);
1547                                        int_field_click.update(cx, |s, _| {
1548                                            if !already_focused {
1549                                                s.was_focused = true;
1550                                                s.draft = formatted_for_click.to_string();
1551                                                s.select_all = true;
1552                                            } else {
1553                                                s.select_all = !s.select_all;
1554                                            }
1555                                        });
1556                                        window.refresh();
1557                                    },
1558                                )
1559                            })
1560                            .child(
1561                                div()
1562                                    .flex()
1563                                    .flex_row()
1564                                    .items_center()
1565                                    .px(px(2.0))
1566                                    .rounded(px(4.0))
1567                                    .when(
1568                                        is_input_focused
1569                                            && snap.select_all
1570                                            && !shown_text.is_empty(),
1571                                        |this| this.bg(select_bg),
1572                                    )
1573                                    .child(shown_text)
1574                                    .when(is_input_focused && !snap.select_all, |this| {
1575                                        this.child(
1576                                            div().ml(px(1.0)).w(px(1.5)).h(px(14.0)).child(
1577                                                canvas(
1578                                                    |_, _, _| {},
1579                                                    move |rect, _, window, _| {
1580                                                        window.paint_quad(quad(
1581                                                            Bounds {
1582                                                                origin: point(
1583                                                                    rect.origin.x,
1584                                                                    rect.origin.y,
1585                                                                ),
1586                                                                size: size(
1587                                                                    px(1.5),
1588                                                                    rect.size.height,
1589                                                                ),
1590                                                            },
1591                                                            Corners::all(px(0.75)),
1592                                                            caret_color,
1593                                                            Edges::default(),
1594                                                            Hsla::transparent_black(),
1595                                                            gpui_kit::BorderStyle::Solid,
1596                                                        ));
1597                                                    },
1598                                                )
1599                                                .size_full(),
1600                                            ),
1601                                        )
1602                                    }),
1603                            ),
1604                    )
1605                    .when_some(unit_el, |this, u| this.child(u)),
1606            )
1607            .when_some(tag_el, |this, tag| this.child(tag))
1608    }
1609}
1610
1611#[cfg(test)]
1612mod tests {
1613    use super::*;
1614
1615    #[test]
1616    fn evaluate_scrub_expression_parses_arithmetic_parentheses_and_units() {
1617        let units: Vec<SharedString> = vec!["px".into(), "%".into(), "deg".into()];
1618
1619        let (v1, u1) = evaluate_scrub_expression("12 * 2", &units).expect("valid product");
1620        assert!((v1 - 24.0).abs() < 1e-6);
1621        assert_eq!(u1, None);
1622
1623        let (v2, u2) =
1624            evaluate_scrub_expression("(100 - 24) / 2 %", &units).expect("valid paren + unit");
1625        assert!((v2 - 38.0).abs() < 1e-6);
1626        assert_eq!(u2, Some(SharedString::from("%")));
1627
1628        // Degree symbol alias `°` -> `deg`
1629        let (v3, u3) = evaluate_scrub_expression("45° * 2", &units).expect("degree alias");
1630        assert!((v3 - 90.0).abs() < 1e-6);
1631        assert_eq!(u3, Some(SharedString::from("deg")));
1632
1633        // Unknown unit or invalid syntax returns None
1634        assert!(evaluate_scrub_expression("50vw", &units).is_none());
1635        assert!(evaluate_scrub_expression("10 / 0", &units).is_none());
1636        assert!(evaluate_scrub_expression("(10 + 2", &units).is_none());
1637    }
1638
1639    #[test]
1640    fn scrub_input_rubber_approaches_12px_limit() {
1641        assert!(scrub_input_rubber(0.0, 12.0).abs() < 1e-5);
1642        let r18 = scrub_input_rubber(18.0, 12.0);
1643        let r90 = scrub_input_rubber(90.0, 12.0);
1644        assert!(r18 > 4.0 && r18 < 12.0);
1645        assert!(r90 > r18 && r90 < 12.0);
1646    }
1647
1648    #[test]
1649    fn constrain_scrub_value_wraps_angles_and_clamps_linear_ranges() {
1650        assert!((constrain_scrub_value(370.0, 0.0, 360.0, 0, true) - 10.0).abs() < 1e-6);
1651        assert!((constrain_scrub_value(-15.0, 0.0, 360.0, 0, true) - 345.0).abs() < 1e-6);
1652        assert!((constrain_scrub_value(120.0, 0.0, 100.0, 0, false) - 100.0).abs() < 1e-6);
1653    }
1654}