whisker-runtime 0.15.3

Host-independent Whisker runtime: reactivity, retained elements, layout, and frames.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
//! Type-erased renderer + thread-local current-renderer plumbing.
//!
//! The `render!` macro emits calls to the free functions in this
//! module ([`create_element`], [`set_attribute`], …). Each looks up
//! the currently-installed [`DynRenderer`] from a `thread_local!`
//! slot and forwards. This keeps the macro output renderer-agnostic
//! while still letting tests swap in a `MockRenderer`.
//!
//! Lifecycle:
//!
//! ```ignore
//! let renderer = Box::new(MyRenderer::new());
//! let prev = install_renderer(renderer);
//! // … all `view::create_element` etc. calls now go to MyRenderer
//! uninstall_renderer(prev);                 // restore previous (None)
//! ```
//!
//! In production the bridge driver installs the Host renderer
//! once at startup and keeps it for the life of the process.

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

use super::handle::Element;
use crate::element::ElementTag;
use crate::event::Dataset;
use crate::value::WhiskerValue;
use whisker_engine::whisker_layout::LayoutParticipation;
use whisker_protocol::{Accessibility, ElementSchema, LayoutGeometry};
use whisker_style::SpecifiedStyle;

/// One internal resolved-layout notification.
///
/// Participation is kept outside [`LayoutGeometry`] because geometry is part
/// of the Host protocol while this state is consumed only by Rust control
/// primitives.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LayoutObservation {
    /// Resolved box geometry for the retained node.
    pub geometry: LayoutGeometry,
    /// Occupied size including resolved margins, for virtual layout accounting.
    pub margin_box_size: whisker_engine::whisker_layout::LayoutSize,
    /// Whether the node belongs to the active layout tree.
    pub participation: LayoutParticipation,
}

/// Event-handler propagation type for the four supported handler kinds
/// (`bind` / `catch` / `capture-bind` /
/// `capture-catch`). The variant chosen when registering a listener is
/// what drives the Host event chain:
///
///   - **phase**: capture handlers fire on the way *down* (root →
///     target); bind/catch (bubble) handlers fire on the way *up*
///     (target → root).
///   - **stop**: a `catch` handler stops propagation after it fires;
///     a `bind` handler lets the event continue along the chain.
///
/// Discriminants are stable for renderer implementations that store the mode
/// as an integer.
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BindType {
    /// `bind` — bubble phase, does not stop propagation. The default
    /// (what plain `on_<event>` registers).
    #[default]
    Bind = 0,
    /// `catch` — bubble phase, stops propagation at this element.
    Catch = 1,
    /// `capture-bind` — capture phase, does not stop propagation.
    CaptureBind = 2,
    /// `capture-catch` — capture phase, stops propagation.
    CaptureCatch = 3,
}

/// One planned listener firing: the listener plus the event value it
/// should receive (its `currentTarget` already rewritten to that
/// listener's element).
pub type EventFiring = (Rc<dyn Fn(WhiskerValue) + 'static>, WhiskerValue);

/// The ordered firing plan produced by
/// [`DynRenderer::plan_event_dispatch`]. Separates *planning* (done
/// under the renderer borrow) from *firing* (done after the borrow is
/// released, since a handler may re-enter the renderer).
#[derive(Default)]
pub struct EventDispatchPlan {
    /// Whether any listener matched.
    pub consumed: bool,
    /// Listeners to invoke, in propagation order.
    pub firings: Vec<EventFiring>,
}

/// Object-safe renderer trait. The renderer owns whatever per-element
/// state it needs and answers in [`Element`] IDs.
///
/// All mutating methods take `&self`, not `&mut self`, so the renderer
/// survives re-entrancy: a Host event can fire *synchronously*
/// during a renderer operation (e.g. Host teardown inside
/// [`remove_child`](Self::remove_child) triggering a UIKit callback
/// that dispatches a custom event) and re-enter through
/// [`dispatch_event`]. With `&self` methods the thread-local
/// the thread-local renderer is held by a *shared* borrow in the private
/// `with_renderer` helper, so the nested call is granted instead of
/// panicking with "RefCell already borrowed". Renderers own their
/// mutable state behind per-field `RefCell`s and must scope each field
/// borrow so it does **not** span a re-entrant FFI call.
pub trait DynRenderer {
    fn create_element(&self, tag: ElementTag) -> Element;
    /// Tag-by-name dispatch for custom / xelement-style tags
    /// ("x-input", etc.) not in the built-in [`ElementTag`] enum.
    /// Returns a handle whose [`id`](Element::id) is `u32::MAX` when the
    /// tag is unknown to the element registry.
    fn create_element_by_name(&self, tag_name: &str) -> Element;
    /// Schema-carrying path used by `#[module_element]`. Renderers that
    /// negotiate schemas out of band can keep the default name-only behavior.
    fn create_element_by_schema(&self, schema: &ElementSchema) -> Element {
        self.create_element_by_name(&schema.name)
    }
    /// Registers a property-to-payload projection for a Custom leaf element.
    fn set_measurement_builder(
        &self,
        _handle: Element,
        _builder: crate::module_measurement::MeasurementPayloadBuilder,
    ) {
    }
    fn release_element(&self, handle: Element);

    fn set_attribute(&self, handle: Element, key: &str, value: &str);
    /// Typed attribute variants preserve value kind for module property
    /// handlers. Default implementations serialize to the string path for
    /// renderers that do not model type discrimination.
    fn set_attribute_int(&self, handle: Element, key: &str, value: i64) {
        self.set_attribute(handle, key, &value.to_string());
    }
    fn set_attribute_bool(&self, handle: Element, key: &str, value: bool) {
        self.set_attribute(handle, key, if value { "true" } else { "false" });
    }
    fn set_attribute_double(&self, handle: Element, key: &str, value: f64) {
        self.set_attribute(handle, key, &value.to_string());
    }
    /// Applies renderer-independent typed style and reports whether it was
    /// accepted. The default `false` is useful for lightweight test renderers;
    /// application-facing style APIs do not fall back to raw CSS.
    fn set_specified_style(&self, _handle: Element, _style: &SpecifiedStyle) -> bool {
        false
    }

    /// Stores the framework-level identifier used in event metadata.
    fn set_element_id(&self, _handle: Element, _id: String) {}

    /// Stores structured metadata surfaced on event targets.
    fn set_dataset(&self, _handle: Element, _dataset: Dataset) {}

    /// Replaces common accessibility semantics independently of element schema.
    fn set_accessibility(&self, _handle: Element, _accessibility: Accessibility) {}

    /// Sets the maximum number of lines for a plain-text element (`0` clears).
    fn set_text_max_lines(&self, _handle: Element, _max_lines: u32) {}

    /// Returns the current typed style when the renderer owns a retained Rust
    /// scene. Framework control flow uses this only for semantic validation;
    /// Hosts do not need to expose native presentation state.
    fn specified_style(&self, _handle: Element) -> Option<SpecifiedStyle> {
        None
    }

    /// Set an object-valued attribute (`{obj[i].0: obj[i].1}` of doubles)
    /// — e.g. `<list>` `item-snap` {factor, offset}. Default no-op.
    fn set_attribute_object(&self, _handle: Element, _key: &str, _obj: &[(String, f64)]) {}

    fn append_child(&self, parent: Element, child: Element);
    fn remove_child(&self, parent: Element, child: Element);

    /// Whether this renderer can insert a child before a reference
    /// sibling in one operation. When `false`, positioned insertion is
    /// simulated by append + rotate (see the private `insert_or_append`).
    /// Defaults to `false` so mock / host renderers opt in explicitly.
    fn supports_insert_before(&self) -> bool {
        false
    }

    /// Insert `child` into `parent` immediately before `reference`
    /// (`None` = append at the tail). An already attached child in the same
    /// parent is moved without detaching its subtree. Only called when
    /// [`supports_insert_before`](Self::supports_insert_before) is
    /// `true`; the default panics to catch a mis-wired caller.
    fn insert_child_before(&self, _parent: Element, _child: Element, _reference: Option<Element>) {
        unreachable!("insert_child_before called on a renderer without support");
    }

    /// Register `callback` for `event_name` on `handle`.
    ///
    /// The callback receives the event body Host hands the handler
    /// as a [`WhiskerValue`] tree (the same wire as module
    /// args/returns). A built-in builder's `on_<event>` method or a
    /// `#[whisker::module_element]` `on_<event>` prop wraps a
    /// typed-event / unit / raw-value closure into this single
    /// shape, deserializing the payload as needed. An event with no
    /// body fires the callback with [`WhiskerValue::Null`].
    fn set_event_listener(
        &self,
        handle: Element,
        event_name: &str,
        bind_type: BindType,
        callback: Box<dyn Fn(WhiskerValue) + 'static>,
    );

    /// Queues a one-shot callback after a future accepted frame includes this
    /// element in resolved, participating layout. The argument is the accepted
    /// revision, not a GPU presentation timestamp. Returns false when unsupported.
    fn on_next_frame_applied(&self, _handle: Element, _callback: Box<dyn FnOnce(u64)>) -> bool {
        false
    }

    /// Observes resolved Rust layout for framework control primitives.
    /// Ordinary renderers may ignore this; SurfaceRuntime reports after each
    /// successful Taffy pass without involving a Host event.
    fn observe_layout(
        &self,
        _handle: Element,
        _callback: Box<dyn Fn(LayoutObservation) + 'static>,
    ) {
    }

    /// Registers a callback that runs once after all per-element layout
    /// notifications for a completed layout pass. Renderers without retained
    /// layout notification batches may ignore it.
    fn observe_layout_batch_end(&self, _handle: Element, _callback: Box<dyn Fn() + 'static>) {}

    #[doc(hidden)]
    fn request_list_layout(&self) {}

    /// Plan how a reported event (`event_name` at `target_sign`,
    /// carrying `body`) propagates through Whisker's reconstructed
    /// chain — capture phase (root → target) then bubble phase
    /// (target → root), honoring each registered listener's
    /// [`BindType`] (catch stops bubbling; capture-catch stops
    /// everything).
    ///
    /// Returns the listeners to fire **in order**, each paired with the
    /// event value it should receive (its `currentTarget` set to that
    /// listener's element), plus whether the event was consumed.
    ///
    /// Crucially this only *plans* — it does not fire the listeners,
    /// because firing happens after the renderer borrow is released
    /// (a handler may mutate signals → effects → re-enter the
    /// renderer). [`dispatch_event`] does the firing. The default impl
    /// plans nothing (renderers without a Host event source); the
    /// Host bridge renderer overrides it.
    fn plan_event_dispatch(
        &self,
        _target_sign: i32,
        _event_name: &str,
        _body: &WhiskerValue,
    ) -> EventDispatchPlan {
        EventDispatchPlan::default()
    }

    #[doc(hidden)]
    fn enable_text_geometry(&self, _handle: Element) {}

    #[doc(hidden)]
    fn mark_inline_truncation(&self, _handle: Element) {}

    #[doc(hidden)]
    fn request_text_query(
        &self,
        _handle: Element,
        _query: crate::text_query::TextQuery,
    ) -> crate::text_query::TextQueryFuture {
        crate::text_query::TextQueryFuture::failed(crate::text_query::TextQueryError::NotBound)
    }

    #[doc(hidden)]
    fn set_text_selection(
        &self,
        _handle: Element,
        _range: Option<whisker_protocol::TextRange>,
    ) -> Result<(), crate::text_query::TextQueryError> {
        Err(crate::text_query::TextQueryError::NotBound)
    }

    /// Handles an element command through the retained semantic frame path.
    /// Renderers without command support leave the default `None`.
    fn invoke_element_command(
        &self,
        _handle: Element,
        _command: &str,
        _parameters: WhiskerValue,
    ) -> Option<Result<(), String>> {
        None
    }

    fn set_root(&self, root: Element);
    fn flush(&self);
}

thread_local! {
    static ELEMENT_CALLBACKS: RefCell<HashMap<Element, Vec<crate::lifetime::Cancellation>>> = RefCell::new(HashMap::new());
    /// The active renderer for this thread. `None` outside any mount.
    ///
    /// Wrapped in `RefCell<Option<Box<dyn>>>` rather than holding the
    /// renderer directly so [`install_renderer`] can swap one out for
    /// another atomically and tests can run with no renderer installed
    /// (where dispatch functions silently no-op + warn).
    static CURRENT_RENDERER: RefCell<Option<Box<dyn DynRenderer>>> = const { RefCell::new(None) };

    /// Whisker-side mirror of every parent → ordered-children
    /// relationship the runtime has emitted. Maintained by
    /// [`append_child`] / [`remove_child`].
    ///
    /// The mirror makes sibling/index queries deterministic without requiring
    /// a reverse query API from each Host.
    static CHILDREN_OF: RefCell<HashMap<Element, Vec<Element>>> =
        RefCell::new(HashMap::new());

    /// Reverse direction of [`CHILDREN_OF`]: child → its mirror
    /// parent. Maintained in lockstep with [`append_child`] /
    /// [`remove_child`] so [phantom hoisting](create_phantom_element)
    /// can walk *up* to the nearest non-phantom ancestor.
    ///
    /// Each child has at most one parent — every move is a detach +
    /// re-attach through us, never a DOM-style reparent. A missing
    /// entry means the child is currently detached.
    static PARENT_OF: RefCell<HashMap<Element, Element>> =
        RefCell::new(HashMap::new());

    /// IDs allocated by [`create_phantom_element`]. A phantom is an
    /// Element that lives in [`CHILDREN_OF`] / [`PARENT_OF`] but is
    /// **not** present in Host. It behaves like a *transparent
    /// container*: any real child mounted under a phantom is hoisted
    /// to the phantom's nearest non-phantom ancestor in Host; if
    /// there is no such ancestor yet (the phantom is still
    /// unattached), the real children stay in the mirror only and
    /// land in Host when the phantom subtree is finally attached.
    static PHANTOM_ELEMENTS: RefCell<HashSet<Element>> =
        RefCell::new(HashSet::new());

    /// Monotonic counter for phantom IDs, starting at [`PHANTOM_BASE`].
    static NEXT_PHANTOM_ID: Cell<u32> = const { Cell::new(PHANTOM_BASE) };
}

pub(crate) struct ViewRuntimeState {
    callbacks: HashMap<Element, Vec<crate::lifetime::Cancellation>>,
    children: HashMap<Element, Vec<Element>>,
    parents: HashMap<Element, Element>,
    phantoms: HashSet<Element>,
    next_phantom_id: u32,
}

impl ViewRuntimeState {
    pub(crate) fn new() -> Self {
        Self {
            callbacks: HashMap::new(),
            children: HashMap::new(),
            parents: HashMap::new(),
            phantoms: HashSet::new(),
            next_phantom_id: PHANTOM_BASE,
        }
    }
}

pub(crate) fn swap_runtime_state(state: &mut ViewRuntimeState) {
    ELEMENT_CALLBACKS.with_borrow_mut(|active| std::mem::swap(active, &mut state.callbacks));
    CHILDREN_OF.with_borrow_mut(|active| std::mem::swap(active, &mut state.children));
    PARENT_OF.with_borrow_mut(|active| std::mem::swap(active, &mut state.parents));
    PHANTOM_ELEMENTS.with_borrow_mut(|active| std::mem::swap(active, &mut state.phantoms));
    NEXT_PHANTOM_ID.with(|active| {
        let current = active.replace(state.next_phantom_id);
        state.next_phantom_id = current;
    });
}

/// Phantom IDs occupy the high half of `u32`; real IDs start at 0
/// from the bridge renderer's counter, so the two ranges stay
/// disjoint without coordination.
pub const PHANTOM_BASE: u32 = 1 << 31;

/// Install `r` as the current renderer for this thread, returning
/// whatever renderer was installed before (so the caller can restore
/// it later if needed).
///
/// Most production callers install exactly once and never restore.
/// Tests use the returned previous value to reset between cases.
pub fn install_renderer(r: Box<dyn DynRenderer>) -> Option<Box<dyn DynRenderer>> {
    CURRENT_RENDERER.with_borrow_mut(|slot| slot.replace(r))
}

/// Restore `prev` (typically what [`install_renderer`] handed back) as
/// the current renderer, dropping whatever is installed now. Passing
/// `None` leaves the slot empty, after which dispatch calls warn (in
/// debug) and no-op.
pub fn uninstall_renderer(prev: Option<Box<dyn DynRenderer>>) {
    CURRENT_RENDERER.with_borrow_mut(|slot| *slot = prev);
}

/// Run `f` with `r` temporarily installed as the current renderer.
/// Restores whatever was previously installed when `f` returns
/// (including the `None` state). Useful for tests + scoped
/// rendering.
pub fn with_installed_renderer<R>(r: Box<dyn DynRenderer>, f: impl FnOnce() -> R) -> R {
    let prev = install_renderer(r);
    struct Restore(Option<Option<Box<dyn DynRenderer>>>);
    impl Drop for Restore {
        fn drop(&mut self) {
            let _current = CURRENT_RENDERER.with_borrow_mut(|slot| slot.take());
            if let Some(previous) = self.0.take().flatten() {
                let _ = install_renderer(previous);
            }
        }
    }
    let _restore = Restore(Some(prev));
    f()
}

/// Crate-internal sigil for "no renderer installed" diagnostics —
/// distinguishes "renderer panicked" from "no renderer in this
/// scope" in tests.
pub fn current_renderer_id() -> Option<&'static str> {
    CURRENT_RENDERER.with_borrow(|slot| slot.as_ref().map(|_| "installed"))
}

/// Run `f` against the installed renderer under a **shared** borrow of
/// the [`CURRENT_RENDERER`] slot.
///
/// The borrow must stay shared: if `f` (e.g. a `remove_child` that
/// synchronously tears down native views) causes a native callback to
/// re-enter Whisker through [`dispatch_event`] → another
/// `with_renderer`, `RefCell` grants the nested shared borrow instead
/// of aborting with "already borrowed".
///
/// Slot *swapping* ([`install_renderer`] / [`uninstall_renderer`]) uses
/// `with_borrow_mut`; those are never called during dispatch, so they
/// can't conflict with an outstanding shared borrow.
fn with_renderer<R>(f: impl FnOnce(&dyn DynRenderer) -> R, default: R) -> R {
    CURRENT_RENDERER.with_borrow(|slot| match slot.as_ref() {
        Some(r) => f(r.as_ref()),
        None => {
            #[cfg(debug_assertions)]
            eprintln!("whisker-view: renderer call outside any installed renderer; ignored");
            default
        }
    })
}

// Free-function dispatch — what the `render!` macro and reactive
// effects call.

/// Allocate an element by tag name, registering it with the current
/// reactive owner so `Owner::dispose` releases it.
pub fn create_element_by_name(tag_name: &str) -> Element {
    let handle = with_renderer(|r| r.create_element_by_name(tag_name), Element(u32::MAX));
    if handle.id() != u32::MAX {
        crate::reactive::with_runtime(|rt| {
            if let Some(owner_id) = rt.current_owner()
                && let Some(owner) = rt.owners.get_mut(owner_id)
            {
                owner.elements.push(handle);
            }
        });
    }
    handle
}

/// Allocate a module element while making its Host-independent schema
/// available to the active retained renderer.
pub fn create_element_by_schema(schema: &ElementSchema) -> Element {
    let handle = with_renderer(
        |renderer| renderer.create_element_by_schema(schema),
        Element(u32::MAX),
    );
    if handle.id() != u32::MAX {
        crate::reactive::with_runtime(|runtime| {
            if let Some(owner_id) = runtime.current_owner()
                && let Some(owner) = runtime.owners.get_mut(owner_id)
            {
                owner.elements.push(handle);
            }
        });
    }
    handle
}

pub fn create_element(tag: ElementTag) -> Element {
    let handle = with_renderer(|r| r.create_element(tag), Element(u32::MAX));
    // Register with the current reactive owner so `Owner::dispose`
    // releases it — otherwise the renderer's element map and Host element
    // records accumulate across every `<Show>` flip,
    // `<For>` removal, and component remount.
    if handle.id() != u32::MAX {
        crate::reactive::with_runtime(|rt| {
            if let Some(owner_id) = rt.current_owner()
                && let Some(owner) = rt.owners.get_mut(owner_id)
            {
                owner.elements.push(handle);
            }
        });
    }
    handle
}

pub fn release_element(handle: Element) {
    let callbacks = ELEMENT_CALLBACKS.with_borrow_mut(|callbacks| callbacks.remove(&handle));
    for callback in callbacks.into_iter().flatten() {
        callback.cancel();
    }
    let parent = PARENT_OF.with_borrow_mut(|parents| parents.remove(&handle));
    let children = CHILDREN_OF.with_borrow_mut(|entries| {
        if let Some(parent) = parent.and_then(|parent| entries.get_mut(&parent)) {
            parent.retain(|child| *child != handle);
        }
        entries.remove(&handle).unwrap_or_default()
    });
    PARENT_OF.with_borrow_mut(|parents| {
        for child in children {
            if parents.get(&child) == Some(&handle) {
                parents.remove(&child);
            }
        }
    });
    if !PHANTOM_ELEMENTS.with_borrow_mut(|elements| elements.remove(&handle)) {
        with_renderer(|renderer| renderer.release_element(handle), ());
    }
}

/// Stores a framework-level element identifier.
pub fn set_element_id(handle: Element, id: String) {
    with_renderer(|renderer| renderer.set_element_id(handle, id), ())
}

/// Stores structured event metadata for an element.
pub fn set_dataset(handle: Element, dataset: Dataset) {
    with_renderer(|renderer| renderer.set_dataset(handle, dataset), ())
}

/// Replaces the common accessibility semantics for an element.
pub fn set_accessibility(handle: Element, accessibility: Accessibility) {
    with_renderer(
        |renderer| renderer.set_accessibility(handle, accessibility),
        (),
    )
}

/// Sets the maximum number of lines for a plain-text element.
pub fn set_text_max_lines(handle: Element, max_lines: u32) {
    with_renderer(
        |renderer| renderer.set_text_max_lines(handle, max_lines),
        (),
    )
}

/// Allocate a phantom element — an opaque positional marker the
/// runtime registers in the mirror but **never** forwards to Host.
/// Phantoms behave as *transparent containers*: any real descendant
/// attached under a phantom is hoisted to the phantom's nearest
/// non-phantom mirror ancestor in Host, preserving source order.
///
/// The phantom joins the current reactive owner's `elements` list like
/// a real element, so the same dispose-cascade reaches it;
/// [`release_element`] then clears its mirror state without touching
/// Host.
///
/// **Use case**: the wrapper-less `fragment` builtin and the
/// `For` / `Show` control-flow components — each allocates one
/// phantom as its "transparent grouping" element so its reactive
/// children appear in the mirror tree as a group while landing in Host
/// as flat siblings of the surrounding non-phantom container.
pub fn create_phantom_element() -> Element {
    let id = NEXT_PHANTOM_ID.with(|c| {
        let id = c.get();
        c.set(id.wrapping_add(1));
        id
    });
    let handle = Element::from_raw(id);
    PHANTOM_ELEMENTS.with_borrow_mut(|s| {
        s.insert(handle);
    });
    crate::reactive::with_runtime(|rt| {
        if let Some(owner_id) = rt.current_owner()
            && let Some(owner) = rt.owners.get_mut(owner_id)
        {
            owner.elements.push(handle);
        }
    });
    handle
}

/// Whether `handle` was allocated by [`create_phantom_element`]. The
/// dispatchers below call this on every tree mutation to decide
/// whether to skip the FFI step.
pub fn is_phantom(handle: Element) -> bool {
    if handle.id() < PHANTOM_BASE {
        return false;
    }
    PHANTOM_ELEMENTS.with_borrow(|s| s.contains(&handle))
}

/// Walk *up* the mirror from `start` (not including `start` itself)
/// until a non-phantom ancestor is found. Returns `None` if `start`
/// has no parent or the entire chain to the root is phantoms.
///
/// The hoisting path passes the *parent* of the just-mutated child:
/// what determines the effective Host parent is the surrounding tree,
/// not the child's own type.
fn nearest_real_ancestor(start: Element) -> Option<Element> {
    let mut current = start;
    loop {
        let parent = PARENT_OF.with_borrow(|m| m.get(&current).copied())?;
        if !is_phantom(parent) {
            return Some(parent);
        }
        current = parent;
    }
}

/// Count the number of *real* (non-phantom) elements reachable from
/// `root` through a strictly transparent path (phantom-only ancestors
/// between `root` and the reached element) that appear in DFS
/// pre-order before `target`. Used to compute the Host-side position
/// at which a newly-attached real element should land in
/// [`nearest_real_ancestor(target)`].
///
/// Excludes `root` itself; counts real descendants only. If `target`
/// is not under `root`, returns the total count (= "append at end").
fn count_real_descendants_before(root: Element, target: Element) -> usize {
    fn walk(node: Element, target: Element, count: &mut usize, found: &mut bool) {
        if *found {
            return;
        }
        let children = CHILDREN_OF.with_borrow(|m| m.get(&node).cloned().unwrap_or_default());
        for child in children {
            if *found {
                return;
            }
            if child == target {
                *found = true;
                return;
            }
            if is_phantom(child) {
                walk(child, target, count, found);
            } else {
                *count += 1;
            }
        }
    }
    let mut count = 0usize;
    let mut found = false;
    walk(root, target, &mut count, &mut found);
    count
}

/// DFS pre-order collect every real (non-phantom) descendant of
/// `root` reachable through a strictly transparent chain (phantom-
/// only ancestors). Used when a phantom subtree gets attached to a
/// real parent — we walk it and hand the real descendants to Host
/// in the right order.
fn collect_transparent_real_descendants(root: Element) -> Vec<Element> {
    let mut out = Vec::new();
    fn walk(node: Element, out: &mut Vec<Element>) {
        let children = CHILDREN_OF.with_borrow(|m| m.get(&node).cloned().unwrap_or_default());
        for child in children {
            if is_phantom(child) {
                walk(child, out);
            } else {
                out.push(child);
            }
        }
    }
    walk(root, &mut out);
    out
}

pub fn set_attribute(handle: Element, key: &str, value: &str) {
    if is_phantom(handle) {
        return; // phantoms carry no Host-side styling — silently no-op
    }
    with_renderer(|r| r.set_attribute(handle, key, value), ())
}

pub fn set_attribute_int(handle: Element, key: &str, value: i64) {
    if is_phantom(handle) {
        return;
    }
    with_renderer(|r| r.set_attribute_int(handle, key, value), ())
}

pub fn set_attribute_bool(handle: Element, key: &str, value: bool) {
    if is_phantom(handle) {
        return;
    }
    with_renderer(|r| r.set_attribute_bool(handle, key, value), ())
}

pub fn set_attribute_double(handle: Element, key: &str, value: f64) {
    if is_phantom(handle) {
        return;
    }
    with_renderer(|r| r.set_attribute_double(handle, key, value), ())
}

/// Attempts to apply renderer-independent typed style.
pub fn set_specified_style(handle: Element, style: &SpecifiedStyle) -> bool {
    if is_phantom(handle) {
        return true;
    }
    with_renderer(
        |renderer| renderer.set_specified_style(handle, style),
        false,
    )
}

#[doc(hidden)]
pub fn specified_style(handle: Element) -> Option<SpecifiedStyle> {
    if is_phantom(handle) {
        return None;
    }
    with_renderer(|renderer| renderer.specified_style(handle), None)
}

pub fn set_attribute_object(handle: Element, key: &str, obj: &[(String, f64)]) {
    if is_phantom(handle) {
        return;
    }
    with_renderer(|r| r.set_attribute_object(handle, key, obj), ())
}

/// Append `child` as the last mirror child of `parent`. The Host-
/// side effect depends on whether either end of the edge is a
/// phantom:
///
///   - both real → the bridge sees `append_child(parent, child)`
///     exactly as before.
///   - phantom child → no FFI for `child` itself (it never reaches
///     Host); if `child` brings a transparent subtree of real
///     descendants with it, they're replayed into the nearest real
///     ancestor at the position the parent's transparent layout
///     puts them.
///   - phantom parent → `child` is hoisted up the phantom chain to
///     the nearest real ancestor (if any); inserted there at the
///     position the mirror order puts it.
///   - phantom parent with no real ancestor → no Host call at all;
///     the subtree is queued in the mirror only. When the topmost
///     phantom is later attached to a real ancestor, the same
///     replay path handles the queued descendants in source order.
pub fn append_child(parent: Element, child: Element) {
    CHILDREN_OF.with_borrow_mut(|map| {
        map.entry(parent).or_default().push(child);
    });
    PARENT_OF.with_borrow_mut(|map| {
        map.insert(child, parent);
    });

    if !realize_hoisted_child(parent, child) {
        with_renderer(|r| r.append_child(parent, child), ());
    }

    // If `child` is the body root of a freshly-mounted `#[component]`,
    // its MountSite learns where it landed — hot-reload remount reads
    // that anchor to put the replacement back in the same place.
    crate::reactive::on_component_root_attached(parent, child);
}

/// Realize `child` — already placed in the mirror at its target
/// position — into the real Host tree, hoisting/replaying real
/// descendants when either end is a phantom. Reads `child`'s *current*
/// mirror position, so it serves both a tail append ([`append_child`])
/// and a positioned insert ([`insert_child_at`]) unchanged.
///
/// Returns `true` when a phantom was involved (and handled here);
/// `false` when both ends are real, leaving the caller to do the direct
/// real-to-real attach (`r.append_child` for a tail append, or a
/// positioned [`insert_or_append`] for a mid-list insert).
fn realize_hoisted_child(parent: Element, child: Element) -> bool {
    let parent_is_phantom = is_phantom(parent);
    let child_is_phantom = is_phantom(child);
    if parent_is_phantom {
        // No real ancestor yet (topmost phantom still detached) means
        // nothing to tell Host — the next attach replays this subtree.
        if let Some(real_anc) = nearest_real_ancestor(parent) {
            let to_attach: Vec<Element> = if child_is_phantom {
                collect_transparent_real_descendants(child)
            } else {
                vec![child]
            };
            // Back-to-front: each child's positioned-insert reference
            // is its next real sibling, so it must already be in the
            // Host tree. A forward pass references batch-mates that
            // aren't on-device yet and Host drops all but the last.
            for real in to_attach.into_iter().rev() {
                let pos = count_real_descendants_before(real_anc, real);
                insert_or_append(real_anc, real, pos);
            }
        }
        true
    } else if child_is_phantom {
        // Back-to-front for the same reason as the branch above.
        for real in collect_transparent_real_descendants(child)
            .into_iter()
            .rev()
        {
            let pos = count_real_descendants_before(parent, real);
            insert_or_append(parent, real, pos);
        }
        true
    } else {
        false
    }
}

/// Detach `child` from `parent` in the mirror. Host-side: any real
/// descendants of `child` (or `child` itself if it's real) are
/// removed from the nearest real ancestor; an already detached child is ignored.
pub fn remove_child(parent: Element, child: Element) {
    if PARENT_OF.with_borrow(|parents| parents.get(&child).copied()) != Some(parent) {
        return;
    }
    let parent_is_phantom = is_phantom(parent);
    let child_is_phantom = is_phantom(child);

    if parent_is_phantom {
        if let Some(real_anc) = nearest_real_ancestor(parent) {
            let to_detach: Vec<Element> = if child_is_phantom {
                collect_transparent_real_descendants(child)
            } else {
                vec![child]
            };
            for real in to_detach {
                with_renderer(|r| r.remove_child(real_anc, real), ());
            }
        }
    } else if child_is_phantom {
        for real in collect_transparent_real_descendants(child) {
            with_renderer(|r| r.remove_child(parent, real), ());
        }
    } else {
        with_renderer(|r| r.remove_child(parent, child), ());
    }

    CHILDREN_OF.with_borrow_mut(|map| {
        if let Some(children) = map.get_mut(&parent) {
            children.retain(|c| *c != child);
        }
    });
    PARENT_OF.with_borrow_mut(|map| {
        map.remove(&child);
    });
}

/// Internal helper: place `real_child` at `position` inside
/// `real_parent`'s Host child list.
///
/// The mirror already includes `real_child` at `position` in the
/// parent's real-only DFS pre-order, so the element that should sit
/// *after* it in Host is the next real descendant (`position + 1`), if
/// any — that's the reference node for a positioned insert.
///
/// A renderer reporting `supports_insert_before` gets one native call
/// with no sibling churn. The append + rotate fallback (test mocks, a
/// Host too old for the capi) detaches and re-appends every real
/// sibling that must sit after `real_child`, which re-anchors stateful
/// native siblings — a focused `<input>` loses focus.
fn insert_or_append(real_parent: Element, real_child: Element, position: usize) {
    let real_descendants = collect_transparent_real_descendants(real_parent);
    let reference = real_descendants.get(position + 1).copied();

    if with_renderer(|r| r.supports_insert_before(), false) {
        with_renderer(
            |r| r.insert_child_before(real_parent, real_child, reference),
            (),
        );
        return;
    }

    // `real_descendants` already includes `real_child` at `position`,
    // so the siblings to rotate past it are everything after it.
    with_renderer(|r| r.append_child(real_parent, real_child), ());
    if position + 1 < real_descendants.len() {
        let to_move: Vec<Element> = real_descendants[position + 1..].to_vec();
        for sib in &to_move {
            with_renderer(|r| r.remove_child(real_parent, *sib), ());
        }
        for sib in &to_move {
            with_renderer(|r| r.append_child(real_parent, *sib), ());
        }
    }
}

/// Places `child` at mirror `index` in `parent`'s child list (appends
/// when `index >= len`). An existing child is moved to the final index;
/// its parent and attachment remain unchanged. The following siblings are
/// **not touched** on
/// the Host side: `child` is realized with a positioned insert
/// (the private `insert_or_append` → native `insert_before` on Host), so a
/// stateful native sibling (a focused `<input>`, a scrolled list) keeps
/// its state.
pub fn insert_child_at(parent: Element, child: Element, index: usize) {
    let previous_parent = PARENT_OF.with_borrow(|map| map.get(&child).copied());
    let moving = previous_parent == Some(parent);
    if moving {
        let unchanged = CHILDREN_OF.with_borrow(|map| {
            map.get(&parent).is_some_and(|children| {
                children.iter().position(|entry| *entry == child)
                    == Some(index.min(children.len().saturating_sub(1)))
            })
        });
        if unchanged {
            return;
        }
        // Legacy renderers cannot move an attached child. Preserve their
        // detach/insert fallback, including transparent descendants.
        if !with_renderer(|r| r.supports_insert_before(), false) {
            remove_child(parent, child);
        } else {
            CHILDREN_OF.with_borrow_mut(|map| {
                if let Some(children) = map.get_mut(&parent) {
                    children.retain(|entry| *entry != child);
                }
            });
        }
    } else if let Some(previous) = previous_parent {
        remove_child(previous, child);
    }
    CHILDREN_OF.with_borrow_mut(|map| {
        let children = map.entry(parent).or_default();
        if index < children.len() {
            children.insert(index, child);
        } else {
            children.push(child);
        }
    });
    PARENT_OF.with_borrow_mut(|map| {
        map.insert(child, parent);
    });

    if !realize_hoisted_child(parent, child) {
        let pos = count_real_descendants_before(parent, child);
        insert_or_append(parent, child, pos);
    }

    if !moving {
        crate::reactive::on_component_root_attached(parent, child);
    }
}

/// Return the element handle that appears immediately before `child`
/// in `parent`'s child list, or `None` if `child` is the first child
/// or `parent` has no recorded children.
pub fn previous_sibling(parent: Element, child: Element) -> Option<Element> {
    CHILDREN_OF.with_borrow(|map| {
        let children = map.get(&parent)?;
        let idx = children.iter().position(|c| *c == child)?;
        if idx == 0 {
            None
        } else {
            Some(children[idx - 1])
        }
    })
}

/// Index of `child` in `parent`'s ordered child list, or `None` if
/// not tracked. Used by the wrapper-less remount path to re-insert
/// the new body root at the same position as the old one.
pub fn child_index(parent: Element, child: Element) -> Option<usize> {
    CHILDREN_OF.with_borrow(|map| {
        let children = map.get(&parent)?;
        children.iter().position(|c| *c == child)
    })
}

/// Snapshot of `parent`'s current ordered child list. Empty Vec if
/// the parent has no tracked children. Used by the batched
/// `remount_components_for` so it can compute the final desired
/// child order before any mutation churns the indices.
pub fn children_of(parent: Element) -> Vec<Element> {
    CHILDREN_OF.with_borrow(|map| map.get(&parent).cloned().unwrap_or_default())
}

/// Test/internal: clear the parent → children mirror. Call between
/// scenarios that share a thread (the production runtime never
/// needs this).
#[doc(hidden)]
pub fn __reset_children_mirror_for_tests() {
    CHILDREN_OF.with_borrow_mut(|map| map.clear());
}

fn element_callback<T: 'static>(handle: Element, callback: T) -> crate::lifetime::Scoped<T> {
    let scoped = crate::lifetime::Scoped::new(callback);
    ELEMENT_CALLBACKS.with_borrow_mut(|callbacks| {
        let callbacks = callbacks.entry(handle).or_default();
        callbacks.retain(crate::lifetime::Cancellation::is_live);
        callbacks.push(scoped.cancellation());
    });
    scoped
}

pub fn set_event_listener(
    handle: Element,
    event_name: &str,
    bind_type: BindType,
    callback: Box<dyn Fn(WhiskerValue) + 'static>,
) {
    if is_phantom(handle) {
        // Phantoms aren't in Host's event chain.
        drop(callback);
        return;
    }
    let scoped = element_callback(handle, callback);
    let callback = Box::new(move |value| {
        scoped.with(|f| f(value));
    });
    with_renderer(
        |r| r.set_event_listener(handle, event_name, bind_type, callback),
        (),
    )
}

/// Runs once after the Host accepts a future frame containing this element's
/// resolved layout. Disposal of the registering owner or element cancels it.
/// This does not wait for images or GPU presentation. A callback registered by
/// a callback waits for a later frame. Returns false for unsupported renderers.
#[doc(hidden)]
pub fn on_next_frame_applied(handle: Element, callback: impl FnOnce(u64) + 'static) -> bool {
    if is_phantom(handle) {
        return false;
    }
    let scoped = element_callback(handle, Some(callback));
    with_renderer(
        |renderer| {
            renderer.on_next_frame_applied(
                handle,
                Box::new(move |revision| {
                    scoped.with_mut(|callback| {
                        if let Some(callback) = callback.take() {
                            callback(revision);
                        }
                    });
                }),
            )
        },
        false,
    )
}

/// Registers an internal resolved-layout observer on one real element.
pub fn observe_layout(handle: Element, callback: Box<dyn Fn(LayoutObservation) + 'static>) {
    if is_phantom(handle) {
        drop(callback);
        return;
    }
    let scoped = element_callback(handle, callback);
    let callback = Box::new(move |value| {
        scoped.with(|f| f(value));
    });
    with_renderer(|renderer| renderer.observe_layout(handle, callback), ())
}

/// Registers an internal callback at the end of each completed resolved-layout
/// notification batch. The callback is owned by `handle`, so removing that
/// element also removes the registration.
pub fn observe_layout_batch_end(handle: Element, callback: Box<dyn Fn() + 'static>) {
    if is_phantom(handle) {
        drop(callback);
        return;
    }
    let scoped = element_callback(handle, callback);
    let callback = Box::new(move || {
        scoped.with(|f| f());
    });
    with_renderer(
        |renderer| renderer.observe_layout_batch_end(handle, callback),
        (),
    )
}

pub(crate) fn request_list_layout() {
    with_renderer(|renderer| renderer.request_list_layout(), ())
}

#[doc(hidden)]
pub fn enable_text_geometry(handle: Element) {
    with_renderer(|renderer| renderer.enable_text_geometry(handle), ())
}

#[doc(hidden)]
pub fn request_text_query(
    handle: Element,
    query: crate::text_query::TextQuery,
) -> crate::text_query::TextQueryFuture {
    with_renderer(
        |renderer| renderer.request_text_query(handle, query),
        crate::text_query::TextQueryFuture::failed(crate::text_query::TextQueryError::NotBound),
    )
}

#[doc(hidden)]
pub fn set_text_selection(
    handle: Element,
    range: Option<whisker_protocol::TextRange>,
) -> Result<(), crate::text_query::TextQueryError> {
    with_renderer(
        |renderer| renderer.set_text_selection(handle, range),
        Err(crate::text_query::TextQueryError::NotBound),
    )
}

/// Gives the installed renderer the first opportunity to handle an element
/// command. `None` asks the driver to use its legacy bridge path.
#[doc(hidden)]
pub fn try_invoke_element_command(
    handle: Element,
    command: &str,
    parameters: WhiskerValue,
) -> Option<Result<(), String>> {
    if is_phantom(handle) {
        return None;
    }
    with_renderer(
        |renderer| renderer.invoke_element_command(handle, command, parameters),
        None,
    )
}

/// Dispatch a reported event through the installed renderer's
/// reconstructed propagation chain. The driver's C entry point (the
/// bridge reporter forwards here) calls this. Returns whether the
/// event was consumed.
///
/// Planning runs under the renderer borrow; the listeners then fire
/// **after** the borrow is released, so a handler is free to mutate
/// signals / re-enter `view::*` without a re-entrant borrow panic.
pub fn dispatch_event(target_sign: i32, event_name: &str, body: WhiskerValue) -> bool {
    let plan = with_renderer(
        |r| r.plan_event_dispatch(target_sign, event_name, &body),
        EventDispatchPlan::default(),
    );
    for (listener, event) in plan.firings {
        listener(event);
    }
    plan.consumed
}

pub fn set_root(root: Element) {
    with_renderer(|renderer| renderer.set_root(root), ())
}

pub fn flush() {
    with_renderer(|r| r.flush(), ())
}

#[doc(hidden)]
pub fn mark_inline_truncation(handle: Element) {
    with_renderer(|renderer| renderer.mark_inline_truncation(handle), ());
}

/// Registers the payload function declared by `module_element`.
#[doc(hidden)]
pub fn set_measurement_builder(
    handle: Element,
    builder: crate::module_measurement::MeasurementPayloadBuilder,
) {
    if !is_phantom(handle) {
        with_renderer(
            |renderer| renderer.set_measurement_builder(handle, builder),
            (),
        );
    }
}