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
//! RFC-058 Phase 2 — compiled template plans.
//!
//! Macro-emitted static descriptor for an entire compiled
//! template's bindings, listeners, refs, and deferred-init
//! entries. The runtime fast-path in [`crate::mount::mount_component`]
//! consumes the plan when one is registered for a component
//! tag, calling the cleanup-safe install helpers from RFC-058
//! Phase 1 directly instead of running the per-attribute
//! directive scan.
//!
//! Companion to [`crate::directives::for_plan`]:
//!
//! * `for_plan` — RFC-054 — keyed `pp-for` row bodies; per-row
//!   instance plan; reused across every row mount.
//! * `templates_plan` (this) — RFC-058 — whole-template plan;
//!   one entry per `#[component]`; runs once per mount.
//!
//! The two share `BindingKind` / `StaticBinding` / `StaticListener`
//! types from [`crate::directives::for_plan`] so the install
//! helpers don't need to switch on which compiler emitted the
//! entry.
//!
//! v1 envelope per RFC-057 §6 (deferred to RFC-058 Phase 2):
//!
//! * Eligible: native HTML/SVG elements; `pp-text`, `pp-html`,
//!   `pp-show`, `pp-bind:<attr>` (DOM attrs, not child-component
//!   props), `pp-on:<event>` with the §6.1 supported modifier
//!   set, `pp-ref`.
//! * Not eligible (attribute-preserved, mount-owned): every
//!   directive on or under a non-HTML-native tag, every
//!   directive on `pp-for` / `pp-if` / `pp-teleport` / `<slot>`
//!   subtrees, `pp-model`, `pp-route`, listeners with
//!   unsupported modifiers.
//! * Stripped attributes are owned by the plan and **fail fast**
//!   on framework bugs; attribute-preserved fallbacks degrade
//!   silently to the runtime mount as today.

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

use wasm_bindgen::{JsCast, JsValue};
use web_sys::{console, Element, Node};

use crate::directives::for_plan::{
    BindingKind, StaticBinding, StaticChildMount, StaticForPlan, StaticIfPlan, StaticInterp,
    StaticListener, StaticNativeModel, StaticOpaqueDirective, StaticRef, StaticSlotOutlet,
    StaticTeleportPlan,
};
use crate::directives::interp::PlannedSegment;
use crate::directives::{self};
use crate::expr;
use crate::expr::StaticExpr;
use crate::reactive::ScopeId;
use crate::slot_fragment::SlotSet;

// ─── macro-emitted static shape ─────────────────────────────────

/// Static-lifetime template plan emitted by `#[component]`. The
/// macro emits one `&'static StaticTemplatePlan` per component
/// alongside the existing `register_template` call:
///
/// ```ignore
/// pub static __POC_TEMPLATE_PLAN_<COMPONENT>: StaticTemplatePlan =
///     StaticTemplatePlan {
///         bindings: &[ /* … */ ],
///         listeners: &[ /* … */ ],
///         refs: &[ /* … */ ],
///     };
/// ```
#[doc(hidden)]
pub struct StaticTemplatePlan {
    pub bindings: &'static [StaticBinding],
    pub listeners: &'static [StaticListener],
    pub refs: &'static [StaticRef],
    /// Child-component mount sites the macro discovered in this
    /// template (RFC-058 Phase 3). Each entry names a non-HTML5
    /// tag the runtime applier mounts via
    /// [`crate::mount::mount_child_component`] before the mount
    /// recurses. Empty for templates that contain no child
    /// components — the prior Phase 2 envelope.
    pub child_mounts: &'static [StaticChildMount],
    /// `pp-if` controller sites the classifier lifted out of
    /// the runtime mount's directive-dispatch path (RFC-058
    /// Phase 4.1b). The macro strips the `pp-if` attribute from
    /// the cleaned HTML — the applier installs the effect via
    /// [`crate::directives::if_::install`] against the
    /// `<template>` element resolved through `template_node_path`.
    /// Empty for templates with no `pp-if` site.
    pub if_plans: &'static [StaticIfPlan],
    /// `pp-for` controller sites (RFC-058 Phase 4.2). The macro
    /// strips `pp-for` / `pp-key` / `pp-stagger` from the
    /// cleaned HTML; the applier installs the effect via
    /// [`crate::directives::for_::install`] with the parsed
    /// item / items / key / stagger pre-resolved. The
    /// `data-pp-row-plan` attribute the §6.2 layering bakes
    /// in stays alongside, so the RFC-054 row-plan registry
    /// still resolves keyed lists. Empty for templates with no
    /// `pp-for` site.
    pub for_plans: &'static [StaticForPlan],
    /// `pp-teleport` controller sites without a co-occurring
    /// `pp-if` (RFC-058 Phase 4.3). The macro strips
    /// `pp-teleport` from the cleaned HTML; the applier resolves
    /// the target selector via
    /// [`crate::directives::teleport::install`]. Empty for
    /// templates with no plan-eligible `pp-teleport` site.
    pub teleport_plans: &'static [StaticTeleportPlan],
    /// `<slot>` outlet sites in a compiled component template
    /// (RFC-058 Phase 3.5e). These are materialised explicitly
    /// by the plan applier after all other path-resolved entries
    /// have installed, so the recursive mount no longer has to
    /// discover `<slot>` elements for planned templates.
    pub slot_outlets: &'static [StaticSlotOutlet],
    /// Runtime-only directives the macro lifts via the directive
    /// registry (RFC-058 Phase 3 hardening). One entry per
    /// allowlisted `pp-X` attribute (currently `pp-roving`,
    /// `pp-resize`, `pp-intersect`, `pp-anchor`, `pp-flip`); the
    /// applier dispatches them through
    /// [`crate::directives::lookup`] after slot materialisation
    /// so container directives that walk descendants find a fully
    /// settled DOM. Empty for plans whose elements use only the
    /// macro's structured directives.
    pub opaque_directives: &'static [StaticOpaqueDirective],
    /// `{{expr}}` text interpolation sites lifted out of the
    /// runtime mount (RFC-058 Phase 6.2). The macro pre-parses
    /// the segment list at compile time; the applier hands it
    /// to [`crate::directives::interp::install_planned`] to
    /// install effects per dynamic segment. Empty for templates
    /// with no interpolation.
    pub interps: &'static [StaticInterp],
    /// `pp-model[.modifier]="field"` sites on native input /
    /// textarea / select elements. Lifted out of the runtime
    /// mount so compiled-only apps wire two-way input bindings
    /// without the runtime mount. Component-target `pp-model`
    /// is on `StaticChildMount` instead.
    pub native_models: &'static [StaticNativeModel],
}

/// Captured interpolation target for RFC 062 specialized mount
/// bodies. The macro resolves every target first, then installs
/// them as a second pass to preserve the generic applier's text
/// index stability guarantee.
#[doc(hidden)]
pub struct StaticInterpTarget {
    pub parent: Element,
    pub text: web_sys::Text,
    pub segments: &'static [PlannedSegment],
}

// ─── registry ────────────────────────────────────────────────────

thread_local! {
    static TEMPLATE_PLANS: RefCell<HashMap<&'static str, &'static StaticTemplatePlan>> =
        RefCell::new(HashMap::new());

    /// Counter for fail-fast-but-recover events in release builds
    /// — incremented when a generated install helper fails
    /// (`node_path` doesn't resolve, `expr_src` doesn't parse).
    /// Tests assert this stays zero across mount/unmount cycles
    /// for templates the macro stripped attributes from. Public
    /// reader: [`plan_failure_count`].
    static PLAN_FAILURES: Cell<u32> = const { Cell::new(0) };

}

/// Register a template plan against a component tag. Called by
/// macro-emitted code immediately after `register_template` for
/// every `#[component]` whose template has at least one
/// plan-eligible directive (RFC-058 Phase 2 §6 envelope).
///
/// Idempotent — repeat calls overwrite the prior entry.
pub fn register_template_plan(tag: &'static str, plan: &'static StaticTemplatePlan) {
    TEMPLATE_PLANS.with(|registry| {
        registry.borrow_mut().insert(tag, plan);
    });
}

/// Look up a registered template plan by component tag. Returns
/// `None` for components the macro chose not to plan (e.g.
/// templates entirely inside non-HTML-native subtrees, or
/// pre-RFC-058 components compiled before the plan emitter
/// existed).
pub fn template_plan_for(tag: &str) -> Option<&'static StaticTemplatePlan> {
    if let Some(plan) = crate::registry::active_component_vtable(tag).and_then(|v| v.plan) {
        return Some(plan);
    }
    TEMPLATE_PLANS.with(|registry| registry.borrow().get(tag).copied())
}

/// Snapshot every registered component tag. Order is
/// implementation-defined (HashMap iteration); callers that
/// need stable ordering should sort. Intended for audit /
/// survey tooling and compiled root discovery.
pub fn registered_template_tags() -> Vec<String> {
    let mut tags: Vec<String> = crate::registry::active_component_names()
        .into_iter()
        .filter(|name| {
            crate::registry::active_component_vtable(name)
                .and_then(|v| v.plan)
                .is_some()
        })
        .map(str::to_string)
        .collect();
    let mut seen: HashSet<String> = tags.iter().cloned().collect();
    TEMPLATE_PLANS.with(|registry| {
        for tag in registry.borrow().keys() {
            if seen.insert((*tag).to_string()) {
                tags.push((*tag).to_string());
            }
        }
    });
    tags
}

/// Cumulative count of plan-install failures observed since
/// process start. Increments via [`record_plan_failure`] when a
/// generated install entry's `node_path` doesn't resolve to a
/// live DOM node, or its `expr_src` doesn't parse — both are
/// framework bugs (the macro stripped a directive whose plan
/// entry can't deliver). Tests can assert this stays zero
/// across mount/unmount cycles for compiled components.
pub fn plan_failure_count() -> u32 {
    PLAN_FAILURES.with(|c| c.get())
}

/// Reset the plan-failure counter. Tests call this between
/// cases so a prior test's failure doesn't leak into the next
/// case's assertion. Production code should never call this.
#[doc(hidden)]
pub fn reset_plan_failure_count() {
    PLAN_FAILURES.with(|c| c.set(0));
}

/// Record one plan-install failure. Called from generated mount
/// helpers when an install entry can't deliver. In debug builds
/// this also panics with a message naming the template + entry;
/// release builds log to `console.error` and continue (the
/// surrounding mount keeps going so a single misclassification
/// doesn't take down the page).
#[doc(hidden)]
pub fn record_plan_failure() {
    PLAN_FAILURES.with(|c| c.set(c.get().saturating_add(1)));
}

/// RFC 062 Phase 2 helper used by macro-specialized mount
/// bodies. It preserves the generic applier's ref semantics
/// after the macro has resolved the target element directly.
#[doc(hidden)]
pub fn install_static_ref(
    el: &Element,
    scope_id: ScopeId,
    entry: &'static StaticRef,
    _template_name: &str,
) {
    crate::refs::register(scope_id, entry.name, el);
}

/// RFC 062 Phase 2 helper used by macro-specialized mount
/// bodies. Parsing and fail-fast behaviour intentionally match
/// the generic applier.
#[doc(hidden)]
pub fn install_static_binding(
    el: &Element,
    proxy: &JsValue,
    entry: &'static StaticBinding,
    template_name: &str,
) {
    let Some(evaluator) = static_evaluator(entry.compiled, entry.expr_src) else {
        fail(
            "binding-parse",
            template_name,
            entry.node_path,
            Some(entry.expr_src),
        );
        return;
    };
    match entry.kind {
        BindingKind::Text => directives::text::install_eval(el, proxy, evaluator),
        BindingKind::Html => directives::html::install_eval(el, proxy, evaluator),
        BindingKind::Show => directives::show::install_eval(el, proxy, evaluator),
        BindingKind::Bind { arg } => directives::bind::install_eval(el, proxy, arg, evaluator),
        BindingKind::Class => fail(
            "binding-kind",
            template_name,
            entry.node_path,
            Some(entry.expr_src),
        ),
    }
}

/// RFC 062 Phase 2 helper used by macro-specialized mount
/// bodies. Parsing and legacy-call backfill stay shared with
/// the generic applier.
#[doc(hidden)]
pub fn install_static_listener(
    el: &Element,
    scope_id: ScopeId,
    proxy: &JsValue,
    entry: &'static StaticListener,
    template_name: &str,
) {
    let ast = match expr::parse_cached(entry.expr_src) {
        Ok(a) => a,
        Err(_) => {
            fail(
                "listener-parse",
                template_name,
                entry.node_path,
                Some(entry.expr_src),
            );
            return;
        }
    };
    directives::on::install(
        el,
        scope_id,
        proxy,
        entry.event,
        entry.modifiers,
        Rc::new(directives::on::backfill_legacy_call(ast)),
    );
}

/// RFC 062 Phase 2 helper used by macro-specialized mount
/// bodies for child-component hosts.
#[doc(hidden)]
pub fn install_static_child_mount(
    el: &Element,
    scope_id: ScopeId,
    proxy: &JsValue,
    entry: &'static StaticChildMount,
    template_name: &str,
) {
    if entry.slots.is_empty() {
        crate::mount::mount_child_component(el, entry.tag);
    } else {
        let mut set = SlotSet::new();
        for s in entry.slots {
            set = match s.scoped_let {
                Some(let_ident) => set.scoped(s.name, s.fragment, let_ident),
                None => set.named(s.name, s.fragment),
            };
        }
        crate::mount::mount_child_component_with_slots(el, entry.tag, set, scope_id, proxy);
    }
    install_child_host_directives(el, scope_id, proxy, entry, template_name);
}

/// RFC 062 Phase 2 helper used by macro-specialized mount
/// bodies for `pp-for` controller templates.
#[doc(hidden)]
pub fn install_static_for_plan(
    el: &Element,
    scope_id: ScopeId,
    proxy: &JsValue,
    entry: &'static StaticForPlan,
    template_name: &str,
) {
    let template = match directives::for_::ForTemplate::from_element(el.clone()) {
        Some(t) => t,
        None => {
            fail(
                "for-plan-template",
                template_name,
                entry.template_node_path,
                Some(entry.items_expr),
            );
            return;
        }
    };
    directives::for_::install(
        template,
        proxy.clone(),
        scope_id,
        entry.item_name,
        entry.items_expr,
        entry.key_expr,
        entry.stagger_ms,
        entry.body,
    );
}

/// RFC 062 Phase 2 helper used by macro-specialized mount
/// bodies for standalone `pp-teleport` controller templates.
#[doc(hidden)]
pub fn install_static_teleport_plan(
    el: &Element,
    entry: &'static StaticTeleportPlan,
    template_name: &str,
) {
    let template = match el.clone().dyn_into::<web_sys::HtmlTemplateElement>() {
        Ok(t) => t,
        Err(_) => {
            fail(
                "teleport-plan-template",
                template_name,
                entry.template_node_path,
                Some(entry.selector),
            );
            return;
        }
    };
    directives::teleport::install(template, entry.selector, entry.body);
}

/// RFC 062 Phase 2 helper used by macro-specialized mount
/// bodies for `pp-if` controller templates.
#[doc(hidden)]
pub fn install_static_if_plan(
    el: &Element,
    proxy: &JsValue,
    entry: &'static StaticIfPlan,
    template_name: &str,
) {
    let template = match el.clone().dyn_into::<web_sys::HtmlTemplateElement>() {
        Ok(t) => t,
        Err(_) => {
            fail(
                "if-plan-template",
                template_name,
                entry.template_node_path,
                Some(entry.expr_src),
            );
            return;
        }
    };
    let Some(evaluator) = static_evaluator(entry.compiled, entry.expr_src) else {
        fail(
            "if-plan-parse",
            template_name,
            entry.template_node_path,
            Some(entry.expr_src),
        );
        return;
    };
    directives::if_::install_eval(
        template,
        proxy.clone(),
        evaluator,
        entry.body,
        entry.teleport_selector,
    );
}

/// RFC 062 Phase 3 helper used by macro-specialized mount
/// bodies to snapshot `<slot>` outlets before later
/// materialisation mutates element-child positions.
#[doc(hidden)]
pub fn capture_static_slot_outlet(
    el: &Element,
    entry: &'static StaticSlotOutlet,
    template_name: &str,
) -> Option<Element> {
    if el.local_name() != "slot" {
        fail(
            "slot-outlet-tag",
            template_name,
            entry.node_path,
            Some(entry.name),
        );
        return None;
    }
    Some(el.clone())
}

/// RFC 062 Phase 3 helper used by macro-specialized mount
/// bodies after every path-based entry has resolved.
#[doc(hidden)]
pub fn materialize_static_slot_outlet(el: &Element) {
    crate::mount::materialize_compiled_slot_outlet(el);
}

/// RFC 062 Phase 3 helper used by macro-specialized mount
/// bodies for allowlisted runtime-only DOM directives.
#[doc(hidden)]
pub fn install_static_opaque_directive(
    el: &Element,
    scope_id: ScopeId,
    proxy: &JsValue,
    entry: &'static StaticOpaqueDirective,
    template_name: &str,
) {
    if !dispatch_opaque(
        entry.name,
        el,
        entry.arg,
        entry.modifiers,
        entry.value,
        scope_id,
        proxy,
    ) {
        fail(
            "opaque-directive-lookup",
            template_name,
            entry.node_path,
            Some(entry.name),
        );
    }
}

/// RFC 062 Phase 3 helper used by macro-specialized mount
/// bodies to snapshot interpolation text nodes before any
/// planned target mutates sibling text-node indexes.
#[doc(hidden)]
pub fn capture_static_interp_target(
    el: &Element,
    entry: &'static StaticInterp,
    _template_name: &str,
) -> Option<StaticInterpTarget> {
    let target = directives::interp::resolve_text_target(el, entry.text_index as usize)?;
    Some(StaticInterpTarget {
        parent: el.clone(),
        text: target,
        segments: entry.segments,
    })
}

/// RFC 062 Phase 3 helper used by macro-specialized mount
/// bodies after every interpolation target has been captured.
#[doc(hidden)]
pub fn install_static_interp_target(target: &StaticInterpTarget, proxy: &JsValue) {
    directives::interp::install_planned_target(
        &target.parent,
        proxy,
        &target.text,
        target.segments,
    );
}

/// RFC 062 Phase 3 helper used by macro-specialized mount
/// bodies for native `pp-model`.
#[doc(hidden)]
pub fn install_static_native_model(
    el: &Element,
    proxy: &JsValue,
    entry: &'static StaticNativeModel,
) {
    directives::model::install_native(
        el,
        proxy,
        entry.expr_src.to_string(),
        entry.number,
        entry.lazy,
    );
}

/// Dispatch an opaque directive lift to its typed install entry.
/// Returns `false` when `name` doesn't match a known opaque
/// directive — caller treats that as a fail-fast event.
fn dispatch_opaque(
    name: &str,
    el: &Element,
    arg: Option<&str>,
    modifiers: &'static [&'static str],
    value: &str,
    scope_id: ScopeId,
    proxy: &JsValue,
) -> bool {
    match name {
        "resize" => directives::resize::install_opaque(el, arg, modifiers, value, scope_id, proxy),
        "intersect" => {
            directives::intersect::install_opaque(el, arg, modifiers, value, scope_id, proxy)
        }
        "anchor" => directives::anchor::install_opaque(el, arg, modifiers, value, scope_id, proxy),
        "roving" => directives::roving::install_opaque(el, arg, modifiers, value, scope_id, proxy),
        "flip" => directives::flip::install_opaque(el, arg, modifiers, value, scope_id, proxy),
        _ => return false,
    }
    true
}

/// Apply the root-owned part of a template plan to the user
/// element hoisted by `pp-as`.
///
/// In `pp-as` mode the user element is already the slot content,
/// so the normal plan applier must not materialise `<slot>` outlets
/// or descend into template children. Root-level refs, bindings,
/// listeners, and deferred inits still belong to the component
/// template and should bind against the hoisted element in the
/// component scope.
#[doc(hidden)]
pub fn apply_static_pp_as_plan(
    root: &Element,
    scope_id: ScopeId,
    proxy: &JsValue,
    plan: &'static StaticTemplatePlan,
    template_name: &str,
) {
    for r in plan.refs.iter().filter(|r| r.node_path.is_empty()) {
        crate::refs::register(scope_id, r.name, root);
    }
    for b in plan.bindings.iter().filter(|b| b.node_path.is_empty()) {
        let Some(evaluator) = static_evaluator(b.compiled, b.expr_src) else {
            fail(
                "pp-as-binding-parse",
                template_name,
                b.node_path,
                Some(b.expr_src),
            );
            continue;
        };
        match b.kind {
            BindingKind::Text => directives::text::install_eval(root, proxy, evaluator),
            BindingKind::Html => directives::html::install_eval(root, proxy, evaluator),
            BindingKind::Show => directives::show::install_eval(root, proxy, evaluator),
            BindingKind::Bind { arg } => {
                directives::bind::install_eval(root, proxy, arg, evaluator)
            }
            BindingKind::Class => {
                fail(
                    "pp-as-binding-kind",
                    template_name,
                    b.node_path,
                    Some(b.expr_src),
                );
            }
        }
    }
    for l in plan.listeners.iter().filter(|l| l.node_path.is_empty()) {
        let ast = match expr::parse_cached(l.expr_src) {
            Ok(a) => a,
            Err(_) => {
                fail(
                    "pp-as-listener-parse",
                    template_name,
                    l.node_path,
                    Some(l.expr_src),
                );
                continue;
            }
        };
        directives::on::install(
            root,
            scope_id,
            proxy,
            l.event,
            l.modifiers,
            Rc::new(directives::on::backfill_legacy_call(ast)),
        );
    }
    for d in plan
        .opaque_directives
        .iter()
        .filter(|d| d.node_path.is_empty())
    {
        if !dispatch_opaque(d.name, root, d.arg, d.modifiers, d.value, scope_id, proxy) {
            fail(
                "opaque-directive-lookup",
                template_name,
                d.node_path,
                Some(d.name),
            );
        }
    }
}

fn install_child_host_directives(
    el: &Element,
    scope_id: ScopeId,
    proxy: &JsValue,
    child: &StaticChildMount,
    template_name: &str,
) {
    for b in child.bindings {
        let Some(evaluator) = static_evaluator(b.compiled, b.expr_src) else {
            fail(
                "child-host-binding-parse",
                template_name,
                child.node_path,
                Some(b.expr_src),
            );
            continue;
        };
        directives::bind::install_eval(el, proxy, b.arg, evaluator);
    }
    for l in child.listeners {
        let ast = match expr::parse_cached(l.expr_src) {
            Ok(a) => a,
            Err(_) => {
                fail(
                    "child-host-listener-parse",
                    template_name,
                    child.node_path,
                    Some(l.expr_src),
                );
                continue;
            }
        };
        directives::on::install(
            el,
            scope_id,
            proxy,
            l.event,
            l.modifiers,
            Rc::new(directives::on::backfill_legacy_call(ast)),
        );
    }
    for m in child.models {
        let _ = scope_id;
        directives::model::install_compiled(el, proxy, m.arg, m.modifiers, m.expr_src);
    }
}

/// RFC-058 Phase 4.1d / RFC 064 §5.1 — `pp-if` body fragment
/// runtime helper.
///
/// Parses `html` (the macro-cleaned body markup) into a fresh
/// namespace-aware fragment, extracts the single root element,
/// scope-binds it, stamps `CTX_PARENT_KEY`, then hands the
/// install pass off to `install_plan` — the macro-emitted
/// per-fragment closure that has the plan body unrolled inline.
/// Returns the root element ready for the `if_::install` caller
/// to pin its borrowed scope on + insert into the live DOM.
///
/// `None` return signals the body HTML didn't parse to a
/// single root element — same shape as the legacy
/// `clone_template_body` miss; the caller surfaces a console
/// error and bails the mount.
///
/// The closure boundary eliminates generic runtime plan
/// iteration for lifted body fragments (RFC 064 §5.1 Phase 1).
/// The closure receives the prepared body root with
/// `bind_borrowed_scope_to` + `CTX_PARENT_KEY` already stamped.
pub fn stamp_if_body_with(
    html: &str,
    scope_id: ScopeId,
    proxy: &JsValue,
    ctx_parent_id: ScopeId,
    install_plan: impl FnOnce(&Element, ScopeId, &JsValue),
) -> Option<Element> {
    let doc = web_sys::window().and_then(|w| w.document())?;
    let (root, content_parent) = parse_body_fragment_root(&doc, html)?;
    crate::mount::bind_borrowed_scope_to(&root, scope_id, proxy);
    let ctx_key = JsValue::from_str(crate::mount::CTX_PARENT_KEY);
    let ctx_val = JsValue::from_f64(ctx_parent_id.0 as f64);
    let _ = js_sys::Reflect::set(root.as_ref(), &ctx_key, &ctx_val);
    install_plan(&root, scope_id, proxy);
    if root.parent_node().is_some() {
        return Some(root);
    }
    // Slot-transparent recovery (see `stamp_if_body` doc).
    let kids = content_parent.child_nodes();
    for i in 0..kids.length() {
        if let Some(n) = kids.item(i) {
            if let Ok(el) = n.dyn_into::<Element>() {
                return Some(el);
            }
        }
    }
    None
}

const SVG_NS: &str = "http://www.w3.org/2000/svg";

fn parse_body_fragment_root(doc: &web_sys::Document, html: &str) -> Option<(Element, Node)> {
    if first_fragment_tag(html).is_some_and(is_svg_fragment_root_tag) {
        let wrapper = doc.create_element_ns(Some(SVG_NS), "svg").ok()?;
        wrapper.set_inner_html(html);
        let root = first_element_child(wrapper.as_ref())?;
        return Some((root, wrapper.into()));
    }

    let template_el = doc.create_element("template").ok()?;
    template_el.set_inner_html(html);
    let template_el = template_el
        .dyn_into::<web_sys::HtmlTemplateElement>()
        .ok()?;
    let content = template_el.content();
    let root = first_element_child(content.as_ref())?;
    Some((root, content.into()))
}

fn first_element_child(parent: &Node) -> Option<Element> {
    let kids = parent.child_nodes();
    for i in 0..kids.length() {
        if let Some(n) = kids.item(i) {
            if let Ok(el) = n.dyn_into::<Element>() {
                return Some(el);
            }
        }
    }
    None
}

fn first_fragment_tag(html: &str) -> Option<&str> {
    let rest = html.trim_start().strip_prefix('<')?;
    if rest.starts_with('!') || rest.starts_with('?') || rest.starts_with('/') {
        return None;
    }
    let end = rest
        .find(|c: char| c.is_ascii_whitespace() || c == '>' || c == '/')
        .unwrap_or(rest.len());
    let tag = &rest[..end];
    (!tag.is_empty()).then_some(tag)
}

fn is_svg_fragment_root_tag(tag: &str) -> bool {
    matches!(
        tag.to_ascii_lowercase().as_str(),
        "animate"
            | "animatemotion"
            | "animatetransform"
            | "circle"
            | "clippath"
            | "defs"
            | "desc"
            | "ellipse"
            | "feblend"
            | "fecolormatrix"
            | "fecomponenttransfer"
            | "fecomposite"
            | "feconvolvematrix"
            | "fediffuselighting"
            | "fedisplacementmap"
            | "fedistantlight"
            | "fedropshadow"
            | "feflood"
            | "fefunca"
            | "fefuncb"
            | "fefuncg"
            | "fefuncr"
            | "fegaussianblur"
            | "feimage"
            | "femerge"
            | "femergenode"
            | "femorphology"
            | "feoffset"
            | "fepointlight"
            | "fespecularlighting"
            | "fespotlight"
            | "fetile"
            | "feturbulence"
            | "filter"
            | "foreignobject"
            | "g"
            | "image"
            | "line"
            | "lineargradient"
            | "marker"
            | "mask"
            | "metadata"
            | "mpath"
            | "path"
            | "pattern"
            | "polygon"
            | "polyline"
            | "radialgradient"
            | "rect"
            | "script"
            | "set"
            | "stop"
            | "style"
            | "svg"
            | "switch"
            | "symbol"
            | "text"
            | "textpath"
            | "title"
            | "tspan"
            | "use"
            | "view"
    )
}

type StaticEvaluator = Rc<dyn Fn(&JsValue) -> JsValue>;

fn static_evaluator(
    compiled: Option<&'static StaticExpr>,
    expr_src: &'static str,
) -> Option<StaticEvaluator> {
    if let Some(compiled) = compiled {
        return Some(Rc::new(move |scope| compiled.evaluate(scope)));
    }
    runtime_evaluator(expr_src)
}

#[cfg(feature = "runtime-expr-fallback")]
fn runtime_evaluator(expr_src: &'static str) -> Option<StaticEvaluator> {
    let ast = expr::parse_cached(expr_src).ok()?;
    Some(Rc::new(move |scope| expr::evaluate(&ast, scope)))
}

#[cfg(not(feature = "runtime-expr-fallback"))]
fn runtime_evaluator(_expr_src: &'static str) -> Option<StaticEvaluator> {
    None
}

fn fail(kind: &str, template_name: &str, node_path: &[u16], expr_src: Option<&str>) {
    record_plan_failure();
    let msg = match expr_src {
        Some(src) => format!(
            "pocopine: template plan {kind} install failed for `{template_name}` at \
             node_path {node_path:?} (expr: {src:?}). This is a framework bug — the \
             macro stripped a directive whose plan entry cannot deliver."
        ),
        None => format!(
            "pocopine: template plan {kind} install failed for `{template_name}` at \
             node_path {node_path:?}. This is a framework bug — the macro stripped a \
             directive whose plan entry cannot deliver."
        ),
    };
    if cfg!(debug_assertions) {
        panic!("{msg}");
    }
    console::error_1(&JsValue::from_str(&msg));
}