egui-cha 0.6.0

TEA (The Elm Architecture) framework for egui
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
//! Throttle helper for TEA applications
//!
//! Throttling limits action frequency to at most once per interval.
//! Useful for scroll events, resize handlers, rate-limited APIs, etc.

use super::clock::Clock;
use crate::Cmd;
use std::time::{Duration, Instant};

/// Throttler - limits action frequency
///
/// # How it works
/// The first call to `run()` executes immediately. Subsequent calls within
/// the throttle interval are ignored. After the interval passes, the next
/// call will execute again.
///
/// # Example
/// ```ignore
/// use egui_cha::helpers::Throttler;
/// use std::time::Duration;
///
/// struct Model {
///     scroll_pos: f32,
///     scroll_throttle: Throttler,
/// }
///
/// enum Msg {
///     Scroll(f32),
///     UpdateVisibleItems,
/// }
///
/// fn update(model: &mut Model, msg: Msg) -> Cmd<Msg> {
///     match msg {
///         Msg::Scroll(pos) => {
///             model.scroll_pos = pos;
///             // Only fires at most once per 100ms
///             model.scroll_throttle.run(
///                 Duration::from_millis(100),
///                 || Cmd::msg(Msg::UpdateVisibleItems),
///             )
///         }
///         Msg::UpdateVisibleItems => {
///             // Expensive computation, throttled
///             Cmd::none()
///         }
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Throttler {
    last_run: Option<Instant>,
}

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

impl Throttler {
    /// Create a new throttler
    pub fn new() -> Self {
        Self { last_run: None }
    }

    /// Run an action if not throttled
    ///
    /// If the throttle interval has passed since the last run (or this is
    /// the first call), executes the action and returns its result.
    /// Otherwise, returns `Cmd::none()`.
    ///
    /// # Arguments
    /// - `interval`: Minimum time between executions
    /// - `action`: Closure that returns a `Cmd<Msg>`
    pub fn run<Msg, F>(&mut self, interval: Duration, action: F) -> Cmd<Msg>
    where
        F: FnOnce() -> Cmd<Msg>,
    {
        let now = Instant::now();

        let should_run = match self.last_run {
            None => true,
            Some(last) => now.duration_since(last) >= interval,
        };

        if should_run {
            self.last_run = Some(now);
            action()
        } else {
            Cmd::none()
        }
    }

    /// Run with a message (convenience method)
    ///
    /// Emits the message if not throttled.
    pub fn run_msg<Msg>(&mut self, interval: Duration, msg: Msg) -> Cmd<Msg>
    where
        Msg: Clone,
    {
        self.run(interval, || Cmd::Msg(msg))
    }

    /// Check if an action would be throttled (without running)
    ///
    /// Returns `true` if calling `run()` now would be throttled.
    pub fn is_throttled(&self, interval: Duration) -> bool {
        match self.last_run {
            None => false,
            Some(last) => Instant::now().duration_since(last) < interval,
        }
    }

    /// Time remaining until throttle expires
    ///
    /// Returns `Some(duration)` if throttled, `None` if ready to run.
    pub fn time_remaining(&self, interval: Duration) -> Option<Duration> {
        self.last_run.and_then(|last| {
            let elapsed = Instant::now().duration_since(last);
            if elapsed < interval {
                Some(interval - elapsed)
            } else {
                None
            }
        })
    }

    /// Reset the throttler state
    ///
    /// The next `run()` call will execute immediately.
    pub fn reset(&mut self) {
        self.last_run = None;
    }

    /// Force the next run to be throttled for the given duration
    ///
    /// Useful when you want to prevent immediate execution after
    /// some external event.
    pub fn suppress(&mut self) {
        self.last_run = Some(Instant::now());
    }
}

// ============================================
// ThrottlerWithClock - testable version
// ============================================

/// A throttler with pluggable clock for testing
///
/// Like [`Throttler`], but uses a [`Clock`] trait for time access,
/// enabling deterministic testing with [`FakeClock`](crate::testing::FakeClock).
///
/// # Example
/// ```ignore
/// use egui_cha::testing::FakeClock;
/// use egui_cha::helpers::ThrottlerWithClock;
/// use std::time::Duration;
///
/// let clock = FakeClock::new();
/// let mut throttler = ThrottlerWithClock::new(clock.clone());
///
/// // First call executes
/// let cmd1 = throttler.run(Duration::from_millis(100), || Cmd::Msg(1));
/// assert!(cmd1.is_msg());
///
/// // Immediate second call is throttled
/// let cmd2 = throttler.run(Duration::from_millis(100), || Cmd::Msg(2));
/// assert!(cmd2.is_none());
///
/// // Advance time past throttle interval
/// clock.advance(Duration::from_millis(150));
/// let cmd3 = throttler.run(Duration::from_millis(100), || Cmd::Msg(3));
/// assert!(cmd3.is_msg());
/// ```
#[derive(Debug, Clone)]
pub struct ThrottlerWithClock<C: Clock> {
    clock: C,
    last_run: Option<Duration>,
}

impl<C: Clock> ThrottlerWithClock<C> {
    /// Create a new throttler with the given clock
    pub fn new(clock: C) -> Self {
        Self {
            clock,
            last_run: None,
        }
    }

    /// Run an action if not throttled
    pub fn run<Msg, F>(&mut self, interval: Duration, action: F) -> Cmd<Msg>
    where
        F: FnOnce() -> Cmd<Msg>,
    {
        let now = self.clock.now();

        let should_run = match self.last_run {
            None => true,
            Some(last) => now >= last + interval,
        };

        if should_run {
            self.last_run = Some(now);
            action()
        } else {
            Cmd::none()
        }
    }

    /// Run with a message (convenience method)
    pub fn run_msg<Msg>(&mut self, interval: Duration, msg: Msg) -> Cmd<Msg>
    where
        Msg: Clone,
    {
        self.run(interval, || Cmd::Msg(msg))
    }

    /// Check if an action would be throttled
    pub fn is_throttled(&self, interval: Duration) -> bool {
        match self.last_run {
            None => false,
            Some(last) => self.clock.now() < last + interval,
        }
    }

    /// Time remaining until throttle expires
    pub fn time_remaining(&self, interval: Duration) -> Option<Duration> {
        self.last_run.and_then(|last| {
            let now = self.clock.now();
            let expires_at = last + interval;
            if now < expires_at {
                Some(expires_at - now)
            } else {
                None
            }
        })
    }

    /// Reset the throttler state
    pub fn reset(&mut self) {
        self.last_run = None;
    }

    /// Force the next run to be throttled
    pub fn suppress(&mut self) {
        self.last_run = Some(self.clock.now());
    }
}

/// Throttler with trailing edge execution
///
/// Like `Throttler`, but also fires once after the throttle period
/// if there were any suppressed calls.
///
/// # Example
/// ```ignore
/// struct Model {
///     throttle: TrailingThrottler,
/// }
///
/// fn update(model: &mut Model, msg: Msg) -> Cmd<Msg> {
///     match msg {
///         Msg::Resize(size) => {
///             model.throttle.run(
///                 Duration::from_millis(100),
///                 Msg::DoResize(size),
///                 Msg::TrailingResize,
///             )
///         }
///         Msg::TrailingResize => {
///             if model.throttle.should_fire_trailing() {
///                 // Handle trailing edge
///             }
///             Cmd::none()
///         }
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct TrailingThrottler {
    last_run: Option<Instant>,
    has_pending: bool,
    trailing_scheduled: bool,
}

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

impl TrailingThrottler {
    /// Create a new trailing throttler
    pub fn new() -> Self {
        Self {
            last_run: None,
            has_pending: false,
            trailing_scheduled: false,
        }
    }

    /// Run with both immediate and trailing edge handling
    ///
    /// - If not throttled: executes immediately with `msg`
    /// - If throttled: schedules trailing edge with `trailing_msg`
    ///
    /// When `trailing_msg` arrives, call `should_fire_trailing()` to check.
    ///
    /// Requires the `tokio` feature.
    #[cfg(feature = "tokio")]
    pub fn run<Msg>(&mut self, interval: Duration, msg: Msg, trailing_msg: Msg) -> Cmd<Msg>
    where
        Msg: Clone + Send + 'static,
    {
        let now = Instant::now();

        let should_run = match self.last_run {
            None => true,
            Some(last) => now.duration_since(last) >= interval,
        };

        if should_run {
            self.last_run = Some(now);
            self.has_pending = false;
            self.trailing_scheduled = false;
            Cmd::Msg(msg)
        } else {
            self.has_pending = true;

            // Schedule trailing if not already scheduled
            if !self.trailing_scheduled {
                self.trailing_scheduled = true;
                let remaining = self
                    .last_run
                    .map(|last| interval.saturating_sub(now.duration_since(last)))
                    .unwrap_or(interval);
                Cmd::delay(remaining, trailing_msg)
            } else {
                Cmd::none()
            }
        }
    }

    /// Mark a run without returning a Cmd (non-tokio version)
    ///
    /// Use this when you want to manage the delay yourself.
    /// Returns `Some(remaining_duration)` if trailing should be scheduled,
    /// `None` if executed immediately or trailing already scheduled.
    pub fn mark_run(&mut self, interval: Duration) -> Option<Duration> {
        let now = Instant::now();

        let should_run = match self.last_run {
            None => true,
            Some(last) => now.duration_since(last) >= interval,
        };

        if should_run {
            self.last_run = Some(now);
            self.has_pending = false;
            self.trailing_scheduled = false;
            None
        } else {
            self.has_pending = true;

            if !self.trailing_scheduled {
                self.trailing_scheduled = true;
                let remaining = self
                    .last_run
                    .map(|last| interval.saturating_sub(now.duration_since(last)))
                    .unwrap_or(interval);
                Some(remaining)
            } else {
                None
            }
        }
    }

    /// Check if trailing edge should fire
    ///
    /// Call this when the trailing message arrives.
    /// Returns `true` if there were suppressed calls during throttle.
    pub fn should_fire_trailing(&mut self) -> bool {
        if self.has_pending {
            self.has_pending = false;
            self.trailing_scheduled = false;
            self.last_run = Some(Instant::now());
            true
        } else {
            self.trailing_scheduled = false;
            false
        }
    }

    /// Reset the throttler state
    pub fn reset(&mut self) {
        self.last_run = None;
        self.has_pending = false;
        self.trailing_scheduled = false;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;

    #[test]
    fn test_throttler_first_call() {
        let mut throttler = Throttler::new();

        // First call should not be throttled
        assert!(!throttler.is_throttled(Duration::from_millis(100)));

        let cmd = throttler.run(Duration::from_millis(100), || Cmd::Msg(42));
        assert!(cmd.is_msg());
    }

    #[test]
    fn test_throttler_blocks_rapid_calls() {
        use crate::testing::FakeClock;

        let clock = FakeClock::new();
        let mut throttler = ThrottlerWithClock::new(clock.clone());
        let interval = Duration::from_millis(50);

        // First call executes
        let cmd1 = throttler.run(interval, || Cmd::Msg(1));
        assert!(cmd1.is_msg());

        // Immediate second call is throttled
        let cmd2 = throttler.run(interval, || Cmd::Msg(2));
        assert!(cmd2.is_none());

        // Still throttled
        clock.advance(Duration::from_millis(20));
        let cmd3 = throttler.run(interval, || Cmd::Msg(3));
        assert!(cmd3.is_none());

        // After interval, executes again
        clock.advance(Duration::from_millis(35));
        let cmd4 = throttler.run(interval, || Cmd::Msg(4));
        assert!(cmd4.is_msg());
    }

    #[test]
    fn test_throttler_reset() {
        let mut throttler = Throttler::new();
        let interval = Duration::from_millis(100);

        // First call
        let _ = throttler.run(interval, || Cmd::Msg(1));

        // Reset
        throttler.reset();

        // Next call should execute immediately
        let cmd = throttler.run(interval, || Cmd::Msg(2));
        assert!(cmd.is_msg());
    }

    #[test]
    fn test_throttler_time_remaining() {
        let mut throttler = Throttler::new();
        let interval = Duration::from_millis(100);

        // Before first run
        assert!(throttler.time_remaining(interval).is_none());

        // After first run
        let _ = throttler.run(interval, || Cmd::Msg(1));
        let remaining = throttler.time_remaining(interval);
        assert!(remaining.is_some());
        assert!(remaining.unwrap() <= interval);
    }

    #[test]
    #[cfg(feature = "tokio")]
    fn test_trailing_throttler_basic() {
        let mut throttler = TrailingThrottler::new();
        let interval = Duration::from_millis(50);

        // First call executes immediately
        let cmd1 = throttler.run(interval, 1, 100);
        assert!(cmd1.is_msg_eq(&1));

        // Second call schedules trailing
        let cmd2 = throttler.run(interval, 2, 100);
        assert!(!cmd2.is_none()); // Trailing scheduled

        // Third call doesn't schedule another trailing
        let cmd3 = throttler.run(interval, 3, 100);
        assert!(cmd3.is_none());

        // Wait and check trailing
        thread::sleep(Duration::from_millis(55));
        assert!(throttler.should_fire_trailing());
    }
}