cotis-interactivity 0.1.0-alpha

Higher-level input managers for Cotis applications
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Wheel and drag scrolling with optional momentum.
//!
//! Low-level scroll algorithms ([`MomentumScroller`], [`HardScroller`]) accumulate
//! per-axis offsets. Element managers combine wheel input, optional mouse drag, and
//! layout bounds to produce clamped scroll positions.
//!
//! Scroll positions use `0.0` when content is aligned to the top-left of the clip
//! region. Scrolling content up or left produces **negative** values. Valid range
//! per axis is `[−limits, 0]` where `limits = (internal_size − bound_size).max(0)`.
//!
//! Layout bounds come from [`cotis_utils::element_state::ElementBoundingBox`] and
//! internal content size from [`cotis_utils::element_state::ElementClipInternalSize`].

use crate::mouse::{FullElementCursorState, MouseButtonManager, MouseClickingStrategy};
use cotis::cotis_app::CotisApp;
use cotis::layout::LayoutManagerCompatible;
use cotis::renders::RenderCompatibleWith;
use cotis::utils::ElementId;
use cotis_utils::element_state::{ElementBoundingBox, ElementClipInternalSize};
use cotis_utils::interactivity::mouse::{MouseButton, MouseProvider};
use cotis_utils::math::{BoundingBox, Vector2};

/// Per-axis scroll algorithm wrapper.
pub enum ScrollAlgorithm {
    /// Inertial scrolling with friction decay.
    Momentum(MomentumScroller),
    /// Direct delta accumulation without momentum.
    HardScroll(HardScroller),
}

impl ScrollAlgorithm {
    /// Returns the current scroll offset for this axis.
    pub fn get_position(&self) -> f32 {
        match self {
            ScrollAlgorithm::Momentum(momentum) => momentum.get_position(),
            ScrollAlgorithm::HardScroll(hard) => hard.get_position(),
        }
    }
}

/// Scroll offset with velocity-based momentum and frame-rate-independent friction.
#[derive(Debug, Clone, Copy)]
pub struct MomentumScroller {
    /// Current scroll offset on this axis.
    pub position: f32,
    /// Multiplier applied to scroll deltas.
    pub scale: f32,
    /// Current scroll velocity in pixels per second.
    pub velocity: f32,
    /// Stored friction factor (`1.0 − friction` passed to [`new`](Self::new)).
    ///
    /// Momentum decay uses `friction.powf(dt * 60.0)` each frame.
    pub friction: f32,
    /// Velocity magnitudes below this threshold are zeroed out.
    pub min_velocity: f32,
}

impl MomentumScroller {
    /// Creates a momentum scroller at position zero.
    ///
    /// * `scale` — multiplier for scroll deltas.
    /// * `friction` — per-60-fps-step decay factor; must satisfy `0.0 < friction < 1.0`.
    ///   Stored internally as `1.0 - friction`.
    /// * `min_velocity` — stop threshold; must be positive.
    ///
    /// # Panics
    ///
    /// Panics if `friction` is not in `(0.0, 1.0)` or if `min_velocity <= 0.0`.
    pub fn new(scale: f32, friction: f32, min_velocity: f32) -> Self {
        assert!(friction > 0.0 && friction < 1.0);
        assert!(min_velocity > 0.0);
        Self {
            position: 0.0,
            scale,
            velocity: 0.0,
            friction: 1.0 - friction,
            min_velocity,
        }
    }

    /// Sets the scroll position and clears velocity.
    pub fn direct_set_position(&mut self, position: f32) {
        self.position = position;
        self.velocity = 0.0;
    }

    /// Advances scroll state for one frame.
    ///
    /// When `d_scroll != 0`, applies the delta and sets velocity from `d_scroll / dt`.
    /// When `d_scroll == 0`, applies momentum with friction decay.
    ///
    /// # Examples
    ///
    /// ```
    /// use cotis_interactivity::scroll::MomentumScroller;
    ///
    /// let mut scroller = MomentumScroller::new(1.0, 0.1, 0.5);
    /// scroller.update(10.0, 1.0 / 60.0);
    /// assert!(scroller.get_position() > 0.0);
    ///
    /// // Momentum continues when no new delta is applied
    /// scroller.update(0.0, 1.0 / 60.0);
    /// assert!(scroller.velocity.abs() > 0.0 || scroller.get_position() > 10.0);
    /// ```
    pub fn update(&mut self, d_scroll: f32, dt: f32) {
        if d_scroll != 0.0 {
            self.position += d_scroll * self.scale;
            if dt > 0.0 {
                self.velocity = d_scroll * self.scale / dt;
            }
        } else {
            self.position += self.velocity * dt;

            // Apply friction (frame-rate independent; friction is per 60fps step)
            let friction_per_step = self.friction.powf(dt * 60.0);
            self.velocity *= friction_per_step;

            if self.velocity.abs() < self.min_velocity {
                self.velocity = 0.0;
            }
        }
    }

    /// Returns the current scroll offset.
    pub fn get_position(&self) -> f32 {
        self.position
    }
}

/// Direct scroll offset without momentum.
#[derive(Debug, Clone, Copy)]
pub struct HardScroller {
    /// Current scroll offset on this axis.
    pub position: f32,
    /// Multiplier applied to scroll deltas.
    pub scale: f32,
}

impl HardScroller {
    /// Creates a hard scroller at position zero.
    pub fn new(scale: f32) -> Self {
        Self {
            position: 0.0,
            scale,
        }
    }

    /// Sets the scroll position directly.
    pub fn direct_set_position(&mut self, position: f32) {
        self.position = position;
    }

    /// Applies a scroll delta for one frame.
    ///
    /// # Examples
    ///
    /// ```
    /// use cotis_interactivity::scroll::HardScroller;
    ///
    /// let mut scroller = HardScroller::new(1.0);
    /// scroller.update(5.0, 0.0);
    /// assert_eq!(scroller.get_position(), 5.0);
    /// ```
    pub fn update(&mut self, d_scroll: f32, _dt: f32) {
        self.position += d_scroll * self.scale;
    }

    /// Returns the current scroll offset.
    pub fn get_position(&self) -> f32 {
        self.position
    }
}

/// Independent scroll algorithms for horizontal (`[0]`) and vertical (`[1]`) axes.
pub struct DoubleAxisScrollManager {
    scroll: [ScrollAlgorithm; 2],
}

impl DoubleAxisScrollManager {
    /// Creates a manager from per-axis algorithms.
    ///
    /// Index `0` is the horizontal axis; index `1` is the vertical axis.
    pub fn new(scroll: [ScrollAlgorithm; 2]) -> Self {
        Self { scroll }
    }

    /// Sets scroll position on both axes and clears momentum velocity.
    pub fn direct_set_position(&mut self, position: Vector2) {
        match &mut self.scroll[0] {
            ScrollAlgorithm::Momentum(m) => {
                m.direct_set_position(position.x);
            }
            ScrollAlgorithm::HardScroll(h) => {
                h.direct_set_position(position.x);
            }
        }
        match &mut self.scroll[1] {
            ScrollAlgorithm::Momentum(m) => {
                m.direct_set_position(position.y);
            }
            ScrollAlgorithm::HardScroll(h) => {
                h.direct_set_position(position.y);
            }
        }
    }

    /// Applies per-axis scroll deltas for one frame.
    pub fn update(&mut self, d_scroll_x: f32, d_scroll_y: f32, dt: f32) {
        match &mut self.scroll[0] {
            ScrollAlgorithm::Momentum(m) => {
                m.update(d_scroll_x, dt);
            }
            ScrollAlgorithm::HardScroll(h) => {
                h.update(d_scroll_x, dt);
            }
        }
        match &mut self.scroll[1] {
            ScrollAlgorithm::Momentum(m) => {
                m.update(d_scroll_y, dt);
            }
            ScrollAlgorithm::HardScroll(h) => {
                h.update(d_scroll_y, dt);
            }
        }
    }

    /// Returns the current scroll offset as a [`Vector2`].
    pub fn get_position(&self) -> Vector2 {
        Vector2 {
            x: self.scroll[0].get_position(),
            y: self.scroll[1].get_position(),
        }
    }
}

/// Scroll manager for a single axis.
pub enum SingleAxisScrollManager {
    /// Horizontal scrolling; vertical component of [`get_position`](Self::get_position) is zero.
    Horizontal(ScrollAlgorithm),
    /// Vertical scrolling; horizontal component of [`get_position`](Self::get_position) is zero.
    Vertical(ScrollAlgorithm),
}

impl SingleAxisScrollManager {
    /// Sets scroll position on the active axis.
    pub fn direct_set_position(&mut self, position: f32) {
        match self {
            SingleAxisScrollManager::Horizontal(ScrollAlgorithm::Momentum(m)) => {
                m.direct_set_position(position);
            }
            SingleAxisScrollManager::Horizontal(ScrollAlgorithm::HardScroll(h)) => {
                h.direct_set_position(position);
            }
            SingleAxisScrollManager::Vertical(ScrollAlgorithm::Momentum(m)) => {
                m.direct_set_position(position);
            }
            SingleAxisScrollManager::Vertical(ScrollAlgorithm::HardScroll(h)) => {
                h.direct_set_position(position);
            }
        }
    }

    /// Applies a scroll delta on the active axis for one frame.
    pub fn update(&mut self, d_scroll: f32, dt: f32) {
        match self {
            SingleAxisScrollManager::Horizontal(ScrollAlgorithm::Momentum(m)) => {
                m.update(d_scroll, dt);
            }
            SingleAxisScrollManager::Horizontal(ScrollAlgorithm::HardScroll(h)) => {
                h.update(d_scroll, dt);
            }
            SingleAxisScrollManager::Vertical(ScrollAlgorithm::Momentum(m)) => {
                m.update(d_scroll, dt);
            }
            SingleAxisScrollManager::Vertical(ScrollAlgorithm::HardScroll(h)) => {
                h.update(d_scroll, dt);
            }
        }
    }

    /// Returns the current scroll offset; the inactive axis is `0.0`.
    pub fn get_position(&self) -> Vector2 {
        match self {
            SingleAxisScrollManager::Horizontal(s) => Vector2 {
                x: s.get_position(),
                y: 0.0,
            },
            SingleAxisScrollManager::Vertical(s) => Vector2 {
                x: 0.0,
                y: s.get_position(),
            },
        }
    }
}

/// Combines cursor state, wheel input, and layout bounds for element scrolling.
///
/// Implementors supply mouse position, wheel delta, bounding box, and internal
/// clip size for scroll clamping.
///
/// # Blanket implementation
///
/// [`CotisApp`] implements this trait when:
///
/// - `Renderer: RenderCompatibleWith<Manager> + MouseProvider`
/// - `Manager: LayoutManagerCompatible<Renderer> + ElementBoundingBox + ElementClipInternalSize`
pub trait FullElementScrollState: FullElementCursorState {
    /// Current cursor position in pixels.
    fn get_mouse_pos(&self) -> Vector2;
    /// Wheel delta; `x` is horizontal, `y` is vertical per [`MouseProvider`].
    fn get_mouse_wheel_move_v(&self) -> Vector2;
    /// Layout bounding box for the element.
    fn get_bound_box(&self, id: ElementId) -> Option<BoundingBox>;
    /// Internal clipped content size for scroll limit calculation.
    fn internal_size(&self, id: ElementId) -> Option<Vector2>;
}

impl<
    Renderer: RenderCompatibleWith<Manager> + MouseProvider,
    Manager: LayoutManagerCompatible<Renderer> + ElementBoundingBox + ElementClipInternalSize,
    Pipe,
> FullElementScrollState for CotisApp<Renderer, Manager, Pipe>
{
    fn get_mouse_pos(&self) -> Vector2 {
        self.render_borrow().get_mouse_position()
    }

    fn get_mouse_wheel_move_v(&self) -> Vector2 {
        self.render_borrow().get_mouse_wheel_move_v()
    }

    fn get_bound_box(&self, id: ElementId) -> Option<BoundingBox> {
        self.layout_manager_borrow().bounding_box(id)
    }

    fn internal_size(&self, id: ElementId) -> Option<Vector2> {
        self.layout_manager_borrow().clip_internal_size(id)
    }
}

/// Per-element two-axis scroll manager with wheel, optional drag, and clamping.
///
/// Combines wheel deltas from [`FullElementScrollState::get_mouse_wheel_move_v`]
/// with optional mouse-drag scrolling when `button` is `Some`. Drag delta is
/// `current_mouse_pos − previous_mouse_pos`; no delta is produced on the first
/// frame the button is held.
///
/// When the parent element is hovered but not yet pressed, hover on any
/// `child_elements` suppresses parent drag capture so children receive priority.
///
/// Scroll position is clamped to `[−limits, 0]` per axis after each update.
pub struct DoubleAxisScrollElementManager {
    id: ElementId,
    exclusive_mouse: MouseButtonManager,
    mouse_prev_pos: Option<Vector2>,
    manager: DoubleAxisScrollManager,
    button: Option<MouseButton>,
    child_elements: Vec<ElementId>,
}

impl DoubleAxisScrollElementManager {
    /// Creates a scroll manager for `id`.
    ///
    /// * `algorithms` — per-axis scroll algorithms; index `0` horizontal, `1` vertical.
    /// * `child_elements` — child IDs that take hover priority over parent drag.
    /// * `button` — mouse button for drag scrolling; `None` disables drag.
    pub fn new(
        algorithms: [ScrollAlgorithm; 2],
        id: ElementId,
        child_elements: Vec<ElementId>,
        button: Option<MouseButton>,
    ) -> Self {
        Self {
            id,
            exclusive_mouse: MouseButtonManager::new(MouseClickingStrategy::Pressed, 0.0),
            mouse_prev_pos: None,
            manager: DoubleAxisScrollManager::new(algorithms),
            button,
            child_elements,
        }
    }

    fn update_mouse(&mut self, provider: &dyn FullElementScrollState, dt: f32) {
        let mouse_button = {
            if let Some(button) = self.button {
                button
            } else {
                return;
            }
        };
        let mut hovered = provider.is_hovered(self.id);
        if hovered && !self.exclusive_mouse.is_clicked() {
            for child in self.child_elements.iter() {
                if provider.is_hovered(*child) {
                    hovered = false;
                    break;
                }
            }
        }
        self.exclusive_mouse
            .update(provider.mouse_button_down(mouse_button), dt, hovered);
    }

    fn get_mouse_drag_delta(
        &mut self,
        provider: &dyn FullElementScrollState,
        dt: f32,
    ) -> Option<Vector2> {
        self.update_mouse(provider, dt);
        let clicked = self.exclusive_mouse.is_clicked();
        if !clicked {
            self.mouse_prev_pos = None;
            return None;
        }
        let mouse_pos = provider.get_mouse_pos();

        let res = self.mouse_prev_pos.map(|mouse_prev_pos| {
            Vector2::new(
                mouse_pos.x - mouse_prev_pos.x,
                mouse_pos.y - mouse_prev_pos.y,
            )
        });
        self.mouse_prev_pos = Some(mouse_pos);

        res
    }

    /// Advances scroll state for one frame.
    ///
    /// No-op when layout bounds or internal size are unavailable for `id`.
    pub fn update(&mut self, provider: &dyn FullElementScrollState, dt: f32) {
        let wheel_scroll = provider.get_mouse_wheel_move_v();
        let mouse_scroll = self.get_mouse_drag_delta(provider, dt);
        let internal = provider.internal_size(self.id);
        let bound = provider.get_bound_box(self.id);
        if internal.is_none() || bound.is_none() {
            return;
        }
        let internal = internal.unwrap();
        let bound = bound.unwrap();
        let limits = Vector2 {
            x: (internal.x - bound.width).max(0.),
            y: (internal.y - bound.height).max(0.),
        };

        let scroll = if let Some(mouse_scroll) = mouse_scroll {
            Vector2 {
                x: wheel_scroll.x + mouse_scroll.x,
                y: wheel_scroll.y + mouse_scroll.y,
            }
        } else {
            wheel_scroll
        };
        self.manager.update(scroll.x, scroll.y, dt);
        let pos = self.manager.get_position();
        if pos.x < 0. || pos.x > -limits.x || pos.y < 0. || pos.y > -limits.y {
            self.manager.direct_set_position(Vector2::new(
                pos.x.min(0.0).max(-limits.x),
                pos.y.min(0.0).max(-limits.y),
            ));
        }
    }

    /// Returns the current clamped scroll offset.
    pub fn get_position(&self) -> Vector2 {
        self.manager.get_position()
    }
}

/// Per-element single-axis scroll manager with wheel, optional drag, and clamping.
///
/// Same wheel/drag/clamp behavior as [`DoubleAxisScrollElementManager`], but
/// scrolls only the axis selected by `manager`.
pub struct SingleAxisScrollElementManager {
    id: ElementId,
    exclusive_mouse: MouseButtonManager,
    mouse_prev_pos: Option<Vector2>,
    manager: SingleAxisScrollManager,
    button: Option<MouseButton>,
    child_elements: Vec<ElementId>,
}

impl SingleAxisScrollElementManager {
    /// Creates a single-axis scroll manager for `id`.
    pub fn new(
        manager: SingleAxisScrollManager,
        id: ElementId,
        child_elements: Vec<ElementId>,
        button: Option<MouseButton>,
    ) -> Self {
        Self {
            id,
            exclusive_mouse: MouseButtonManager::new(MouseClickingStrategy::Pressed, 0.0),
            mouse_prev_pos: None,
            manager,
            button,
            child_elements,
        }
    }

    fn update_mouse(&mut self, provider: &dyn FullElementScrollState, dt: f32) {
        let mouse_button = {
            if let Some(button) = self.button {
                button
            } else {
                return;
            }
        };
        let mut hovered = provider.is_hovered(self.id);
        if hovered && !self.exclusive_mouse.is_clicked() {
            for child in self.child_elements.iter() {
                if provider.is_hovered(*child) {
                    hovered = false;
                    break;
                }
            }
        }
        self.exclusive_mouse
            .update(provider.mouse_button_down(mouse_button), dt, hovered);
    }

    fn get_mouse_drag_delta(
        &mut self,
        provider: &dyn FullElementScrollState,
        dt: f32,
    ) -> Option<Vector2> {
        self.update_mouse(provider, dt);
        let clicked = self.exclusive_mouse.is_clicked();
        if !clicked {
            self.mouse_prev_pos = None;
            return None;
        }
        let mouse_pos = provider.get_mouse_pos();

        let res = self.mouse_prev_pos.map(|mouse_prev_pos| {
            Vector2::new(
                mouse_pos.x - mouse_prev_pos.x,
                mouse_pos.y - mouse_prev_pos.y,
            )
        });
        self.mouse_prev_pos = Some(mouse_pos);

        res
    }

    /// Advances scroll state for one frame.
    ///
    /// No-op when layout bounds or internal size are unavailable for `id`.
    pub fn update(&mut self, provider: &dyn FullElementScrollState, dt: f32) {
        let wheel_scroll = provider.get_mouse_wheel_move_v();
        let mouse_scroll = self.get_mouse_drag_delta(provider, dt);
        let internal = provider.internal_size(self.id);
        let bound = provider.get_bound_box(self.id);
        if internal.is_none() || bound.is_none() {
            return;
        }
        let internal = internal.unwrap();
        let bound = bound.unwrap();
        let limits = Vector2 {
            x: (internal.x - bound.width).max(0.),
            y: (internal.y - bound.height).max(0.),
        };

        let scroll = if let Some(mouse_scroll) = mouse_scroll {
            Vector2 {
                x: wheel_scroll.x + mouse_scroll.x,
                y: wheel_scroll.y + mouse_scroll.y,
            }
        } else {
            wheel_scroll
        };

        self.manager.update(
            match &self.manager {
                SingleAxisScrollManager::Horizontal(_) => scroll.x,
                SingleAxisScrollManager::Vertical(_) => scroll.y,
            },
            dt,
        );
        let pos = self.manager.get_position();

        if pos.x < 0. || pos.x > -limits.x || pos.y < 0. || pos.y > -limits.y {
            self.manager.direct_set_position(match &self.manager {
                SingleAxisScrollManager::Horizontal(_) => pos.x.min(0.0).max(-limits.x),
                SingleAxisScrollManager::Vertical(_) => pos.y.min(0.0).max(-limits.y),
            });
        }
    }

    /// Returns the current clamped scroll offset.
    pub fn get_position(&self) -> Vector2 {
        self.manager.get_position()
    }
}