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
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
//! Component scopes and the JS-`Proxy` bridge they expose to directives.
//!
//! A scope owns a `ComponentState` (macro-generated), a stable `ScopeId`, and
//! a `js_sys::Proxy` whose `get`/`set` traps plug into [`crate::reactive`] so
//! any directive that reads a field through the proxy gets auto-subscribed.

use std::any::Any;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use js_sys::{Array, Function, Object, Proxy, Reflect};
use wasm_bindgen::closure::Closure;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsValue;
use web_sys::Element;

use crate::magics;
use crate::reactive::{next_scope_id, track, trigger, trigger_scope, ScopeId};

/// Static HTML attributes are strings, but Pocopine has historically
/// coerced them before writing component props. The macro supplies this
/// narrow field-kind hint so the runtime can preserve numeric-looking
/// strings for `String` props while keeping number/bool ergonomics for
/// number/bool props.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum StaticPropKind {
    Auto,
    String,
    Bool,
    Number,
}

/// Implemented by components (generated by `#[component]` + `#[handlers]`).
pub trait ComponentState: 'static {
    /// Read a declared field as a JsValue (for proxy `get`).
    fn get(&self, key: &str) -> JsValue;

    /// Whether this state's `get` returns values worth caching in the
    /// per-scope `FIELD_CACHE`. Defaults to `true` for component
    /// states (where `get` re-serialises Rust state through serde and
    /// the cache cuts the cost down to one allocation per trigger
    /// cycle). Override to `false` for "derived" scopes whose `get`
    /// reads through to a parent proxy — `SlotScope`'s `ctx` ident
    /// composes a fresh JS object from the owner's current field
    /// values on each call, so caching it would freeze the slot at
    /// its first-render snapshot even after the owner mutates.
    fn cacheable_fields(&self) -> bool {
        true
    }

    /// Write a declared field from a JsValue (for proxy `set`).
    fn set(&mut self, key: &str, value: JsValue);

    /// All data keys this component exposes. Used for sweep-triggers after
    /// a handler invocation.
    fn keys(&self) -> &'static [&'static str];

    /// RFC-031 — is `key` annotated `#[prop]`? Returns `false` for
    /// state fields (the default — anything not explicitly
    /// marked as part of the parent contract). Used by
    /// `apply_static_props`, `pp-bind`'s child-prop write, and
    /// `pp-model`'s mirror-in leg to keep parents out of state.
    /// Unknown keys return `false` — the runtime also uses
    /// `keys()` / `set()` to know which fields exist at all.
    fn is_prop(&self, key: &str) -> bool {
        let _ = key;
        false
    }

    /// Coercion hint for static HTML attrs targeting `#[prop]`
    /// fields. Unknown and flattened props use `Auto`, preserving the
    /// pre-existing generic coercion path.
    fn static_prop_kind(&self, key: &str) -> StaticPropKind {
        let _ = key;
        StaticPropKind::Auto
    }

    /// RFC-044 §5.10 — for a `flatten` leaf key, the container field
    /// key it writes through; `None` for ordinary keys. A write to a
    /// flattened leaf mutates the *whole* container field, so the
    /// proxy `set` trap triggers both the leaf key and the container
    /// key — that is what lets a single `#[watch(<container>)]` fire
    /// when any one leaf changes. Defaults to `None` so non-component
    /// scopes and flatten-free components need no override.
    fn flatten_container_of(&self, key: &str) -> Option<&'static str> {
        let _ = key;
        None
    }

    /// True iff `key` is a `#[model]` field. Runtime uses this for
    /// assignment-driven model publication and devtools metadata.
    fn is_model(&self, key: &str) -> bool {
        let _ = key;
        false
    }

    /// Public wire name reserved by a `#[model]` field. Returns `None`
    /// for non-model keys.
    fn model_name(&self, key: &str) -> Option<&'static str> {
        let _ = key;
        None
    }

    /// Serialize a model field with any field-level serde attrs still
    /// in play. Defaults to the plain field getter so non-component
    /// scopes keep compiling.
    fn get_model_value(&self, key: &str) -> JsValue {
        self.get(key)
    }

    /// Invoke a named method on `&mut self` with JS-land arguments.
    /// Returns a JsValue (or `JsValue::UNDEFINED` for void methods).
    fn invoke(&mut self, key: &str, args: &Array) -> JsValue;

    /// Lifecycle — called once right after the scope is minted and
    /// its RFC-027 parent is set, *before* the template's children
    /// walk. Lets compound-component children initialise fields
    /// from injected context so directives in their template see
    /// the populated values on first bind. Default no-op;
    /// `#[component]` wires the user's `on_setup` when one exists.
    /// RFC 056 follow-on: receives a `LifecycleContext` (phase
    /// `Setup`) so authors can extract `Inject<KEY, T>`,
    /// `Handle<Self>`, etc. Element-dependent extractors panic in
    /// this phase (template hasn't been walked).
    fn setup(&mut self, ctx: crate::lifecycle::LifecycleContext<'_>) {
        let _ = ctx;
    }

    /// Lifecycle — called once after the component's subtree is fully
    /// bound. Default no-op; `#[component]` wires the user's
    /// `on_mount` when one exists. RFC-032: receives a
    /// `LifecycleContext` so handler signatures can extract the
    /// rendered root, scope id, refs, etc. via `From`.
    fn mount(&mut self, ctx: crate::lifecycle::LifecycleContext<'_>) {
        let _ = ctx;
    }

    /// Lifecycle — called once, scheduled via `tick::next` AFTER
    /// `mount()` returns. Takes `&self` (not `&mut self`) so
    /// proxy-reading code inside the hook (watches, refs, etc.)
    /// doesn't clash with the scope's state borrow. Mutation in
    /// on_ready goes through `pocopine::this::<Self>().update(...)`.
    /// Default no-op; `#[component]` wires the user's `on_ready`
    /// when one exists. See RFC-026 / RFC-029 / RFC-032.
    fn on_ready(&self, ctx: crate::lifecycle::LifecycleContext<'_>) {
        let _ = ctx;
    }

    /// Lifecycle — called once just before the component is torn down.
    /// Default no-op; `#[component]` wires the user's `on_unmount`
    /// when one exists. RFC 056 follow-on: receives a
    /// `LifecycleContext` (phase `Unmount`) for symmetry with the
    /// other lifecycle hooks. Element-dependent extractors panic
    /// (the element may already be detaching).
    fn unmount(&mut self, ctx: crate::lifecycle::LifecycleContext<'_>) {
        let _ = ctx;
    }

    /// True iff the component has a user-defined `on_setup`.
    /// `mount_component` uses this to skip the setup call for
    /// components without the hook.
    fn has_setup(&self) -> bool {
        false
    }

    /// True iff the component actually has a user-defined `on_mount`.
    /// Lets the mount skip the post-mount `trigger_scope` sweep for
    /// components that don't need it — critical for recursive
    /// children, where a blanket sweep would cascade through the
    /// whole subtree.
    fn has_on_mount(&self) -> bool {
        false
    }

    /// True iff the component has a user-defined `on_ready` hook.
    /// Walker uses this to decide whether to schedule a microtask
    /// after mount — components without the hook pay nothing.
    fn has_on_ready(&self) -> bool {
        false
    }

    /// Symmetric with [`has_on_mount`]. Kept for parity; reserved
    /// for future devtools coverage displays.
    fn has_on_unmount(&self) -> bool {
        false
    }

    /// RFC-038 — enter preset name the component declared at
    /// `#[component(transition = "…")]` (or `transition_in`). The
    /// mount calls this once post-template-clone to stamp the
    /// preset's `pp-transition:*` attrs on the rendered root.
    fn transition_in_preset(&self) -> &'static str {
        ""
    }

    /// RFC-038 — leave preset name (`transition` or `transition_out`).
    fn transition_out_preset(&self) -> &'static str {
        ""
    }

    /// RFC-038 — keyed-pp-for layout-animation kind (only `"flip"`
    /// today). The mount's for_.rs hooks check this to decide
    /// whether to FLIP-animate reordered clones.
    fn animate_kind(&self) -> &'static str {
        ""
    }

    /// Human-readable tag / type name used by devtools. Default
    /// `"?"`; `#[component]` / `#[store]` override with the concrete
    /// kebab-case name.
    fn type_name(&self) -> &'static str {
        "?"
    }
}

/// A live component instance bound to a DOM element.
///
/// Holds both the type-erased `ComponentState` handle the mount uses and
/// a typed `Rc<RefCell<T>>` behind an `Any` for handler code that wants
/// to mutate the underlying Rust struct directly (see
/// [`crate::this`](crate::handle::this)).
#[derive(Clone)]
pub struct Scope {
    pub id: ScopeId,
    pub state: Rc<RefCell<dyn ComponentState>>,
    /// `Rc<RefCell<T>>` erased behind `dyn Any`. `T` is the concrete
    /// struct the user annotated with `#[component]` / `#[store]`.
    /// Downcast via [`Scope::typed`] to mutate Rust fields directly.
    pub typed: Rc<dyn Any>,
}

/// Type-erased storage for the two `Closure`s backing a proxy's
/// `get` and `set` traps. Kept as a `Vec<Box<dyn Any>>` so the
/// per-trap type parameters don't pollute the side-table's type.
/// Dropping the `Box<dyn Any>` drops the underlying `Closure`,
/// which reclaims the `Box<dyn Fn>` behind it — the whole point of
/// this table (old code called `.forget()` and leaked forever).
type AnyClosures = Vec<Box<dyn Any>>;

thread_local! {
    /// Registry of live scopes keyed by id. Directives look up the scope
    /// here to invoke handlers when an event fires.
    static SCOPES: RefCell<HashMap<ScopeId, Scope>> = RefCell::new(HashMap::new());

    /// Proxy-trap closures pinned to their owning scope id. Previously
    /// these were leaked via `Closure::forget()` — the comment there
    /// claimed "live as long as the scope" but `Scope::remove` had no
    /// code path to recover them. With the side-table, `Scope::remove`
    /// drops the entry and the two `Box<dyn Fn>` boxes behind the
    /// closures are reclaimed.
    static PROXY_CLOSURES: RefCell<HashMap<ScopeId, AnyClosures>> =
        RefCell::new(HashMap::new());

    /// RFC 054 phase A — per-scope cache of serialised JS values
    /// for `ComponentState::get` results. The proxy's `get` trap
    /// reads this first; cache miss falls through to
    /// `state.get(key)` (which serialises the field via
    /// `serde_wasm_bindgen`) and stores the result so subsequent
    /// reads of the same field reuse the same `JsValue`. Targeted
    /// list ops (`patch_list_at`, etc.) update the cache + the
    /// underlying Rust state in lockstep so the cached `Array` /
    /// `Object` identities stay stable across mutations — pp-for
    /// row identity becomes a pointer comparison instead of a
    /// fresh JSON.stringify per row.
    ///
    /// Invalidation: `set` trap drops the slot for that key;
    /// `Handle::update` / `Scope::invoke` clear the whole scope's
    /// cache after the closure / handler runs (we don't know
    /// which fields it touched). Fields the handler explicitly
    /// kept fresh via `patch_list_at_inline` are recorded in
    /// `FRESH_FIELDS` and survive invalidation.
    static FIELD_CACHE: RefCell<HashMap<ScopeId, HashMap<String, JsValue>>> =
        RefCell::new(HashMap::new());

    /// Per-scope set of field names that were explicitly kept in
    /// sync with Rust state by a `patch_*_inline` call. Consumed
    /// (and cleared) by the next `invalidate_field_cache` so
    /// only those fields survive the post-handler / post-update
    /// blanket invalidate.
    static FRESH_FIELDS: RefCell<HashMap<ScopeId, std::collections::HashSet<String>>> =
        RefCell::new(HashMap::new());

    /// The element the current directive is running against. Set by the
    /// mount immediately around each directive call so `$el` works without
    /// threading the element through every call site.
    static CURRENT_EL: RefCell<Option<Element>> = const { RefCell::new(None) };

    /// The scope whose handler is currently executing, if any. Set by
    /// `Scope::invoke` for the duration of the call so handlers can
    /// discover their own id — useful when a handler needs to capture the
    /// id for an `async` task that will mutate the scope after the
    /// handler returns.
    static CURRENT_SCOPE_ID: std::cell::Cell<Option<ScopeId>> =
        const { std::cell::Cell::new(None) };
}

impl Scope {
    /// Build a scope from a typed `Rc<RefCell<T>>`. Stashes both the
    /// type-erased and the typed form so later code (mount + handler
    /// handles) can choose the right one.
    pub fn new<T: ComponentState + 'static>(state: Rc<RefCell<T>>) -> Self {
        let id = next_scope_id();
        let erased: Rc<RefCell<dyn ComponentState>> = state.clone();
        let typed: Rc<dyn Any> = Rc::new(state);
        let scope = Scope {
            id,
            state: erased,
            typed,
        };
        SCOPES.with(|s| s.borrow_mut().insert(id, scope.clone()));
        scope
    }

    /// Look up a live scope by id.
    pub fn find(id: ScopeId) -> Option<Scope> {
        SCOPES.with(|s| s.borrow().get(&id).cloned())
    }

    /// Snapshot of every live scope, sorted by id. Devtools reads this
    /// to render the scope list.
    pub fn all() -> Vec<Scope> {
        SCOPES.with(|s| {
            let mut out: Vec<Scope> = s.borrow().values().cloned().collect();
            out.sort_by_key(|sc| sc.id.0);
            out
        })
    }

    /// Remove a scope from the registry. Called when its element is
    /// unmounted. Also drops any refs + captured slot content
    /// registered against this scope so we don't leak element
    /// handles.
    pub fn remove(id: ScopeId) {
        SCOPES.with(|s| s.borrow_mut().remove(&id));
        crate::refs::clear_scope(id);
        crate::mount::clear_light_dom_slots(id);
        crate::slot_fragment::clear(id);
        crate::id::clear_scope(id);
        crate::context::clear_scope(id);
        crate::events::clear_scope(id);
        crate::reactive::clear_scope(id);
        crate::component_computed::clear_scope(id);
        crate::model_runtime::clear_scope(id);
        crate::task::clear_scope(id);
        // Drop the proxy-trap closures that were pinned in
        // `into_proxy`. The `Box<dyn Any>` drop chain runs the
        // `Closure` destructor, which releases the underlying
        // `Box<dyn Fn>`.
        PROXY_CLOSURES.with(|m| {
            m.borrow_mut().remove(&id);
        });
        FIELD_CACHE.with(|c| {
            c.borrow_mut().remove(&id);
        });
        FRESH_FIELDS.with(|f| {
            f.borrow_mut().remove(&id);
        });
    }

    /// Bulk teardown for the RFC 054 compiled-row bulk-clear path.
    /// Drains every per-scope side-table once over the full slice
    /// instead of paying `12 × thread_local::with` per scope.
    /// Compiled row scopes are guaranteed not to register
    /// refs/slots/tasks/inject/computed/model state — those
    /// table-clears collapse to a no-op for known-empty maps.
    ///
    /// **Caller obligations:** every id in `ids` MUST be a
    /// compiled-row loop scope. General-purpose scope teardown
    /// still goes through [`Scope::remove`].
    pub fn remove_compiled_rows(ids: &[ScopeId]) {
        if ids.is_empty() {
            return;
        }
        SCOPES.with(|s| {
            let mut map = s.borrow_mut();
            for id in ids {
                map.remove(id);
            }
        });
        crate::reactive::clear_scopes(ids);
        // Compiled rows that never minted a proxy have no entry in
        // PROXY_CLOSURES / FIELD_CACHE / FRESH_FIELDS — the
        // per-id `remove` is a hash + compare with no value drop.
        // Still cheaper than 10K thread_local::with calls.
        PROXY_CLOSURES.with(|m| {
            let mut map = m.borrow_mut();
            if !map.is_empty() {
                for id in ids {
                    map.remove(id);
                }
            }
        });
        FIELD_CACHE.with(|c| {
            let mut map = c.borrow_mut();
            if !map.is_empty() {
                for id in ids {
                    map.remove(id);
                }
            }
        });
        FRESH_FIELDS.with(|f| {
            let mut map = f.borrow_mut();
            if !map.is_empty() {
                for id in ids {
                    map.remove(id);
                }
            }
        });
        crate::lifecycle::__clear_mount_epochs(ids);
    }

    /// Recover the typed inner `Rc<RefCell<T>>`, if `T` matches the struct
    /// this scope was created with. `None` on type mismatch.
    pub fn typed<T: 'static>(&self) -> Option<Rc<RefCell<T>>> {
        self.typed.downcast_ref::<Rc<RefCell<T>>>().cloned()
    }

    /// Read the cached `JsValue` for `field`, or `None` if no
    /// reader has populated the cache yet (or it was just
    /// invalidated). Used by [`patch_list_at`] and friends to
    /// apply targeted patches against the live JS object that
    /// effects are reading.
    pub fn cached_field(&self, field: &str) -> Option<JsValue> {
        FIELD_CACHE.with(|c| c.borrow().get(&self.id).and_then(|m| m.get(field).cloned()))
    }

    /// Replace the cached `JsValue` for `field`. Mostly used by
    /// targeted op APIs after they patch the cached value via
    /// `Reflect::set` and want subsequent readers to see the
    /// patched object identity.
    pub fn set_cached_field(&self, field: &str, value: JsValue) {
        FIELD_CACHE.with(|c| {
            c.borrow_mut()
                .entry(self.id)
                .or_default()
                .insert(field.to_string(), value);
        });
    }

    /// Build a `js_sys::Proxy` whose `get` trap records dependencies and
    /// whose `set` trap triggers them. The proxy is what every directive
    /// reads through.
    pub fn into_proxy(&self) -> JsValue {
        let target = Object::new();
        let handler = Object::new();
        let scope_id = self.id;
        let state_for_get = self.state.clone();
        let state_for_set = self.state.clone();

        let get_closure = Closure::wrap(Box::new(
            move |_target: JsValue, key: JsValue, _receiver: JsValue| -> JsValue {
                let Some(key_str) = key.as_string() else {
                    return JsValue::UNDEFINED;
                };
                if key_str.starts_with('$') {
                    // Loop scopes own these names; other `$...`
                    // reads stay on the magic resolver.
                    if matches!(key_str.as_str(), "$index" | "$first" | "$last") {
                        let local = state_for_get.borrow().get(&key_str);
                        if !local.is_undefined() {
                            track(scope_id, &key_str);
                            return local;
                        }
                    }
                    return magics::resolve(&key_str, scope_id);
                }
                track(scope_id, &key_str);
                // Derived scopes (`SlotScope`, etc.) compose their
                // return value from a parent proxy on every read —
                // caching would freeze the value at the first call.
                // Skip the cache lookup AND the cache write for
                // those; the trigger that matters lands on the
                // parent scope's key, picked up via the inner
                // `Reflect::get` inside `state.get`.
                let cacheable = state_for_get.borrow().cacheable_fields();
                if !cacheable {
                    return state_for_get.borrow().get(&key_str);
                }
                // RFC 054 phase A — field cache short-circuit. The
                // first `get` for a field invokes the macro-emitted
                // `ComponentState::get` (which serialises via
                // `serde_wasm_bindgen`); subsequent reads of the
                // same field by other effects in the same trigger
                // cycle reuse the cached JsValue. Targeted
                // `patch_*` ops keep the cache valid across
                // mutations so Vec fields don't pay the full
                // re-serialise tax on every reactive cycle.
                if let Some(cached) = FIELD_CACHE.with(|c| {
                    c.borrow()
                        .get(&scope_id)
                        .and_then(|m| m.get(&key_str).cloned())
                }) {
                    return cached;
                }
                let v = state_for_get.borrow().get(&key_str);
                FIELD_CACHE.with(|c| {
                    c.borrow_mut()
                        .entry(scope_id)
                        .or_default()
                        .insert(key_str.clone(), v.clone());
                });
                v
            },
        )
            as Box<dyn Fn(JsValue, JsValue, JsValue) -> JsValue>);

        let set_closure = Closure::wrap(Box::new(
            move |_target: JsValue, key: JsValue, value: JsValue, _receiver: JsValue| -> bool {
                let Some(key_str) = key.as_string() else {
                    return false;
                };
                let origin = crate::model_runtime::current_write_origin();
                crate::model_runtime::with_scope_write(scope_id, origin, || {
                    state_for_set.borrow_mut().set(&key_str, value);
                });
                // RFC-044 §5.10 — a write to a `flatten` leaf mutates
                // the whole container field. Resolve the container key
                // (short borrow, released before the triggers below)
                // so its cache is invalidated and `#[watch(<container>)]`
                // fires alongside the per-leaf watch.
                let flatten_container = state_for_set.borrow().flatten_container_of(&key_str);
                // RFC 054 phase A — invalidate the field's cached
                // JsValue (and the container's, if any). Next reader
                // will re-serialise from Rust state, picking up the
                // write the `set_closure` just applied.
                FIELD_CACHE.with(|c| {
                    if let Some(m) = c.borrow_mut().get_mut(&scope_id) {
                        m.remove(&key_str);
                        if let Some(container) = flatten_container {
                            m.remove(container);
                        }
                    }
                });
                trigger(scope_id, &key_str);
                if let Some(container) = flatten_container {
                    trigger(scope_id, container);
                }
                true
            },
        )
            as Box<dyn Fn(JsValue, JsValue, JsValue, JsValue) -> bool>);

        Reflect::set(
            &handler,
            &"get".into(),
            get_closure.as_ref().unchecked_ref(),
        )
        .expect("set get trap");
        Reflect::set(
            &handler,
            &"set".into(),
            set_closure.as_ref().unchecked_ref(),
        )
        .expect("set set trap");

        // Pin the two closures in the per-scope side-table. The
        // handler `Object` holds their JS function pointers; we
        // hold the Rust `Closure` wrappers so the `Box<dyn Fn>`
        // they own is dropped when `Scope::remove` runs. Previously
        // a `.forget()` call leaked both boxes for the life of the
        // process.
        PROXY_CLOSURES.with(|m| {
            m.borrow_mut().entry(scope_id).or_default().extend([
                Box::new(get_closure) as Box<dyn Any>,
                Box::new(set_closure) as Box<dyn Any>,
            ]);
        });

        Proxy::new(&target, &handler).into()
    }

    /// Invoke a handler by name. Mutates Rust state directly, then sweep-
    /// triggers every key on this scope so effects re-evaluate.
    pub fn invoke(&self, key: &str, args: &Array) -> JsValue {
        let prev = CURRENT_SCOPE_ID.with(|c| c.replace(Some(self.id)));
        #[cfg(feature = "devtools")]
        let start = crate::devtools::ring::now_ms_for_scope();
        let out = crate::model_runtime::with_scope_write(
            self.id,
            crate::model_runtime::WriteOrigin::LocalHandler,
            || self.state.borrow_mut().invoke(key, args),
        );
        CURRENT_SCOPE_ID.with(|c| c.set(prev));
        // RFC 054 phase A — handler may have mutated arbitrary
        // fields directly through `&mut self`; without targeted
        // hints we have to drop the whole cache so the next
        // proxy reads pick up the fresh state. Targeted ops
        // (`patch_list_at`) keep the cache valid.
        invalidate_field_cache(self.id);
        trigger_scope(self.id);
        // Devtools hook — fired after trigger_scope so any effect
        // runs scheduled by this handler are visible on the timeline
        // with a seq > this handler's.
        #[cfg(feature = "devtools")]
        {
            let dur = std::time::Duration::from_micros(
                ((crate::devtools::ring::now_ms_for_scope() - start).max(0.0) * 1000.0) as u64,
            );
            crate::devtools::hooks::fire_handler_invoke(self.id, key, args, dur);
        }
        out
    }
}

/// Drop every cached field `JsValue` for `scope_id`. Called from
/// `Handle::update` (which doesn't know which fields the closure
/// touched), and from `Scope::invoke`. Targeted op APIs
/// (`patch_list_at` and friends) deliberately do NOT call this —
/// they keep the cache valid by patching it in lockstep with
/// the Rust mutation, which is the whole point of the API.
pub fn invalidate_field_cache(scope_id: ScopeId) {
    let fresh = FRESH_FIELDS.with(|f| {
        let mut map = f.borrow_mut();
        map.remove(&scope_id).unwrap_or_default()
    });
    FIELD_CACHE.with(|c| {
        if let Some(m) = c.borrow_mut().get_mut(&scope_id) {
            if fresh.is_empty() {
                m.clear();
            } else {
                m.retain(|k, _| fresh.contains(k));
            }
        }
    });
}

/// Drop one field's cache slot. Call this from inside a
/// `&mut self` handler after a Rust-side mutation when you DON'T
/// want a full state re-serialise on the next read but also can't
/// patch the JS cache surgically (e.g. structural reshape, length
/// change). Reactivity does NOT fire here — call `trigger` (or
/// the caller's `Handle::update` boundary) for that.
pub fn invalidate_field(scope_id: ScopeId, field: &str) {
    FIELD_CACHE.with(|c| {
        if let Some(m) = c.borrow_mut().get_mut(&scope_id) {
            m.remove(field);
        }
    });
}

/// Patch one element of a `Vec<T>`-style field's cached
/// `JsValue` against the *current* scope (resolved via
/// `current_scope_id`). Designed to be called from inside a
/// `&mut self` handler after a Rust-side mutation:
///
/// ```ignore
/// pub fn touch_row(&mut self, idx: usize) {
///     self.rows[idx].label.push_str(" !!!");
///     pocopine::scope::patch_list_at_inline(
///         "rows", idx, &self.rows[idx],
///     );
/// }
/// ```
///
/// Reactivity fires for `field` on the current scope id. Unlike
/// `Handle::update`'s blanket `trigger_scope`, only effects
/// subscribed to `field` re-evaluate. The cached `JsValue` is
/// patched in place via `Reflect::set` so the live JS Array
/// readers (e.g. a `pp-for` reconcile) see the same Array
/// identity with one updated cell — Object identities for
/// every other row stay stable.
///
/// No-op (still fires reactivity) when:
///
/// - no scope is currently set (called outside a handler),
/// - the field has never been read by a JS effect (cache empty),
/// - the cached value isn't object-shaped (e.g. raw scalar field).
pub fn patch_list_at_inline<T: serde::Serialize>(field: &str, idx: usize, row: &T) {
    let Some(sid) = current_scope_id() else {
        return;
    };
    let cached = FIELD_CACHE.with(|c| c.borrow().get(&sid).and_then(|m| m.get(field).cloned()));
    if let Some(arr) = cached {
        if arr.is_object() {
            if let Ok(new_js) = serde_wasm_bindgen::to_value(row) {
                let _ = Reflect::set(&arr, &(idx as u32).into(), &new_js);
            }
        }
        // Keep the slot alive across the post-handler invalidate.
        FRESH_FIELDS.with(|f| {
            f.borrow_mut()
                .entry(sid)
                .or_default()
                .insert(field.to_string());
        });
    }
    crate::reactive::trigger(sid, field);
}

/// Patch several elements of a cached JS Array and trigger once.
/// This is the bulk sibling of [`patch_list_at_inline`] for handlers
/// such as "update every 10th row": it preserves object identity for
/// untouched rows without paying one reactive dispatch per changed row.
pub fn patch_list_indices_inline<T: serde::Serialize>(field: &str, patches: &[(usize, &T)]) {
    let Some(sid) = current_scope_id() else {
        return;
    };
    let cached = FIELD_CACHE.with(|c| c.borrow().get(&sid).and_then(|m| m.get(field).cloned()));
    if let Some(arr) = cached {
        if arr.is_object() {
            for (idx, row) in patches {
                if let Ok(new_js) = serde_wasm_bindgen::to_value(row) {
                    let _ = Reflect::set(&arr, &(*idx as u32).into(), &new_js);
                }
            }
        }
        keep_field_fresh(sid, field);
    }
    crate::reactive::trigger(sid, field);
}

fn keep_field_fresh(scope_id: ScopeId, field: &str) {
    FRESH_FIELDS.with(|f| {
        f.borrow_mut()
            .entry(scope_id)
            .or_default()
            .insert(field.to_string());
    });
}

/// Swap two indices inside a cached JS Array for a Vec-like field.
/// Call from inside a handler after swapping the Rust Vec. This keeps
/// existing row object identities intact, so keyed `pp-for` can avoid
/// re-stringifying unchanged rows on the follow-up reconcile.
pub fn swap_list_indices_inline(field: &str, a: usize, b: usize) {
    let Some(sid) = current_scope_id() else {
        return;
    };
    let cached = FIELD_CACHE.with(|c| c.borrow().get(&sid).and_then(|m| m.get(field).cloned()));
    if let Some(arr) = cached {
        if arr.is_object() {
            let a_key = JsValue::from_f64(a as f64);
            let b_key = JsValue::from_f64(b as f64);
            let a_val = Reflect::get(&arr, &a_key).unwrap_or(JsValue::UNDEFINED);
            let b_val = Reflect::get(&arr, &b_key).unwrap_or(JsValue::UNDEFINED);
            let _ = Reflect::set(&arr, &a_key, &b_val);
            let _ = Reflect::set(&arr, &b_key, &a_val);
        }
        keep_field_fresh(sid, field);
    }
    crate::reactive::trigger(sid, field);
}

/// Remove one element from a cached JS Array for a Vec-like field,
/// preserving object identity for every surviving row. Call from
/// inside a handler after removing the same index from the Rust Vec.
pub fn remove_list_at_inline(field: &str, idx: usize) {
    let Some(sid) = current_scope_id() else {
        return;
    };
    let cached = FIELD_CACHE.with(|c| c.borrow().get(&sid).and_then(|m| m.get(field).cloned()));
    if let Some(arr) = cached {
        if arr.is_object() {
            let array = js_sys::Array::from(&arr);
            let len = array.length();
            let idx = idx as u32;
            if idx < len {
                if let Ok(splice) = Reflect::get(&arr, &JsValue::from_str("splice")).and_then(|v| {
                    v.dyn_into::<Function>()
                        .map_err(|_| JsValue::from_str("Array.splice is not callable"))
                }) {
                    let _ = splice.call2(
                        &arr,
                        &JsValue::from_f64(idx as f64),
                        &JsValue::from_f64(1.0),
                    );
                }
            }
        }
        keep_field_fresh(sid, field);
    }
    crate::reactive::trigger(sid, field);
}

/// Append serialized rows into a cached JS Array for a Vec-like field.
/// Call from inside a handler after extending the Rust Vec. Existing
/// JS row objects remain in place; only the appended range is
/// serialized.
pub fn append_list_inline<T: serde::Serialize>(field: &str, start_idx: usize, rows: &[T]) {
    let Some(sid) = current_scope_id() else {
        return;
    };
    let cached = FIELD_CACHE.with(|c| c.borrow().get(&sid).and_then(|m| m.get(field).cloned()));
    if let Some(arr) = cached {
        if arr.is_object() {
            for (offset, row) in rows.iter().enumerate() {
                if let Ok(new_js) = serde_wasm_bindgen::to_value(row) {
                    let _ = Reflect::set(&arr, &((start_idx + offset) as u32).into(), &new_js);
                }
            }
        }
        keep_field_fresh(sid, field);
    }
    crate::reactive::trigger(sid, field);
}

/// Prepend serialized rows into a cached JS Array for a Vec-like
/// field while preserving existing JS row object identities in the
/// shifted tail. Call from inside a handler after prepending the
/// Rust Vec.
pub fn prepend_list_inline<T: serde::Serialize>(field: &str, rows: &[T]) {
    let Some(sid) = current_scope_id() else {
        return;
    };
    let cached = FIELD_CACHE.with(|c| c.borrow().get(&sid).and_then(|m| m.get(field).cloned()));
    if let Some(arr) = cached {
        if arr.is_object() {
            let array = js_sys::Array::from(&arr);
            let added = rows.len() as u32;
            let old_len = array.length();
            for idx in (0..old_len).rev() {
                let value = Reflect::get(&arr, &idx.into()).unwrap_or(JsValue::UNDEFINED);
                let _ = Reflect::set(&arr, &(idx + added).into(), &value);
            }
            for (idx, row) in rows.iter().enumerate() {
                if let Ok(new_js) = serde_wasm_bindgen::to_value(row) {
                    let _ = Reflect::set(&arr, &(idx as u32).into(), &new_js);
                }
            }
        }
        keep_field_fresh(sid, field);
    }
    crate::reactive::trigger(sid, field);
}

/// Replace the entire cached `JsValue` for `field` against the
/// current scope. Fires per-field reactivity. Use this when a
/// structural change (push / swap / clear / length change) means
/// individual cell patching won't work — re-serialise the whole
/// field once, stash it, and trigger. Sister of
/// [`patch_list_at_inline`] for ops without per-index granularity.
pub fn replace_field_inline<T: serde::Serialize>(field: &str, value: &T) {
    let Some(sid) = current_scope_id() else {
        return;
    };
    match serde_wasm_bindgen::to_value(value) {
        Ok(new_js) => {
            FIELD_CACHE.with(|c| {
                c.borrow_mut()
                    .entry(sid)
                    .or_default()
                    .insert(field.to_string(), new_js);
            });
            FRESH_FIELDS.with(|f| {
                f.borrow_mut()
                    .entry(sid)
                    .or_default()
                    .insert(field.to_string());
            });
        }
        Err(_) => invalidate_field(sid, field),
    }
    crate::reactive::trigger(sid, field);
}

/// The scope whose handler is currently on the stack. `None` outside of a
/// handler invocation. Handlers use this to hand their id to an async task:
///
/// ```ignore
/// pub fn init(&mut self) {
///     let id = pocopine::current_scope_id().unwrap();
///     self.loading = true;
///     wasm_bindgen_futures::spawn_local(async move {
///         let post = api::get_post(1).await;
///         if let Some(scope) = Scope::find(id) {
///             scope.state.borrow_mut().set("title", /* ... */);
///             pocopine::reactive::trigger_scope(id);
///         }
///     });
/// }
/// ```
pub fn current_scope_id() -> Option<ScopeId> {
    CURRENT_SCOPE_ID.with(|c| c.get())
}

/// Run `f` with `CURRENT_SCOPE_ID` set to `id`, restoring the prior
/// value on exit. Used by [`crate::handle::Handle::update`] so
/// `dispatch!` / `this::<T>()` called from inside an async update
/// closure still sees its own scope. Also used internally by
/// [`Scope::invoke`].
pub fn with_current_scope_id<R>(id: ScopeId, f: impl FnOnce() -> R) -> R {
    let prev = CURRENT_SCOPE_ID.with(|c| c.replace(Some(id)));
    let out = f();
    CURRENT_SCOPE_ID.with(|c| c.set(prev));
    out
}

/// Set the current element for the duration of a directive call. The caller
/// is responsible for clearing it on exit.
pub fn with_current_el<R>(el: &Element, f: impl FnOnce() -> R) -> R {
    let prev = CURRENT_EL.with(|c| c.replace(Some(el.clone())));
    let out = f();
    CURRENT_EL.with(|c| *c.borrow_mut() = prev);
    out
}

/// The element the current directive is running against, if any.
pub fn current_el() -> Option<Element> {
    CURRENT_EL.with(|c| c.borrow().clone())
}

// A compact helper for callers that need to pull a scope out of the registry
// by id without importing the inner types.
pub fn invoke_handler(scope_id: ScopeId, key: &str, args: &Array) -> JsValue {
    match Scope::find(scope_id) {
        Some(s) => s.invoke(key, args),
        None => JsValue::UNDEFINED,
    }
}

#[allow(dead_code)]
fn _type_check(_: &Function) {}