retroglyph-ui 0.5.1

Immediate-mode terminal UI toolkit for retroglyph: widgets, layout, input/focus, theming, and animation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
use crate::interact::Response;

/// Configurable physics constants for [`ScrollState`].
///
/// Not `#[non_exhaustive]`: unlike this crate's enums, this type's whole point is direct struct-
/// literal construction, which `#[non_exhaustive]` would forbid for external crates (including
/// via functional update syntax). Construct a custom value off [`ScrollPhysics::DEFAULT`] with
/// functional update syntax instead of naming every field, so a field added here later needs at
/// most a call-site addition rather than a rewrite:
///
/// ```
/// use retroglyph_ui::state::ScrollPhysics;
///
/// let physics = ScrollPhysics { friction: 6.0, ..ScrollPhysics::DEFAULT };
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ScrollPhysics {
    /// Exponential friction decay constant. Higher means faster deceleration.
    pub friction: f32,
    /// Stiffness of the overscroll spring.
    pub stiffness: f32,
    /// Damping of the overscroll spring.
    pub damping: f32,
    /// Maximum rows/cells the viewport can be rubber-banded past the edge.
    pub rubber_band_limit: f32,
}

impl ScrollPhysics {
    /// The default scroll physics parameters as a constant.
    ///
    /// The spring pair (`stiffness`/`damping`) is close to but deliberately under critical
    /// damping: critical would be `damping = 2 * sqrt(stiffness) = 2 * sqrt(180) ~= 26.8`, and
    /// `24.0` sits just below that, so the rubber band settles with one small visible bounce
    /// rather than a dead stop. `friction` and the `stiffness` magnitude were tuned by feel for a
    /// row-per-item viewport at ~60fps, not derived; treat them as adjustable.
    pub const DEFAULT: Self = Self {
        friction: 4.5,
        stiffness: 180.0,
        damping: 24.0,
        rubber_band_limit: 4.0,
    };
}

impl Default for ScrollPhysics {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// Scroll state for smooth, momentum-based scrolling with rubber-banding.
///
/// Keeps track of the current fractional scroll offset, velocity, and
/// drag-to-scroll gestures. Completely separate from drawing, and generic over
/// time: takes a time delta step to decay velocity or animate snap-back,
/// making it deterministic and suitable for unit tests.
///
/// For a *row*-based viewport (a menu, a list of fixed-height items) where content scrolls a
/// whole row at a time and there's no momentum to animate, reach for [`crate::state::ListState`]
/// instead: its `offset` is a plain `usize`, clamped only at zero, with no velocity or physics
/// step. The two don't compose into one type on purpose (see [`crate::state::ListState`]'s own doc
/// comment): pick whichever one matches what's actually scrolling: continuous/pixel-ish
/// content reaches for `ScrollState`, a discrete item list reaches for `ListState`.
#[derive(Clone, Debug, PartialEq)]
pub struct ScrollState {
    offset: f32,
    velocity: f32,
    dragging: bool,
    time_accumulator: f32,
    last_pointer_y: f32,
    /// Recent (time, pointer-y) samples for estimating fling velocity at drag end, oldest first.
    /// Four is enough to average out one jittery pointer report while staying inside the ~150ms
    /// look-back window `calculate_fling_velocity` uses; more just holds staler samples the
    /// window discards anyway. Only `samples[..sample_len]` is meaningful.
    samples: [(f32, f32); 4],
    sample_len: usize,
    physics: ScrollPhysics,
}

impl Default for ScrollState {
    fn default() -> Self {
        Self::new()
    }
}

#[allow(clippy::suboptimal_flops)]
impl ScrollState {
    /// Create a new `ScrollState` at offset 0.0 with default physics.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            offset: 0.0,
            velocity: 0.0,
            dragging: false,
            time_accumulator: 0.0,
            last_pointer_y: 0.0,
            samples: [(0.0, 0.0); 4],
            sample_len: 0,
            physics: ScrollPhysics::DEFAULT,
        }
    }

    /// Create a new `ScrollState` with custom physics.
    #[must_use]
    pub const fn with_physics(physics: ScrollPhysics) -> Self {
        Self {
            offset: 0.0,
            velocity: 0.0,
            dragging: false,
            time_accumulator: 0.0,
            last_pointer_y: 0.0,
            samples: [(0.0, 0.0); 4],
            sample_len: 0,
            physics,
        }
    }

    /// The current fractional scroll offset.
    #[must_use]
    pub const fn offset(&self) -> f32 {
        self.offset
    }

    /// Set the offset directly, clamping it to bounds.
    pub const fn set_offset(&mut self, offset: f32, max_offset: f32) {
        let max = if max_offset > 0.0 { max_offset } else { 0.0 };
        self.offset = if offset < 0.0 {
            0.0
        } else if offset > max {
            max
        } else {
            offset
        };
        self.velocity = 0.0;
    }

    /// The current velocity in items/second.
    #[must_use]
    pub const fn velocity(&self) -> f32 {
        self.velocity
    }

    /// Whether a drag gesture is currently active.
    #[must_use]
    pub const fn dragging(&self) -> bool {
        self.dragging
    }

    /// Returns the integer part of the offset, clamped to positive.
    #[must_use]
    pub fn integer_offset(&self) -> usize {
        if self.offset < 0.0 {
            0
        } else {
            // `self.offset` is checked non-negative above and scroll offsets never approach
            // usize::MAX, so truncation can't happen in practice.
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            {
                self.offset as usize
            }
        }
    }

    /// Returns the fractional remainder of the offset (0.0..1.0).
    #[must_use]
    pub fn fractional_offset(&self) -> f32 {
        if self.offset < 0.0 {
            self.offset
        } else {
            // Truncate to the integer part via usize (offset is non-negative here), then back to
            // f32 to subtract. Scroll offsets stay well under 2^24 items, so the round-trip is
            // exact in practice despite f32's 23-bit mantissa.
            #[allow(
                clippy::cast_possible_truncation,
                clippy::cast_sign_loss,
                clippy::cast_precision_loss
            )]
            let int_part = self.offset as usize as f32;
            self.offset - int_part
        }
    }

    /// Update physics for a single frame step.
    ///
    /// Decays momentum if in bounds, or animates the rubber-band spring back to
    /// boundaries if out of bounds. Has no effect if dragging is active.
    #[allow(clippy::while_float)]
    pub fn tick(&mut self, dt: core::time::Duration, max_offset: f32) {
        let dt_secs = dt.as_secs_f32();
        if dt_secs <= 0.0 {
            return;
        }
        self.time_accumulator += dt_secs;

        if self.dragging {
            return;
        }

        let max_offset = max_offset.max(0.0);
        // 8ms cap so a long frame delta is integrated as several small spring steps instead of
        // one large one. The explicit spring integration below diverges once a single step grows
        // past roughly `1 / sqrt(stiffness)` seconds; 8ms stays well inside that for the default
        // stiffness of 180 and still subdivides a dropped-to-30fps 33ms frame into 5 steps.
        let max_step = 0.008;
        let mut remaining = dt_secs;

        while remaining > 0.0 {
            let step = remaining.min(max_step);
            remaining -= step;

            if self.offset >= 0.0 && self.offset <= max_offset {
                // In bounds: apply friction decay
                self.velocity *= retroglyph_core::math::exp(-self.physics.friction * step);
                self.offset += self.velocity * step;

                // Stop moving once velocity drops below 0.05 items/second: below this the
                // remaining motion is imperceptible per frame, so snapping to zero avoids an
                // indefinite exponential tail that never quite reaches exactly 0.0.
                if self.velocity.abs() < 0.05 {
                    self.velocity = 0.0;
                }
            } else {
                // Out of bounds: apply spring snapback force
                let target = if self.offset < 0.0 { 0.0 } else { max_offset };
                let overshoot = self.offset - target;

                let force = -overshoot * self.physics.stiffness;
                let damping_force = -self.velocity * self.physics.damping;
                let acceleration = force + damping_force;

                self.velocity += acceleration * step;
                self.offset += self.velocity * step;

                // Snap to target once within 0.01 items and slower than 0.2 items/second: both
                // thresholds were picked by feel as "close enough to be indistinguishable", not
                // derived; the pair together avoids a spring that oscillates forever chasing an
                // exact zero.
                if (self.offset - target).abs() < 0.01 && self.velocity.abs() < 0.2 {
                    self.offset = target;
                    self.velocity = 0.0;
                    break;
                }
            }
        }
    }

    /// Begin a drag gesture at pointer coordinate `y`.
    pub const fn begin_drag(&mut self, y: f32) {
        self.dragging = true;
        self.velocity = 0.0;
        self.last_pointer_y = y;
        self.samples = [(0.0, 0.0); 4];
        self.sample_len = 0;
        self.record_sample(self.time_accumulator, y);
    }

    /// Update the drag gesture with a new pointer coordinate `y`.
    pub fn update_drag(&mut self, y: f32, max_offset: f32) {
        if !self.dragging {
            self.begin_drag(y);
            return;
        }

        let mut delta_y = self.last_pointer_y - y; // dragging UP increases offset
        let max_offset = max_offset.max(0.0);
        let proposed = self.offset + delta_y;

        // Apply rubber-band resistance when dragging past boundaries
        if proposed < 0.0 && delta_y < 0.0 {
            let overshoot = if self.offset < 0.0 {
                -self.offset
            } else {
                -proposed / 2.0
            };
            let resistance = (1.0 - overshoot / self.physics.rubber_band_limit).clamp(0.0, 1.0);
            delta_y *= resistance;
        } else if proposed > max_offset && delta_y > 0.0 {
            let overshoot = if self.offset > max_offset {
                self.offset - max_offset
            } else {
                (proposed - max_offset) / 2.0
            };
            let resistance = (1.0 - overshoot / self.physics.rubber_band_limit).clamp(0.0, 1.0);
            delta_y *= resistance;
        }

        self.offset += delta_y;
        self.last_pointer_y = y;
        self.record_sample(self.time_accumulator, y);
    }

    /// End the current drag gesture, initiating a fling if pointer speed was sufficient.
    pub fn end_drag(&mut self) {
        if !self.dragging {
            return;
        }
        self.dragging = false;
        self.velocity = self.calculate_fling_velocity();
    }

    /// Apply a scroll wheel impulse directly to velocity.
    pub fn scroll_by_wheel(&mut self, delta: f32) {
        if !self.dragging {
            // One wheel notch -> 12 items/second of fling; paired with `friction: 4.5` this coasts
            // a notch roughly two-to-three rows before stopping. Tuned by feel, not derived.
            self.velocity += delta * 12.0;
        }
    }

    /// Feeds a frame's resolved [`Response::scroll_delta`] straight into
    /// [`scroll_by_wheel`](Self::scroll_by_wheel), so a widget wires wheel input by calling
    /// [`Interaction::interact`](crate::interact::Interaction::interact) with [`Sense::SCROLL`](crate::interact::Sense::SCROLL)
    /// and handing the [`Response`] here, instead of re-deriving it from raw
    /// [`MouseEventKind::Scroll`](retroglyph_core::event::MouseEventKind::Scroll) events the way a widget
    /// with no route to `ScrollState` has to.
    ///
    /// A no-op if nothing scrolled this frame (`scroll_delta` is `0`), which also makes this safe
    /// to call unconditionally every frame rather than gating it on a dirty check first. Drag-to-scroll
    /// isn't covered here: `Response` reports only *whether* a drag is in progress
    /// ([`Response::dragging`]), not a pointer position, so that gesture still goes through
    /// [`begin_drag`](Self::begin_drag)/[`update_drag`](Self::update_drag)/[`end_drag`](Self::end_drag)
    /// directly, using [`Interaction::pointer`](crate::interact::Interaction::pointer)'s position alongside
    /// this `Response`.
    ///
    /// # Examples
    ///
    /// ```
    /// use retroglyph_core::grid::Rect;
    /// use retroglyph_ui::interact::{Interaction, Sense};
    /// use retroglyph_ui::state::ScrollState;
    ///
    /// #[derive(Clone, Copy, PartialEq, Eq)]
    /// struct Id;
    ///
    /// let mut interaction = Interaction::new();
    /// let mut scroll = ScrollState::new();
    ///
    /// interaction.begin_frame();
    /// let response = interaction.interact(Rect::new(0, 0, 10, 5), Id, Sense::scroll());
    /// scroll.apply(&response); // a no-op here: nothing scrolled this frame
    /// interaction.end_frame();
    ///
    /// assert_eq!(scroll.velocity(), 0.0);
    /// ```
    pub fn apply<Id>(&mut self, response: &Response<Id>) {
        let delta = response.scroll_delta();
        if delta != 0 {
            #[allow(clippy::cast_precision_loss)] // scroll deltas stay tiny: a handful of wheel
            // notches per frame, nowhere near f32's 24-bit exact-integer range.
            self.scroll_by_wheel(delta as f32);
        }
    }

    const fn record_sample(&mut self, time: f32, y: f32) {
        if self.sample_len < self.samples.len() {
            self.samples[self.sample_len] = (time, y);
            self.sample_len += 1;
        } else {
            // Full: evict the oldest by shifting everything left one slot, then append. Hand-
            // written instead of `copy_within` because this runs in a `const fn` (`copy_within`
            // isn't const-stable) and the array is fixed at 4 elements.
            let mut i = 0;
            while i + 1 < self.samples.len() {
                self.samples[i] = self.samples[i + 1];
                i += 1;
            }
            self.samples[self.samples.len() - 1] = (time, y);
        }
    }

    fn calculate_fling_velocity(&self) -> f32 {
        let samples = &self.samples[..self.sample_len];

        if samples.len() < 2 {
            return 0.0;
        }

        let newest = samples[samples.len() - 1];

        // If the latest sample is older than 100ms, the pointer stopped moving before the drag
        // ended (drag paused, not a fling): 100ms is long enough that a genuinely flinging finger
        // would still be producing fresh samples, but short enough to reject a deliberate pause.
        if self.time_accumulator - newest.0 > 0.1 {
            return 0.0;
        }

        // Look back for oldest sample within 150ms of newest
        let mut oldest = newest;
        for &sample in samples[..samples.len() - 1].iter().rev() {
            // 150ms look-back: recent enough to reflect the finger's final motion, long enough
            // to smooth over one or two skipped/jittery pointer reports. Widening it would average
            // in motion from earlier in the drag that no longer reflects the release speed.
            if newest.0 - sample.0 <= 0.15 {
                oldest = sample;
            } else {
                break;
            }
        }

        let dt = newest.0 - oldest.0;
        // Guard against dividing by a near-zero time delta, which would produce a huge spurious
        // velocity from two samples that are really just one pointer report apart.
        if dt < 0.01 {
            return 0.0;
        }

        (oldest.1 - newest.1) / dt
    }
}

#[cfg(test)]
#[allow(clippy::float_cmp)]
mod tests {
    use super::*;

    #[test]
    fn scroll_state_starts_at_zero() {
        let s = ScrollState::new();
        assert_eq!(s.offset(), 0.0);
        assert_eq!(s.velocity(), 0.0);
        assert!(!s.dragging());
        assert_eq!(s.integer_offset(), 0);
        assert_eq!(s.fractional_offset(), 0.0);
    }

    #[test]
    fn scroll_state_set_offset_clamps() {
        let mut s = ScrollState::new();
        s.set_offset(10.0, 5.0);
        assert_eq!(s.offset(), 5.0);
        s.set_offset(-2.0, 5.0);
        assert_eq!(s.offset(), 0.0);
    }

    #[test]
    fn scroll_state_drag_moves_offset() {
        let mut s = ScrollState::new();
        s.begin_drag(10.0);
        assert!(s.dragging());
        s.update_drag(7.0, 10.0);
        assert_eq!(s.offset(), 3.0);
        s.update_drag(8.0, 10.0);
        assert_eq!(s.offset(), 2.0);
    }

    #[test]
    fn scroll_state_drag_resistance_past_bounds() {
        let mut s = ScrollState::new();
        s.begin_drag(10.0);
        s.update_drag(15.0, 10.0);
        assert!(s.offset() < 0.0);
        assert!(s.offset() > -5.0);

        let mut s = ScrollState::new();
        s.set_offset(10.0, 10.0);
        s.begin_drag(10.0);
        s.update_drag(5.0, 10.0);
        assert!(s.offset() > 10.0);
        assert!(s.offset() < 15.0);
    }

    #[test]
    fn scroll_state_fling_momentum_and_friction() {
        let mut s = ScrollState::new();
        s.begin_drag(10.0);
        s.tick(core::time::Duration::from_millis(50), 10.0);
        s.update_drag(5.0, 10.0);
        s.tick(core::time::Duration::from_millis(50), 10.0);
        s.update_drag(0.0, 10.0);
        s.end_drag();

        assert!(s.velocity() > 0.0);
        let init_vel = s.velocity();

        s.tick(core::time::Duration::from_millis(100), 10.0);
        assert!(s.velocity() < init_vel);
        assert!(s.offset() > 10.0);
    }

    #[test]
    fn scroll_state_fling_velocity_wraps_past_four_samples() {
        // Drives 6 update_drag calls (7 samples total including begin_drag's), forcing the
        // 4-slot sample buffer to evict twice. This exercises the eviction path (`sample_len ==
        // samples.len()` in `record_sample`), which no other test reaches.
        let mut s = ScrollState::new();
        s.begin_drag(0.0);
        for step in 1_u32..=6 {
            s.tick(core::time::Duration::from_millis(10), 10.0);
            #[allow(clippy::cast_precision_loss)] // step stays well under f32's exact range
            s.update_drag(step as f32, 10.0);
        }
        s.end_drag();

        // Pointer moved consistently in the positive-y direction, i.e. offset decreasing, so the
        // fling velocity should be negative (matches update_drag's `delta_y = last - y` sign
        // convention for downward drag).
        assert!(s.velocity() < 0.0);
    }

    #[test]
    fn scroll_state_spring_snapback() {
        let mut s = ScrollState::new();
        s.offset = -2.0;
        assert_eq!(s.offset(), -2.0);

        s.tick(core::time::Duration::from_millis(100), 10.0);
        assert!(s.offset() > -2.0);

        for _ in 0..50 {
            s.tick(core::time::Duration::from_millis(16), 10.0);
        }
        assert_eq!(s.offset(), 0.0);
        assert_eq!(s.velocity(), 0.0);
    }

    #[test]
    fn scroll_state_scroll_wheel() {
        let mut s = ScrollState::new();
        s.scroll_by_wheel(2.0);
        assert!(s.velocity() > 0.0);
        s.tick(core::time::Duration::from_millis(100), 10.0);
        assert!(s.offset() > 0.0);
    }

    fn response_with_scroll_delta(scroll_delta: i32) -> Response<()> {
        Response {
            scroll_delta,
            ..Response::default()
        }
    }

    #[test]
    fn apply_feeds_scroll_delta_into_the_wheel_impulse() {
        let mut applied = ScrollState::new();
        applied.apply(&response_with_scroll_delta(2));

        let mut direct = ScrollState::new();
        direct.scroll_by_wheel(2.0);

        assert_eq!(applied.velocity(), direct.velocity());
        assert!(applied.velocity() > 0.0);
    }

    #[test]
    fn apply_is_a_no_op_when_nothing_scrolled() {
        let mut s = ScrollState::new();
        s.apply(&response_with_scroll_delta(0));
        assert_eq!(s.velocity(), 0.0);
        assert_eq!(s.offset(), 0.0);
    }

    #[test]
    fn apply_negative_delta_scrolls_backward() {
        let mut s = ScrollState::new();
        s.set_offset(5.0, 10.0);
        s.apply(&response_with_scroll_delta(-1));
        assert!(s.velocity() < 0.0);
    }

    #[test]
    fn apply_is_ignored_while_dragging_like_scroll_by_wheel() {
        let mut s = ScrollState::new();
        s.begin_drag(0.0);
        s.apply(&response_with_scroll_delta(3));
        assert_eq!(s.velocity(), 0.0);
    }
}