rdom-tui 0.4.0

Terminal rendering layer for rdom-core — flexbox layout, TUI styles, key/mouse events. Use rdom-core directly for headless DOM manipulation.
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
//! Timer scheduler — `setTimeout` / `setInterval` /
//! `requestAnimationFrame` / `queueMicrotask`, all matching the
//! HTML spec shapes (M3 Part A).
//!
//! ## Architecture
//!
//! Scheduler is concrete and lives on `App`. Callbacks are
//! `Box<dyn FnOnce(&mut TimerCtx<'_>)>` (or `FnMut` for intervals)
//! with a higher-ranked lifetime so they accept any
//! `TimerCtx<'a>`. `TimerCtx` exposes the same scheduling methods
//! the event-handler context does — chaining `set_timeout`
//! inside a callback Just Works, matching JS.
//!
//! ## Determinism
//!
//! The scheduler holds an `Instant`-based wall clock for
//! production but `advance_to(now)` is the only way time
//! advances. Tests pass synthetic instants for byte-perfect
//! determinism.
//!
//! `dead_code` allow on the few "wired in next slice"
//! accessors (`now`, `has_active_raf`) that the App tick loop
//! will pick up when §15-integration lands.

#![allow(dead_code)]

use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
use std::time::{Duration, Instant};

use crate::TuiDom;

/// The scheduler as shared by the `App`, the timer callbacks, and the
/// `TuiTimers` extension on event contexts. One `Rc` per `App`;
/// borrows are taken per call and never held across a user callback,
/// so a callback that schedules more work (or dispatches an event
/// whose listener does) borrows a free cell.
pub(crate) type SharedScheduler = Rc<RefCell<Scheduler>>;

thread_local! {
    /// The scheduler user code reaches through `TuiTimers`. Installed
    /// by [`SchedulerGuard`] around every path that runs user
    /// callbacks — event dispatch, ticks, timer pumps, injected
    /// closures, animation events, the drag-autoscroll synthetic move.
    /// An `Rc` clone, not a pointer: no aliasing with the `App`'s own
    /// handle, and nothing dangles if a guard is forgotten.
    static CURRENT_SCHEDULER: RefCell<Option<SharedScheduler>> = const { RefCell::new(None) };
}

/// RAII guard that makes `scheduler` the one `TuiTimers` routes to
/// for the guard's lifetime. On drop the previous value is restored,
/// so nested installs (an `App` entry point calling another) are
/// safe and re-entrant.
pub(crate) struct SchedulerGuard {
    previous: Option<SharedScheduler>,
}

impl SchedulerGuard {
    pub(crate) fn install(scheduler: &SharedScheduler) -> Self {
        let previous = CURRENT_SCHEDULER.with(|s| s.replace(Some(scheduler.clone())));
        SchedulerGuard { previous }
    }
}

impl Drop for SchedulerGuard {
    fn drop(&mut self) {
        let previous = self.previous.take();
        CURRENT_SCHEDULER.with(|s| *s.borrow_mut() = previous);
    }
}

/// Run `f` against the currently-installed scheduler. `None` when no
/// `App` context is active on this thread. The `Rc` is cloned out of
/// the thread-local first so `f` may itself re-enter `with_current`.
fn with_current<F, R>(f: F) -> Option<R>
where
    F: FnOnce(&mut Scheduler) -> R,
{
    let current = CURRENT_SCHEDULER.with(|s| s.borrow().clone())?;
    Some(f(&mut current.borrow_mut()))
}

/// The running `App`'s scheduler clock, when user code is executing
/// under one. Builtins and the router use it for time-window
/// heuristics (multi-click, type-ahead) so `App::advance` drives them
/// deterministically; callers fall back to wall time outside an `App`.
pub(crate) fn current_now() -> Option<Instant> {
    with_current(|s| s.now())
}

/// Numeric handle returned by `set_timeout` / `set_interval` /
/// `request_animation_frame`. Pass to `clear_*` to cancel.
///
/// Allocated monotonically starting at 1 — matches the JS
/// expectation that `0` is falsy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TimerId(pub(crate) u32);

impl TimerId {
    /// Sentinel id used as the "no timer" marker. Never
    /// allocated by the scheduler.
    pub const NONE: TimerId = TimerId(0);

    pub fn raw(self) -> u32 {
        self.0
    }
}

/// Callback context passed to every timer callback. Mirrors
/// `window.*` in JS: scheduling methods on the context route
/// into the same scheduler that's currently pumping.
pub struct TimerCtx<'a> {
    pub dom: &'a mut TuiDom,
    scheduler: SharedScheduler,
}

impl<'a> TimerCtx<'a> {
    pub(crate) fn new(dom: &'a mut TuiDom, scheduler: SharedScheduler) -> Self {
        Self { dom, scheduler }
    }

    pub fn set_timeout(
        &mut self,
        callback: impl FnOnce(&mut TimerCtx<'_>) + 'static,
        delay_ms: u32,
    ) -> TimerId {
        self.scheduler.borrow_mut().set_timeout(callback, delay_ms)
    }

    pub fn clear_timeout(&mut self, id: TimerId) {
        self.scheduler.borrow_mut().clear_timeout(id);
    }

    pub fn set_interval(
        &mut self,
        callback: impl FnMut(&mut TimerCtx<'_>) -> bool + 'static,
        period_ms: u32,
    ) -> TimerId {
        self.scheduler
            .borrow_mut()
            .set_interval(callback, period_ms)
    }

    pub fn clear_interval(&mut self, id: TimerId) {
        self.scheduler.borrow_mut().clear_interval(id);
    }

    pub fn request_animation_frame(
        &mut self,
        callback: impl FnOnce(&mut TimerCtx<'_>, f64) + 'static,
    ) -> TimerId {
        self.scheduler
            .borrow_mut()
            .request_animation_frame(callback)
    }

    pub fn cancel_animation_frame(&mut self, id: TimerId) {
        self.scheduler.borrow_mut().cancel_animation_frame(id);
    }

    pub fn queue_microtask(&mut self, callback: impl FnOnce(&mut TimerCtx<'_>) + 'static) {
        self.scheduler.borrow_mut().queue_microtask(callback);
    }
}

type OneShotCb = Box<dyn FnOnce(&mut TimerCtx<'_>) + 'static>;
type IntervalCb = Box<dyn FnMut(&mut TimerCtx<'_>) -> bool + 'static>;
/// rAF callbacks receive a `DOMHighResTimeStamp`-equivalent
/// (`f64` ms since `App::new`) as their second argument — matches
/// the browser `requestAnimationFrame` contract. All rAFs drained
/// in the same tick observe the same timestamp.
type RafCb = Box<dyn FnOnce(&mut TimerCtx<'_>, f64) + 'static>;

struct TimeoutEntry {
    id: TimerId,
    fires_at: Instant,
    callback: OneShotCb,
}

struct IntervalEntry {
    id: TimerId,
    period: Duration,
    next_fire: Instant,
    callback: IntervalCb,
}

struct RafEntry {
    id: TimerId,
    callback: RafCb,
}

struct MicrotaskEntry {
    callback: OneShotCb,
}

/// The scheduler. Owned by `App`; one per app instance.
pub(crate) struct Scheduler {
    next_id: u32,
    /// The interval whose callback is currently running (its entry is
    /// claimed out of `intervals` for the call). `clear_interval` on it
    /// cannot find the entry, so it flags `running_cleared` instead and
    /// the pump drops the entry on release — `clearInterval(id)` from
    /// inside the callback works as in JS.
    running_interval: Option<TimerId>,
    running_cleared: bool,
    /// Virtual clock; `advance_to(now)` is the only way time
    /// moves forward. Production sets this from `Instant::now()`
    /// at the top of each tick; tests pass synthetic instants.
    now: Instant,
    /// Wall-clock origin captured at `App::new` and never mutated.
    /// rAF callbacks receive `now - app_start` (in ms) as the
    /// `DOMHighResTimeStamp` equivalent. Browser-faithful: zero at
    /// app startup, monotonically non-decreasing thereafter.
    app_start: Instant,
    timeouts: Vec<TimeoutEntry>,
    intervals: Vec<IntervalEntry>,
    raf: Vec<RafEntry>,
    microtasks: VecDeque<MicrotaskEntry>,
}

impl Scheduler {
    pub(crate) fn new(start: Instant) -> Self {
        Self {
            running_interval: None,
            running_cleared: false,
            next_id: 1, // 0 is the NONE sentinel — matches JS falsy
            now: start,
            app_start: start,
            timeouts: Vec::new(),
            intervals: Vec::new(),
            raf: Vec::new(),
            microtasks: VecDeque::new(),
        }
    }

    /// Frame timestamp in milliseconds since `App::new`. Matches
    /// the browser `DOMHighResTimeStamp` value passed to rAF
    /// callbacks. Stable for the duration of a tick — all rAF
    /// callbacks drained in one `pump_raf` see this same value.
    pub(crate) fn frame_timestamp_ms(&self) -> f64 {
        self.now
            .saturating_duration_since(self.app_start)
            .as_secs_f64()
            * 1000.0
    }

    fn alloc_id(&mut self) -> TimerId {
        let id = TimerId(self.next_id);
        // Wraparound is effectively never (u32::MAX outstanding
        // timers); on overflow we skip 0 to keep the falsy
        // sentinel reserved.
        self.next_id = self.next_id.checked_add(1).unwrap_or(1);
        id
    }

    pub(crate) fn now(&self) -> Instant {
        self.now
    }

    /// Move the virtual clock forward to `now`. Must be
    /// monotonically non-decreasing — production guarantees this
    /// because it always passes `Instant::now()`.
    pub(crate) fn set_now(&mut self, now: Instant) {
        if now > self.now {
            self.now = now;
        }
    }

    pub fn set_timeout(
        &mut self,
        callback: impl FnOnce(&mut TimerCtx<'_>) + 'static,
        delay_ms: u32,
    ) -> TimerId {
        let id = self.alloc_id();
        let fires_at = self.now + Duration::from_millis(delay_ms as u64);
        self.timeouts.push(TimeoutEntry {
            id,
            fires_at,
            callback: Box::new(callback),
        });
        id
    }

    pub fn clear_timeout(&mut self, id: TimerId) {
        self.timeouts.retain(|e| e.id != id);
    }

    pub fn set_interval(
        &mut self,
        callback: impl FnMut(&mut TimerCtx<'_>) -> bool + 'static,
        period_ms: u32,
    ) -> TimerId {
        let id = self.alloc_id();
        let period = Duration::from_millis(period_ms as u64);
        self.intervals.push(IntervalEntry {
            id,
            period,
            next_fire: self.now + period,
            callback: Box::new(callback),
        });
        id
    }

    pub fn clear_interval(&mut self, id: TimerId) {
        if self.running_interval == Some(id) {
            self.running_cleared = true;
        }
        self.intervals.retain(|e| e.id != id);
    }

    /// Schedule `callback` to run before the next paint. The
    /// callback receives a `DOMHighResTimeStamp`-equivalent (`f64`
    /// ms since `App::new`) as its second argument. All rAFs that
    /// drain in the same tick observe the same timestamp —
    /// browser-faithful per the HTML spec.
    pub fn request_animation_frame(
        &mut self,
        callback: impl FnOnce(&mut TimerCtx<'_>, f64) + 'static,
    ) -> TimerId {
        let id = self.alloc_id();
        self.raf.push(RafEntry {
            id,
            callback: Box::new(callback),
        });
        id
    }

    pub fn cancel_animation_frame(&mut self, id: TimerId) {
        self.raf.retain(|e| e.id != id);
    }

    pub fn queue_microtask(&mut self, callback: impl FnOnce(&mut TimerCtx<'_>) + 'static) {
        self.microtasks.push_back(MicrotaskEntry {
            callback: Box::new(callback),
        });
    }

    /// Earliest deadline across timeouts + intervals. `None` if
    /// the scheduler has nothing pending. Used by the App tick
    /// loop to size its `crossterm::poll` timeout.
    pub(crate) fn next_deadline(&self) -> Option<Instant> {
        let timeout = self.timeouts.iter().map(|e| e.fires_at).min();
        let interval = self.intervals.iter().map(|e| e.next_fire).min();
        match (timeout, interval) {
            (Some(a), Some(b)) => Some(a.min(b)),
            (a, b) => a.or(b),
        }
    }

    /// True when the scheduler has any work that benefits from
    /// the tightened animation frame rate. Animations register
    /// elsewhere (animation registry); this only tracks rAF +
    /// pending timers shorter than a frame.
    pub(crate) fn has_active_raf(&self) -> bool {
        !self.raf.is_empty()
    }

    /// Pop and return every timeout entry whose `fires_at <=
    /// self.now`. Caller invokes each callback with a real
    /// `TimerCtx`. Returned in fire order (earliest first).
    pub(crate) fn drain_expired_timeouts(&mut self) -> Vec<OneShotCb> {
        let mut expired_idx: Vec<usize> = self
            .timeouts
            .iter()
            .enumerate()
            .filter_map(|(i, e)| {
                if e.fires_at <= self.now {
                    Some(i)
                } else {
                    None
                }
            })
            .collect();
        // Sort by fires_at via a stable mapping. Indices are
        // already in vector order; we want the actual entries in
        // fires_at order.
        expired_idx.sort_by_key(|&i| self.timeouts[i].fires_at);
        // Remove highest-index-first so earlier indices stay valid.
        let mut out = Vec::with_capacity(expired_idx.len());
        for &i in expired_idx.iter().rev() {
            out.push(self.timeouts.remove(i).callback);
        }
        out.reverse(); // restore fire-order
        out
    }

    /// Pop every interval entry whose `next_fire <= self.now`,
    /// returning `(id, callback)` pairs. The caller invokes each;
    /// the scheduler reschedules at `next_fire + period` if the
    /// callback returns `true`. Returned in fire order.
    ///
    /// Note: callbacks for intervals are `FnMut` so we can't
    /// simply move them out and back. Instead we use a
    /// "claim/release" pattern — see `pump_intervals`.
    pub(crate) fn drain_expired_interval_ids(&self) -> Vec<TimerId> {
        let mut due: Vec<(TimerId, Instant)> = self
            .intervals
            .iter()
            .filter(|e| e.next_fire <= self.now)
            .map(|e| (e.id, e.next_fire))
            .collect();
        due.sort_by_key(|(_, t)| *t);
        due.into_iter().map(|(id, _)| id).collect()
    }

    /// Drain all queued rAF callbacks for one frame.
    pub(crate) fn drain_raf(&mut self) -> Vec<RafCb> {
        std::mem::take(&mut self.raf)
            .into_iter()
            .map(|e| e.callback)
            .collect()
    }

    /// Drain one microtask. Caller loops until empty.
    pub(crate) fn pop_microtask(&mut self) -> Option<OneShotCb> {
        self.microtasks.pop_front().map(|e| e.callback)
    }
}

/// Pump every expired interval, calling the callback with the
/// supplied ctx-builder closure. Schedules the next fire if the
/// callback returns `true`; removes the entry if it returns
/// `false` (self-cancel).
///
/// Lives outside `Scheduler` because it borrows interval entries
/// for a `FnMut` call which the borrow checker would otherwise
/// reject if we held a mutable borrow on the whole scheduler.
pub(crate) fn pump_intervals(scheduler: &SharedScheduler, dom: &mut TuiDom, expired: &[TimerId]) {
    let _current = SchedulerGuard::install(scheduler);
    for &id in expired {
        // Claim the entry (tolerating a previous callback in this same
        // drain having cleared it), call it with the cell free, then
        // release it back if it wants to keep firing.
        let claimed = {
            let mut s = scheduler.borrow_mut();
            let pos = s.intervals.iter().position(|e| e.id == id);
            pos.map(|p| s.intervals.swap_remove(p))
        };
        let Some(mut entry) = claimed else { continue };
        {
            let mut s = scheduler.borrow_mut();
            s.running_interval = Some(id);
            s.running_cleared = false;
        }
        let keep = {
            let mut ctx = TimerCtx::new(dom, scheduler.clone());
            (entry.callback)(&mut ctx)
        };
        let cleared = {
            let mut s = scheduler.borrow_mut();
            s.running_interval = None;
            std::mem::take(&mut s.running_cleared)
        };
        if keep && !cleared {
            entry.next_fire += entry.period;
            scheduler.borrow_mut().intervals.push(entry);
        }
    }
}

/// Drain expired timeouts and invoke each callback with a real
/// `TimerCtx`. Convenience for App's tick loop.
pub(crate) fn pump_timeouts(scheduler: &SharedScheduler, dom: &mut TuiDom) {
    let _current = SchedulerGuard::install(scheduler);
    let cbs = scheduler.borrow_mut().drain_expired_timeouts();
    for cb in cbs {
        let mut ctx = TimerCtx::new(dom, scheduler.clone());
        cb(&mut ctx);
    }
}

/// Drain queued rAF callbacks for the current frame. All callbacks
/// in this drain receive the same `frame_timestamp_ms()` value —
/// matches the browser contract that one frame = one timestamp.
pub(crate) fn pump_raf(scheduler: &SharedScheduler, dom: &mut TuiDom) {
    let _current = SchedulerGuard::install(scheduler);
    let (timestamp, cbs) = {
        let mut s = scheduler.borrow_mut();
        (s.frame_timestamp_ms(), s.drain_raf())
    };
    for cb in cbs {
        let mut ctx = TimerCtx::new(dom, scheduler.clone());
        cb(&mut ctx, timestamp);
    }
}

/// Extension trait on `TuiEventCtx<'_>` exposing the HTML timer
/// API to event listeners. Mirrors `window.setTimeout`,
/// `window.setInterval`, `window.requestAnimationFrame`, etc.
///
/// Routes to the scheduler of the `App` currently running user code on
/// this thread — installed around event dispatch, ticks, timer pumps,
/// injected closures, animation events, and autoscroll — so it works
/// from a listener regardless of how that listener was reached. It
/// panics only when no `App` is active at all (a listener fired from a
/// bare `Dom::dispatch_event` in a test with no `App`); pass a
/// scheduler through your own context in that case.
pub trait TuiTimers {
    fn set_timeout(
        &mut self,
        callback: impl FnOnce(&mut TimerCtx<'_>) + 'static,
        delay_ms: u32,
    ) -> TimerId;

    fn clear_timeout(&mut self, id: TimerId);

    fn set_interval(
        &mut self,
        callback: impl FnMut(&mut TimerCtx<'_>) -> bool + 'static,
        period_ms: u32,
    ) -> TimerId;

    fn clear_interval(&mut self, id: TimerId);

    fn request_animation_frame(
        &mut self,
        callback: impl FnOnce(&mut TimerCtx<'_>, f64) + 'static,
    ) -> TimerId;

    fn cancel_animation_frame(&mut self, id: TimerId);

    fn queue_microtask(&mut self, callback: impl FnOnce(&mut TimerCtx<'_>) + 'static);
}

impl<'a> TuiTimers for crate::TuiEventCtx<'a> {
    fn set_timeout(
        &mut self,
        callback: impl FnOnce(&mut TimerCtx<'_>) + 'static,
        delay_ms: u32,
    ) -> TimerId {
        with_current(|s| s.set_timeout(callback, delay_ms))
            .expect("set_timeout: no App is running on this thread")
    }

    fn clear_timeout(&mut self, id: TimerId) {
        with_current(|s| s.clear_timeout(id));
    }

    fn set_interval(
        &mut self,
        callback: impl FnMut(&mut TimerCtx<'_>) -> bool + 'static,
        period_ms: u32,
    ) -> TimerId {
        with_current(|s| s.set_interval(callback, period_ms))
            .expect("set_interval: no App is running on this thread")
    }

    fn clear_interval(&mut self, id: TimerId) {
        with_current(|s| s.clear_interval(id));
    }

    fn request_animation_frame(
        &mut self,
        callback: impl FnOnce(&mut TimerCtx<'_>, f64) + 'static,
    ) -> TimerId {
        with_current(|s| s.request_animation_frame(callback))
            .expect("request_animation_frame: no App is running on this thread")
    }

    fn cancel_animation_frame(&mut self, id: TimerId) {
        with_current(|s| s.cancel_animation_frame(id));
    }

    fn queue_microtask(&mut self, callback: impl FnOnce(&mut TimerCtx<'_>) + 'static) {
        with_current(|s| s.queue_microtask(callback));
    }
}

/// Drain microtask queue to empty. Microtasks queued *during*
/// this drain are appended and drained in the same loop —
/// matches HTML spec.
pub(crate) fn drain_microtasks(scheduler: &SharedScheduler, dom: &mut TuiDom) {
    let _current = SchedulerGuard::install(scheduler);
    loop {
        let next = scheduler.borrow_mut().pop_microtask();
        let Some(cb) = next else { break };
        let mut ctx = TimerCtx::new(dom, scheduler.clone());
        cb(&mut ctx);
    }
}

#[cfg(test)]
mod tests {
    fn shared(start: Instant) -> SharedScheduler {
        Rc::new(RefCell::new(Scheduler::new(start)))
    }
    use super::*;
    use std::cell::Cell;
    use std::rc::Rc;

    fn epoch() -> Instant {
        Instant::now()
    }

    fn dom_for_tests() -> TuiDom {
        TuiDom::new()
    }

    // ── §15.1 — set_timeout fires after delay ─────────────────

    #[test]
    fn timeout_fires_after_delay() {
        let start = epoch();
        let sched = shared(start);
        let mut dom = dom_for_tests();
        let fired = Rc::new(Cell::new(0u32));
        let f = fired.clone();
        sched
            .borrow_mut()
            .set_timeout(move |_ctx| f.set(f.get() + 1), 100);

        // Before deadline: not fired.
        sched
            .borrow_mut()
            .set_now(start + Duration::from_millis(50));
        pump_timeouts(&sched, &mut dom);
        assert_eq!(fired.get(), 0);

        // After deadline: fired exactly once.
        sched
            .borrow_mut()
            .set_now(start + Duration::from_millis(150));
        pump_timeouts(&sched, &mut dom);
        assert_eq!(fired.get(), 1);

        // Doesn't fire again.
        sched
            .borrow_mut()
            .set_now(start + Duration::from_millis(300));
        pump_timeouts(&sched, &mut dom);
        assert_eq!(fired.get(), 1);
    }

    // ── §15.2 — clear_timeout cancels ─────────────────────────

    #[test]
    fn clear_timeout_cancels_before_deadline() {
        let start = epoch();
        let sched = shared(start);
        let mut dom = dom_for_tests();
        let fired = Rc::new(Cell::new(0u32));
        let f = fired.clone();
        let id = sched
            .borrow_mut()
            .set_timeout(move |_| f.set(f.get() + 1), 100);

        sched.borrow_mut().clear_timeout(id);
        sched
            .borrow_mut()
            .set_now(start + Duration::from_millis(200));
        pump_timeouts(&sched, &mut dom);
        assert_eq!(fired.get(), 0);
    }

    // ── §15.3 — set_interval repeats ──────────────────────────

    #[test]
    fn interval_repeats_at_period() {
        let start = epoch();
        let sched = shared(start);
        let mut dom = dom_for_tests();
        let count = Rc::new(Cell::new(0u32));
        let c = count.clone();
        sched.borrow_mut().set_interval(
            move |_| {
                c.set(c.get() + 1);
                true
            },
            50,
        );

        // Advance 175ms — 3 fires expected (at 50, 100, 150).
        sched
            .borrow_mut()
            .set_now(start + Duration::from_millis(175));
        let due = sched.borrow_mut().drain_expired_interval_ids();
        pump_intervals(&sched, &mut dom, &due);
        // First pump catches one entry per drain — but the
        // collected `due` list only has the entry once, so we
        // need a loop in the App. Test the pump-loop semantic:
        while !sched.borrow_mut().drain_expired_interval_ids().is_empty() {
            let due = sched.borrow_mut().drain_expired_interval_ids();
            pump_intervals(&sched, &mut dom, &due);
        }
        assert_eq!(count.get(), 3);
    }

    // ── §15.4 — Interval returning false self-cancels ─────────

    #[test]
    fn interval_self_cancels_on_false_return() {
        let start = epoch();
        let sched = shared(start);
        let mut dom = dom_for_tests();
        let count = Rc::new(Cell::new(0u32));
        let c = count.clone();
        sched.borrow_mut().set_interval(
            move |_| {
                c.set(c.get() + 1);
                c.get() < 2
            },
            50,
        );

        // Advance 500ms — should fire at 50ms (count=1, keep=true)
        // and at 100ms (count=2, keep=false). After that the
        // entry is removed.
        sched
            .borrow_mut()
            .set_now(start + Duration::from_millis(500));
        loop {
            let due = sched.borrow_mut().drain_expired_interval_ids();
            if due.is_empty() {
                break;
            }
            pump_intervals(&sched, &mut dom, &due);
        }
        assert_eq!(count.get(), 2);
        // No more pending intervals.
        assert!(sched.borrow().intervals.is_empty());
    }

    // ── §15.5 — clear_timeout on stale handle is no-op ────────

    #[test]
    fn clear_timeout_on_stale_handle_is_noop() {
        let start = epoch();
        let sched = shared(start);
        let mut dom = dom_for_tests();

        let fired = Rc::new(Cell::new(false));
        let f = fired.clone();
        let id = sched.borrow_mut().set_timeout(move |_| f.set(true), 50);

        // Fire it.
        sched
            .borrow_mut()
            .set_now(start + Duration::from_millis(100));
        pump_timeouts(&sched, &mut dom);
        assert!(fired.get());

        // Clearing the now-stale id is a silent no-op.
        sched.borrow_mut().clear_timeout(id);
        // Also: a never-issued id is a no-op.
        sched.borrow_mut().clear_timeout(TimerId(99999));
    }

    // ── §15.6 — request_animation_frame fires once per drain ──

    #[test]
    fn raf_fires_once_per_drain() {
        let start = epoch();
        let sched = shared(start);
        let mut dom = dom_for_tests();
        let fired = Rc::new(Cell::new(0u32));
        let f = fired.clone();
        sched
            .borrow_mut()
            .request_animation_frame(move |_, _ts| f.set(f.get() + 1));

        pump_raf(&sched, &mut dom);
        assert_eq!(fired.get(), 1);

        // Second drain finds nothing — rAF is one-shot.
        pump_raf(&sched, &mut dom);
        assert_eq!(fired.get(), 1);
    }

    // ── §15.7 — queue_microtask drains FIFO ────────────────────

    #[test]
    fn microtasks_drain_in_fifo_order_including_late_queues() {
        let start = epoch();
        let sched = shared(start);
        let mut dom = dom_for_tests();
        let order = Rc::new(std::cell::RefCell::new(Vec::<u32>::new()));

        let o = order.clone();
        sched.borrow_mut().queue_microtask(move |ctx| {
            o.borrow_mut().push(1);
            // Microtask queued during drain is appended and
            // drained in the same loop (HTML spec).
            let o2 = o.clone();
            ctx.queue_microtask(move |_| o2.borrow_mut().push(3));
        });
        let o = order.clone();
        sched
            .borrow_mut()
            .queue_microtask(move |_| o.borrow_mut().push(2));

        drain_microtasks(&sched, &mut dom);
        assert_eq!(*order.borrow(), vec![1, 2, 3]);
    }

    // ── §15.8 — Handles unique and monotonically allocated ────

    #[test]
    fn handles_are_unique_and_monotonic() {
        let start = epoch();
        let sched = shared(start);
        let a = sched.borrow_mut().set_timeout(|_| {}, 100);
        let b = sched.borrow_mut().set_timeout(|_| {}, 100);
        let c = sched.borrow_mut().request_animation_frame(|_, _ts| {});
        let d = sched.borrow_mut().set_interval(|_| true, 50);
        assert_ne!(a, b);
        assert_ne!(b, c);
        assert_ne!(c, d);
        // First handle is 1 (0 is the NONE sentinel).
        assert_eq!(a.raw(), 1);
        // Monotonic.
        assert!(b.raw() > a.raw());
        assert!(c.raw() > b.raw());
        assert!(d.raw() > c.raw());
    }

    // ── Listener-side surface via TuiTimers + thread-local ───

    #[test]
    fn listener_can_call_set_timeout_via_extension_trait() {
        use rdom_core::ListenerOptions;

        let mut dom = TuiDom::new();
        let root = dom.root();
        let div = dom.create_element("div");
        dom.append_child(root, div).unwrap();

        let fired = Rc::new(Cell::new(0u32));
        let f = fired.clone();
        // Listener schedules a 100ms timeout.
        dom.add_event_listener(div, "click", ListenerOptions::default(), move |ctx| {
            let f2 = f.clone();
            // Extension-trait method lights up here.
            ctx.set_timeout(move |_| f2.set(f2.get() + 1), 100);
        })
        .unwrap();

        let start = epoch();
        let sched = shared(start);
        // Install scheduler guard (mimics what App::handle_event does).
        let _g = SchedulerGuard::install(&sched);
        // Dispatch the click event manually.
        let mut ev = rdom_core::Event::new("click");
        let _ = dom.dispatch_event(div, &mut ev);
        drop(_g);

        // Before the deadline.
        sched
            .borrow_mut()
            .set_now(start + Duration::from_millis(50));
        pump_timeouts(&sched, &mut dom);
        assert_eq!(fired.get(), 0);

        // After the deadline.
        sched
            .borrow_mut()
            .set_now(start + Duration::from_millis(200));
        pump_timeouts(&sched, &mut dom);
        assert_eq!(fired.get(), 1);
    }

    /// `clearInterval(id)` from inside that interval's own callback
    /// stops it (the JS idiom). The entry is claimed while running, so
    /// the clear must be remembered and honored on release.
    #[test]
    fn interval_can_clear_itself_from_its_own_callback() {
        let start = epoch();
        let sched = shared(start);
        let mut dom: TuiDom = TuiDom::new();
        let fired = Rc::new(Cell::new(0u32));
        let f = fired.clone();
        let id_cell: Rc<Cell<Option<TimerId>>> = Rc::new(Cell::new(None));
        let id_for_cb = id_cell.clone();
        let id = sched.borrow_mut().set_interval(
            move |ctx| {
                f.set(f.get() + 1);
                ctx.clear_interval(id_for_cb.get().unwrap());
                true // "keep" — but the explicit clear must win
            },
            10,
        );
        id_cell.set(Some(id));
        for tick in 1..=3 {
            sched
                .borrow_mut()
                .set_now(start + Duration::from_millis(10 * tick));
            let due = sched.borrow().drain_expired_interval_ids();
            pump_intervals(&sched, &mut dom, &due);
        }
        assert_eq!(fired.get(), 1, "fired once, then stayed cleared");
    }

    #[test]
    fn scheduler_guard_restores_previous_on_drop() {
        let start = epoch();
        let a = shared(start);
        let b = shared(start);
        // Outer guard installs `a`.
        let _outer = SchedulerGuard::install(&a);
        // Inner guard installs `b`.
        {
            let _inner = SchedulerGuard::install(&b);
            // While inner is alive, the current scheduler is `b`.
            let count_b = with_current(|s| s.next_id);
            assert_eq!(count_b, Some(1));
        }
        // After inner drops, `a` is restored.
        let count_a = with_current(|s| s.next_id);
        assert_eq!(count_a, Some(1));
    }

    // ── D-M3-4 — rAF callback receives DOMHighResTimeStamp ────

    #[test]
    fn raf_callback_receives_timestamp_zero_at_app_start() {
        let start = epoch();
        let sched = shared(start);
        let mut dom = dom_for_tests();
        let observed = Rc::new(Cell::new(-1.0_f64));
        let o = observed.clone();
        sched
            .borrow_mut()
            .request_animation_frame(move |_ctx, ts| o.set(ts));
        pump_raf(&sched, &mut dom);
        // No clock advancement → timestamp is exactly 0.0.
        assert_eq!(observed.get(), 0.0);
    }

    #[test]
    fn raf_callback_timestamp_reflects_scheduler_clock() {
        let start = epoch();
        let sched = shared(start);
        let mut dom = dom_for_tests();
        let observed = Rc::new(Cell::new(-1.0_f64));
        let o = observed.clone();
        sched
            .borrow_mut()
            .request_animation_frame(move |_ctx, ts| o.set(ts));
        sched
            .borrow_mut()
            .set_now(start + Duration::from_millis(16));
        pump_raf(&sched, &mut dom);
        // 16ms elapsed since app start → timestamp is 16.0.
        assert_eq!(observed.get(), 16.0);
    }

    #[test]
    fn raf_timestamps_monotonic_across_ticks() {
        let start = epoch();
        let sched = shared(start);
        let mut dom = dom_for_tests();
        let stamps = Rc::new(std::cell::RefCell::new(Vec::<f64>::new()));

        let s = stamps.clone();
        sched
            .borrow_mut()
            .request_animation_frame(move |_ctx, ts| s.borrow_mut().push(ts));
        sched
            .borrow_mut()
            .set_now(start + Duration::from_millis(16));
        pump_raf(&sched, &mut dom);

        let s = stamps.clone();
        sched
            .borrow_mut()
            .request_animation_frame(move |_ctx, ts| s.borrow_mut().push(ts));
        sched
            .borrow_mut()
            .set_now(start + Duration::from_millis(33));
        pump_raf(&sched, &mut dom);

        let s = stamps.clone();
        sched
            .borrow_mut()
            .request_animation_frame(move |_ctx, ts| s.borrow_mut().push(ts));
        sched
            .borrow_mut()
            .set_now(start + Duration::from_millis(50));
        pump_raf(&sched, &mut dom);

        let captured = stamps.borrow().clone();
        assert_eq!(captured.len(), 3);
        assert!(captured[0] <= captured[1]);
        assert!(captured[1] <= captured[2]);
        // Floats but the values are exact multiples of ms here.
        assert_eq!(captured, vec![16.0, 33.0, 50.0]);
    }

    #[test]
    fn raf_timestamps_coherent_within_one_tick() {
        // Browser semantics: all rAF callbacks within the same
        // frame observe the same timestamp. We schedule two rAFs
        // before advancing the clock and pump them in one drain —
        // both must see the same value.
        let start = epoch();
        let sched = shared(start);
        let mut dom = dom_for_tests();
        let stamps = Rc::new(std::cell::RefCell::new(Vec::<f64>::new()));

        let s1 = stamps.clone();
        sched
            .borrow_mut()
            .request_animation_frame(move |_ctx, ts| s1.borrow_mut().push(ts));
        let s2 = stamps.clone();
        sched
            .borrow_mut()
            .request_animation_frame(move |_ctx, ts| s2.borrow_mut().push(ts));

        sched
            .borrow_mut()
            .set_now(start + Duration::from_millis(16));
        pump_raf(&sched, &mut dom);

        let captured = stamps.borrow().clone();
        assert_eq!(captured.len(), 2);
        assert_eq!(captured[0], 16.0);
        assert_eq!(captured[1], 16.0);
    }

    // ── §15.9 — next_deadline returns shortest ────────────────

    #[test]
    fn next_deadline_returns_shortest_pending() {
        let start = epoch();
        let sched = shared(start);
        assert_eq!(sched.borrow_mut().next_deadline(), None);

        sched.borrow_mut().set_timeout(|_| {}, 200);
        sched.borrow_mut().set_timeout(|_| {}, 50); // closer
        sched.borrow_mut().set_timeout(|_| {}, 500);

        assert_eq!(
            sched.borrow_mut().next_deadline(),
            Some(start + Duration::from_millis(50))
        );

        // Adding an interval that fires sooner wins.
        sched.borrow_mut().set_interval(|_| true, 10);
        assert_eq!(
            sched.borrow_mut().next_deadline(),
            Some(start + Duration::from_millis(10))
        );
    }
}