pocopine-core 0.1.0

Client-side reactive runtime for pocopine — a Rust/WASM port of Alpine.js.
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
//! `pp-transition:*` — CSS-class based enter / leave animations.
//!
//! Per RFC-005. Six optional attributes provide the class strings:
//!
//! | Attribute | Phase |
//! |---|---|
//! | `pp-transition:enter`       | held for the whole enter phase |
//! | `pp-transition:enter-start` | one frame at the start of enter |
//! | `pp-transition:enter-end`   | rest of enter phase (replaces -start) |
//! | `pp-transition:leave`       | held for the whole leave phase |
//! | `pp-transition:leave-start` | one frame at the start of leave |
//! | `pp-transition:leave-end`   | rest of leave phase (replaces -start) |
//!
//! Callers don't register this as a directive. `pp-show` and `pp-if`
//! call [`enter`] / [`leave`] at mount/unmount time; those functions
//! lazy-init the per-element state by reading the attributes on first
//! use. When no transition attributes are present, the callbacks fire
//! synchronously — the "no-animation" path stays free.

use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;

use js_sys::Reflect;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsValue;
use web_sys::{window, Element};

const TX_ID_KEY: &str = "__pp_tx_id";

#[derive(Clone, Copy, PartialEq, Eq)]
enum Phase {
    Idle,
    Entering,
    Leaving,
}

struct State {
    enter: Vec<String>,
    enter_start: Vec<String>,
    enter_end: Vec<String>,
    leave: Vec<String>,
    leave_start: Vec<String>,
    leave_end: Vec<String>,
    /// Incremented on every cancel / phase-start. End callbacks
    /// capture the epoch at schedule time and no-op if it moved.
    epoch: u64,
    phase: Phase,
    pending_timer: Option<i32>,
}

impl State {
    fn any(&self) -> bool {
        !self.enter.is_empty()
            || !self.enter_start.is_empty()
            || !self.enter_end.is_empty()
            || !self.leave.is_empty()
            || !self.leave_start.is_empty()
            || !self.leave_end.is_empty()
    }

    fn all_classes(&self) -> impl Iterator<Item = &String> {
        self.enter
            .iter()
            .chain(self.enter_start.iter())
            .chain(self.enter_end.iter())
            .chain(self.leave.iter())
            .chain(self.leave_start.iter())
            .chain(self.leave_end.iter())
    }
}

thread_local! {
    static TX: RefCell<HashMap<u64, Rc<RefCell<State>>>> =
        RefCell::new(HashMap::new());
    static NEXT_ID: Cell<u64> = const { Cell::new(1) };
    /// When true, `enter` / `leave` fire `on_done` synchronously and
    /// skip the CSS-class machinery. Tests opt in via
    /// `pocopine::animate::disable()` so previously-instant
    /// mount/unmount assertions stay fast after RFC-038's defaults
    /// gave every Pine primitive a real CSS transition.
    static DISABLED: Cell<bool> = const { Cell::new(false) };
}

/// Globally turn off CSS transitions for `pp-transition`. Intended
/// for tests; production code should leave the default in place.
pub fn set_disabled(v: bool) {
    DISABLED.with(|c| c.set(v));
}

pub fn is_disabled() -> bool {
    DISABLED.with(|c| c.get())
}

fn get_or_init(el: &Element) -> Option<Rc<RefCell<State>>> {
    if let Some(v) = Reflect::get(el.as_ref(), &TX_ID_KEY.into())
        .ok()
        .and_then(|v| v.as_f64())
    {
        let id = v as u64;
        return TX.with(|m| m.borrow().get(&id).cloned());
    }
    // RFC-038 preset shorthand — if the element carries
    // `pp-transition="fade"` (symmetric) or the asymmetric split
    // `pp-transition:in="scale"` / `pp-transition:out="fade"`,
    // expand to the six `pp-transition:*` attrs here before
    // parsing. `apply_preset` is a no-op when the element already
    // has the six attrs (or when the name is `none` / unknown).
    expand_preset_shorthand(el);
    let state = parse_attrs(el);
    if !state.any() {
        return None;
    }
    let id = NEXT_ID.with(|c| {
        let v = c.get();
        c.set(v + 1);
        v
    });
    let rc = Rc::new(RefCell::new(state));
    TX.with(|m| m.borrow_mut().insert(id, rc.clone()));
    let _ = Reflect::set(
        el.as_ref(),
        &TX_ID_KEY.into(),
        &JsValue::from_f64(id as f64),
    );
    Some(rc)
}

/// If the element carries a preset shorthand (`pp-transition="fade"`
/// or `pp-transition:in` / `pp-transition:out`), expand it into the
/// six `pp-transition:*` class attrs via `animate::apply_preset`.
/// The already-six-attr author path stays untouched — explicit attrs
/// win if both are present (we only fill in attrs the author didn't
/// already set).
fn expand_preset_shorthand(el: &Element) {
    let sym = el.get_attribute("pp-transition");
    let in_attr = el.get_attribute("pp-transition:in");
    let out_attr = el.get_attribute("pp-transition:out");
    if sym.is_none() && in_attr.is_none() && out_attr.is_none() {
        return;
    }
    let symmetric = sym.as_deref().unwrap_or("");
    let in_name = in_attr.as_deref().unwrap_or(symmetric);
    let out_name = out_attr.as_deref().unwrap_or(symmetric);
    // Only stamp attrs that aren't already explicitly set by the
    // author — mix-and-match: author can override a single phase.
    let has = |name: &str| el.has_attribute(name);
    if has("pp-transition:enter")
        && has("pp-transition:enter-start")
        && has("pp-transition:enter-end")
        && has("pp-transition:leave")
        && has("pp-transition:leave-start")
        && has("pp-transition:leave-end")
    {
        return;
    }
    crate::animate::apply_preset(el, in_name, out_name);
}

fn parse_attrs(el: &Element) -> State {
    fn split(s: &str) -> Vec<String> {
        s.split_whitespace().map(str::to_string).collect()
    }
    let get = |name: &str| {
        el.get_attribute(name)
            .map(|s| split(&s))
            .unwrap_or_default()
    };
    State {
        enter: get("pp-transition:enter"),
        enter_start: get("pp-transition:enter-start"),
        enter_end: get("pp-transition:enter-end"),
        leave: get("pp-transition:leave"),
        leave_start: get("pp-transition:leave-start"),
        leave_end: get("pp-transition:leave-end"),
        epoch: 0,
        phase: Phase::Idle,
        pending_timer: None,
    }
}

fn cancel(state: &mut State, el: &Element) {
    let cl = el.class_list();
    for c in state.all_classes() {
        let _ = cl.remove_1(c);
    }
    if let Some(h) = state.pending_timer.take() {
        if let Some(w) = window() {
            w.clear_timeout_with_handle(h);
        }
    }
    state.epoch = state.epoch.wrapping_add(1);
    state.phase = Phase::Idle;
}

/// True if `el` has a transition mid-leave. Consumers (`pp-if`) use
/// this to decide whether a flip-back-to-truthy needs to cancel the
/// pending unmount or can no-op.
pub fn is_leaving(el: &Element) -> bool {
    match get_or_init(el) {
        Some(rc) => rc.borrow().phase == Phase::Leaving,
        None => false,
    }
}

/// Run the enter sequence on `el`, then invoke `on_done`. If no
/// `pp-transition:*` attrs are present, invokes `on_done` synchronously.
///
/// Honours `prefers-reduced-motion` (RFC-039 §1) — when reduced and
/// the element has no `data-pp-motion="always"` opt-out, fires
/// `on_done` synchronously and skips the class swap. Authors who
/// want motion under reduced-motion stamp `data-pp-motion="always"`
/// (the `#[component(motion = "always")]` macro arg does this).
pub fn enter<F: FnOnce() + 'static>(el: &Element, on_done: F) {
    if is_disabled() {
        on_done();
        return;
    }
    if crate::animate::motion::effective_for(el)
        == crate::animate::motion::MotionPreference::Reduced
    {
        on_done();
        return;
    }
    let rc = match get_or_init(el) {
        Some(r) => r,
        None => {
            on_done();
            return;
        }
    };

    // Cancel whatever was in flight (leaving, or stale entering).
    {
        let mut s = rc.borrow_mut();
        cancel(&mut s, el);
        s.phase = Phase::Entering;
    }
    let epoch = rc.borrow().epoch;

    // Two-phase swap. Apply ONLY `enter-start` (the initial state)
    // first, force a reflow so the browser commits opacity:0 /
    // transform:scale(...) WITHOUT a transition rule active. Then
    // on next frame, add `enter` (which carries the
    // `transition: opacity ..., transform ...` shorthand) AND
    // `enter-end` (the final state) at once, removing
    // `enter-start`. The browser sees the property change with a
    // transition rule already present and starts a clean tween.
    //
    // The earlier single-phase pattern (add base+from together)
    // looked correct but kicked off a TRANSITION from the prior
    // computed value (opacity:1 for a freshly cloned element) to
    // the from-state (opacity:0). The next-frame swap to `to` then
    // interrupted that in-flight tween with a new target near the
    // current value, leaving opacity stuck around 1 — the
    // user-visible "content settles before the overlay fades in"
    // flicker on Pine Dialog.
    let cl = el.class_list();
    {
        let s = rc.borrow();
        for c in &s.enter_start {
            let _ = cl.add_1(c);
        }
    }
    let _ = el.client_width();

    let el_cap = el.clone();
    let rc_cap = rc.clone();
    let on_done_cell = std::rc::Rc::new(std::cell::RefCell::new(Some(on_done)));
    crate::tick::next_frame(move || {
        if rc_cap.borrow().epoch != epoch {
            return;
        }
        let cl = el_cap.class_list();
        {
            let s = rc_cap.borrow();
            for c in &s.enter_start {
                let _ = cl.remove_1(c);
            }
            for c in &s.enter {
                let _ = cl.add_1(c);
            }
            for c in &s.enter_end {
                let _ = cl.add_1(c);
            }
        }
        let el_for_end = el_cap.clone();
        let rc_for_end = rc_cap.clone();
        let on_done_cell = on_done_cell.clone();
        schedule_end(&el_cap, rc_cap.clone(), epoch, move || {
            // KEEP `enter` (base) + `enter-end` (to) on the element
            // post-settle. Removing them at the moment the
            // transition completes triggered a visible end-of-enter
            // flicker: `transform: matrix(1,0,0,1,0,0)` snapping
            // to `transform: none` (semantically identical, but
            // browsers re-rasterize anti-aliased glyphs / borders
            // on style change). The `enter` class still has the
            // `transition: opacity ...` rule active, so a later
            // author-side style change to opacity / transform
            // would tween — but for Pine compounds those are
            // stable post-mount, and the trade-off (no flicker)
            // wins. `cancel()` at the start of `leave()` clears
            // these before the leave dispatch, so the next round
            // has a clean slate.
            let _ = el_for_end;
            let mut s = rc_for_end.borrow_mut();
            s.phase = Phase::Idle;
            drop(s);
            if let Some(cb) = on_done_cell.borrow_mut().take() {
                cb();
            }
        });
    });
}

/// Run the leave sequence on `el`, then invoke `on_done`. Callers pass
/// the real "hide or remove" work as `on_done` so the DOM mutation
/// happens after the animation completes. With no transition attrs,
/// `on_done` fires synchronously.
pub fn leave<F: FnOnce() + 'static>(el: &Element, on_done: F) {
    if is_disabled() {
        on_done();
        return;
    }
    if crate::animate::motion::effective_for(el)
        == crate::animate::motion::MotionPreference::Reduced
    {
        on_done();
        return;
    }
    let rc = match get_or_init(el) {
        Some(r) => r,
        None => {
            on_done();
            return;
        }
    };

    {
        let mut s = rc.borrow_mut();
        cancel(&mut s, el);
        s.phase = Phase::Leaving;
    }
    let epoch = rc.borrow().epoch;

    // Mirror enter()'s two-phase swap. For leave: the element is
    // currently visible (opacity:1 etc.). Apply ONLY `leave-start`
    // first to lock in the current rendered state explicitly, then
    // on next frame add `leave` (transition rule) and `leave-end`
    // (target state) at once so the browser tweens cleanly from
    // start to end.
    let cl = el.class_list();
    {
        let s = rc.borrow();
        for c in &s.leave_start {
            let _ = cl.add_1(c);
        }
    }
    let _ = el.client_width();

    let el_cap = el.clone();
    let rc_cap = rc.clone();
    let on_done_cell = std::rc::Rc::new(std::cell::RefCell::new(Some(on_done)));
    crate::tick::next_frame(move || {
        if rc_cap.borrow().epoch != epoch {
            return;
        }
        let cl = el_cap.class_list();
        {
            let s = rc_cap.borrow();
            for c in &s.leave_start {
                let _ = cl.remove_1(c);
            }
            for c in &s.leave {
                let _ = cl.add_1(c);
            }
            for c in &s.leave_end {
                let _ = cl.add_1(c);
            }
        }
        let el_for_end = el_cap.clone();
        let rc_for_end = rc_cap.clone();
        let on_done_cell = on_done_cell.clone();
        schedule_end(&el_cap, rc_cap.clone(), epoch, move || {
            // Same reasoning as enter: keep the leave classes
            // applied. For pp-if leave, the on_done callback
            // removes the element entirely — the classes go with
            // it. For pp-show leave, the on_done sets `display:
            // none` so the leftover classes are invisible until
            // the next enter, which `cancel`s them in its first
            // step.
            let _ = el_for_end;
            let mut s = rc_for_end.borrow_mut();
            s.phase = Phase::Idle;
            drop(s);
            if let Some(cb) = on_done_cell.borrow_mut().take() {
                cb();
            }
        });
    });
}

/// Schedule `on_done` to fire after the element's computed
/// `transition-duration + transition-delay` (plus a small slop). If
/// the total is zero, fires synchronously — matches the "no transition
/// configured" fast path for pp-show/pp-if.
fn schedule_end<F: FnOnce() + 'static>(
    el: &Element,
    rc: Rc<RefCell<State>>,
    epoch: u64,
    on_done: F,
) {
    let duration = computed_duration_ms(el);
    if duration <= 0.0 {
        on_done();
        return;
    }
    let rc_cap = rc.clone();
    let closure = Closure::once(Box::new(move || {
        let current_epoch = rc_cap.borrow().epoch;
        if current_epoch != epoch {
            return;
        }
        rc_cap.borrow_mut().pending_timer = None;
        on_done();
    }) as Box<dyn FnOnce()>);
    if let Some(w) = window() {
        if let Ok(handle) = w.set_timeout_with_callback_and_timeout_and_arguments_0(
            closure.as_ref().unchecked_ref(),
            (duration + 20.0) as i32,
        ) {
            rc.borrow_mut().pending_timer = Some(handle);
        }
    }
    closure.forget();
}

fn computed_duration_ms(el: &Element) -> f64 {
    let Some(w) = window() else { return 0.0 };
    let Ok(Some(cs)) = w.get_computed_style(el) else {
        return 0.0;
    };
    let dur = cs
        .get_property_value("transition-duration")
        .unwrap_or_default();
    let delay = cs
        .get_property_value("transition-delay")
        .unwrap_or_default();
    parse_duration(&dur) + parse_duration(&delay)
}

fn parse_duration(s: &str) -> f64 {
    // `transition-*` may be comma-separated when properties have
    // different timings (e.g. `opacity 100ms, transform 250ms`).
    // Take the MAX so `schedule_end` waits for the longest property
    // — RFC-039 §4 fixes a bug where reading the first value early-
    // fired `on_done` and yanked the element mid-transform.
    s.split(',')
        .map(|seg| {
            let t = seg.trim();
            if let Some(n) = t.strip_suffix("ms") {
                n.trim().parse::<f64>().unwrap_or(0.0)
            } else if let Some(n) = t.strip_suffix('s') {
                n.trim().parse::<f64>().unwrap_or(0.0) * 1000.0
            } else {
                0.0
            }
        })
        .fold(0.0_f64, f64::max)
}

/// Selector matching every element that carries any preset attr
/// (shorthand or six-attr form). Used by the subtree helpers to
/// gather descendants whose transitions should fire alongside the
/// pp-if/pp-show toggle on the clone root.
const ATTR_SELECTOR: &str = "[pp-transition], [pp-transition\\:in], [pp-transition\\:out], \
    [pp-transition\\:enter], [pp-transition\\:enter-start], [pp-transition\\:enter-end], \
    [pp-transition\\:leave], [pp-transition\\:leave-start], [pp-transition\\:leave-end]";

fn has_any_transition_attr(el: &Element) -> bool {
    el.has_attribute("pp-transition")
        || el.has_attribute("pp-transition:in")
        || el.has_attribute("pp-transition:out")
        || el.has_attribute("pp-transition:enter")
        || el.has_attribute("pp-transition:enter-start")
        || el.has_attribute("pp-transition:enter-end")
        || el.has_attribute("pp-transition:leave")
        || el.has_attribute("pp-transition:leave-start")
        || el.has_attribute("pp-transition:leave-end")
}

pub fn has_transition_in_subtree(root: &Element) -> bool {
    if has_any_transition_attr(root) {
        return true;
    }
    root.query_selector(ATTR_SELECTOR).ok().flatten().is_some()
}

fn collect_animated(root: &Element) -> Vec<Element> {
    use wasm_bindgen::JsCast;
    let mut out = Vec::new();
    if has_any_transition_attr(root) {
        out.push(root.clone());
    }
    if let Ok(list) = root.query_selector_all(ATTR_SELECTOR) {
        for i in 0..list.length() {
            if let Some(node) = list.item(i) {
                if let Ok(el) = node.dyn_into::<Element>() {
                    out.push(el);
                }
            }
        }
    }
    out
}

/// Run the enter sequence on `root` AND every descendant carrying
/// any `pp-transition:*` attr. Compound primitives stamp preset
/// attrs on inner custom-element children (`<pine-dialog-content>`)
/// rather than the pp-if clone root (the portal `<div>`), so
/// callers walking the subtree pick those up. `on_done` fires after
/// the longest enter completes; with no animated elements it's
/// synchronous.
pub fn enter_subtree<F: FnOnce() + 'static>(root: &Element, on_done: F) {
    enter_subtree_dyn(root, Box::new(on_done));
}

// RFC-058 Phase 6.5 — type-erased implementation. The generic
// shim above forwards into this single boxed instantiation so
// the bulk of `enter_subtree`'s body collapses to one wasm
// function regardless of how many distinct closure types call
// it. Twiggy showed `transition::enter_subtree::<F>` totalling
// ~7 KB across pp-for / pp-if / show / for_::run_keyed closure
// types before this consolidation.
fn enter_subtree_dyn(root: &Element, on_done: Box<dyn FnOnce() + 'static>) {
    let elems = collect_animated(root);
    if elems.is_empty() {
        on_done();
        return;
    }
    let remaining = Rc::new(Cell::new(elems.len()));
    let on_done_cell = Rc::new(RefCell::new(Some(on_done)));
    for el in elems {
        let remaining = remaining.clone();
        let on_done_cell = on_done_cell.clone();
        enter(&el, move || {
            let n = remaining.get().saturating_sub(1);
            remaining.set(n);
            if n == 0 {
                if let Some(cb) = on_done_cell.borrow_mut().take() {
                    cb();
                }
            }
        });
    }
}

/// Stagger the enter transition across many clones in one batch.
///
/// `enter_subtree` fires every clone's enter simultaneously;
/// `enter_subtree_staggered` delays the whole enter call per index
/// (so clone `i` waits `i * stagger_ms` ms). The big difference is
/// that `staggered` lets clones render at their natural state
/// during the delay, then snap to the start state when their turn
/// comes — visible "pop then shrink" artefact.
///
/// This batched variant fixes that by:
///
///   1. Walking every clone and stamping the `enter-start` class
///      on each animated descendant synchronously.
///   2. Doing ONE forced reflow across the batch so every clone
///      commits its start state before any transition fires.
///   3. Scheduling each clone's end-class swap at
///      `i * stagger_ms` ms, independently per clone.
///
/// Net effect for a 500-item mount: every chip is invisible /
/// scaled-down at the instant it enters the DOM, then animates in
/// at its assigned delay. No flash of default state.
///
/// Respects `prefers-reduced-motion` and the per-element
/// `data-pp-motion="always"` opt-out (the normal `enter` path).
pub fn enter_subtrees_sequenced(clones: &[Element], stagger_ms: u32) {
    // Resolved + filtered per-clone descendant lists + their state
    // rcs, so the deferred finisher doesn't re-walk.
    struct Pending {
        el: Element,
        rc: Rc<RefCell<State>>,
        epoch: u64,
    }
    let mut batch: Vec<Vec<Pending>> = Vec::with_capacity(clones.len());
    for root in clones {
        let mut per_clone: Vec<Pending> = Vec::new();
        for el in collect_animated(root) {
            if is_disabled() {
                continue;
            }
            if crate::animate::motion::effective_for(&el)
                == crate::animate::motion::MotionPreference::Reduced
            {
                continue;
            }
            let Some(rc) = get_or_init(&el) else { continue };
            {
                let mut s = rc.borrow_mut();
                cancel(&mut s, &el);
                s.phase = Phase::Entering;
            }
            let epoch = rc.borrow().epoch;
            let cl = el.class_list();
            {
                let s = rc.borrow();
                for c in &s.enter_start {
                    let _ = cl.add_1(c);
                }
            }
            per_clone.push(Pending { el, rc, epoch });
        }
        batch.push(per_clone);
    }

    // ONE forced reflow across everyone. Commits the start-state
    // class writes synchronously so the browser caches state-A
    // before we queue state-B swaps.
    if let Some(first_clone) = batch.iter().flatten().next() {
        let _ = first_clone.el.client_width();
    }

    // Schedule all class swaps through `next_frame` so they land
    // AFTER the browser has painted the enter-start state. Without
    // this, applying start + end classes in the same JS task can
    // cause the browser to coalesce both writes into a single
    // style recalc — no transition fires because the engine never
    // sees the start values as a distinct "previous" state.
    //
    // Inside the rAF callback, each clone's end-class swap fires
    // at `i * stagger_ms` ms via `setTimeout`. Clone 0 fires
    // immediately within the frame; the rest shift in sequence.
    crate::tick::next_frame(move || {
        for (i, per_clone) in batch.into_iter().enumerate() {
            let delay = (i as u32).saturating_mul(stagger_ms);
            let finish = move || {
                for Pending { el, rc, epoch } in per_clone {
                    // Epoch check — if a leave dispatched between
                    // start-class and this delayed finish (e.g. the
                    // pp-for condition flipped, the clone got
                    // removed), bail so we don't apply end classes
                    // to a detached element.
                    if rc.borrow().epoch != epoch {
                        continue;
                    }
                    let cl = el.class_list();
                    {
                        let s = rc.borrow();
                        for c in &s.enter_start {
                            let _ = cl.remove_1(c);
                        }
                        for c in &s.enter {
                            let _ = cl.add_1(c);
                        }
                        for c in &s.enter_end {
                            let _ = cl.add_1(c);
                        }
                    }
                    let rc_for_end = rc.clone();
                    schedule_end(&el, rc.clone(), epoch, move || {
                        let mut s = rc_for_end.borrow_mut();
                        s.phase = Phase::Idle;
                    });
                }
            };
            if delay == 0 {
                finish();
            } else if let Some(window) = window() {
                let cb = Closure::once_into_js(finish);
                let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(
                    cb.unchecked_ref(),
                    delay as i32,
                );
            }
        }
    });
}

/// Like [`enter_subtree`] but each animated descendant fires with
/// an additional `i * stagger_ms` delay (where `i` is its index in
/// the collected list). Useful for sequenced reveals on `pp-for`
/// list mounts (RFC-039 §6).
///
/// `on_done` fires after the LAST animation settles. Pass
/// `stagger_ms = 0` for the same behaviour as [`enter_subtree`].
pub fn enter_subtree_staggered<F: FnOnce() + 'static>(root: &Element, stagger_ms: u32, on_done: F) {
    let elems = collect_animated(root);
    if elems.is_empty() {
        on_done();
        return;
    }
    let remaining = Rc::new(Cell::new(elems.len()));
    let on_done_cell = Rc::new(RefCell::new(Some(on_done)));
    for (i, el) in elems.into_iter().enumerate() {
        let remaining = remaining.clone();
        let on_done_cell = on_done_cell.clone();
        let delay = (i as u32).saturating_mul(stagger_ms);
        let fire = move || {
            enter(&el, move || {
                let n = remaining.get().saturating_sub(1);
                remaining.set(n);
                if n == 0 {
                    if let Some(cb) = on_done_cell.borrow_mut().take() {
                        cb();
                    }
                }
            });
        };
        if delay == 0 {
            fire();
        } else {
            let cb = wasm_bindgen::closure::Closure::once_into_js(fire);
            if let Some(w) = web_sys::window() {
                let _ = w.set_timeout_with_callback_and_timeout_and_arguments_0(
                    cb.unchecked_ref(),
                    delay as i32,
                );
            }
        }
    }
}

/// Mirror of [`enter_subtree`] for unmount. Dispatches `leave` to
/// every animated element in the subtree in parallel; the caller's
/// `on_done` (typically the actual DOM removal) fires once they all
/// complete. Synchronous when no element animates.
///
/// A safety timeout backstops the counter. When a different caller
/// dispatches leaves onto the same elements (for example, pp-if
/// wrapping a pp-for — pp-if's subtree walk finds every chip while
/// pp-for ALSO dispatches per-chip leaves, and the second `leave`
/// call cancels the first's `schedule_end`), some of this caller's
/// counter callbacks never fire. Without the backstop, `on_done`
/// never runs and the caller's clone (e.g. pp-if's wrapper) stays
/// stranded in the DOM. The backstop gives the real transitions
/// plenty of time to land first — if they don't, we fire `on_done`
/// anyway so the DOM doesn't leak.
pub fn leave_subtree<F: FnOnce() + 'static>(root: &Element, on_done: F) {
    leave_subtree_dyn(root, Box::new(on_done));
}

// RFC-058 Phase 6.5 — type-erased counterpart to
// `enter_subtree_dyn`. Same monomorphization-collapse rationale.
fn leave_subtree_dyn(root: &Element, on_done: Box<dyn FnOnce() + 'static>) {
    let elems = collect_animated(root);
    if elems.is_empty() {
        on_done();
        return;
    }
    let remaining = Rc::new(Cell::new(elems.len()));
    let on_done_cell = Rc::new(RefCell::new(Some(on_done)));

    // Safety backstop — one second is well past any default Pine
    // transition (the longest preset is 300 ms). Enough buffer
    // that an overlapping leave's cancellation doesn't leave the
    // caller's counter stuck; soon enough that a leaked clone
    // doesn't linger for the user.
    const SAFETY_MS: i32 = 1000;
    let remaining_for_safety = remaining.clone();
    let on_done_for_safety = on_done_cell.clone();
    let safety = Closure::once_into_js(move || {
        if remaining_for_safety.get() > 0 {
            if let Some(cb) = on_done_for_safety.borrow_mut().take() {
                cb();
            }
        }
    });
    if let Some(w) = window() {
        let _ = w.set_timeout_with_callback_and_timeout_and_arguments_0(
            safety.unchecked_ref(),
            SAFETY_MS,
        );
    }

    for el in elems {
        let remaining = remaining.clone();
        let on_done_cell = on_done_cell.clone();
        leave(&el, move || {
            let n = remaining.get().saturating_sub(1);
            remaining.set(n);
            if n == 0 {
                if let Some(cb) = on_done_cell.borrow_mut().take() {
                    cb();
                }
            }
        });
    }
}

/// True if any element in the subtree (root included) is mid-leave.
pub fn is_subtree_leaving(root: &Element) -> bool {
    collect_animated(root).iter().any(is_leaving)
}

/// Drop any transition state associated with `el`. Called from the
/// mount's `release_subtree` when an element is unmounted — keeps
/// the thread-local map from growing unboundedly.
pub fn release(el: &Element) {
    let Some(id) = Reflect::get(el.as_ref(), &TX_ID_KEY.into())
        .ok()
        .and_then(|v| v.as_f64())
    else {
        return;
    };
    let id = id as u64;
    TX.with(|m| {
        if let Some(rc) = m.borrow_mut().remove(&id) {
            if let Some(h) = rc.borrow_mut().pending_timer.take() {
                if let Some(w) = window() {
                    w.clear_timeout_with_handle(h);
                }
            }
        }
    });
}

#[cfg(test)]
mod tests {
    use super::parse_duration;

    #[test]
    fn parses_ms() {
        assert_eq!(parse_duration("300ms"), 300.0);
    }

    #[test]
    fn parses_fractional_seconds() {
        assert_eq!(parse_duration("0.3s"), 300.0);
    }

    #[test]
    fn empty_is_zero() {
        assert_eq!(parse_duration(""), 0.0);
    }

    #[test]
    fn takes_first_of_list() {
        assert_eq!(parse_duration("300ms, 200ms"), 300.0);
    }
}