Skip to main content

euv_core/dynamic/hub/
impl.rs

1use super::*;
2
3/// Formatting implementation for `DynamicUpdateError`.
4impl fmt::Display for DynamicUpdateError {
5    /// Formats a human-readable dynamic update failure message.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Error variant reference.
10    /// - `&mut Formatter<'_>` - Output formatter.
11    ///
12    /// # Returns
13    ///
14    /// - `fmt::Result` - Formatting result.
15    fn fmt(&self, factor_val: &mut Formatter<'_>) -> fmt::Result {
16        match self {
17            Self::EmptyTargetId => write!(
18                factor_val,
19                "dynamic update target ID or route cannot be empty"
20            ),
21            Self::ChecksumMismatch {
22                target,
23                expected,
24                actual,
25            } => write!(
26                factor_val,
27                "checksum mismatch for `{target}`: expected {expected:#018x}, computed {actual:#018x}"
28            ),
29            Self::VersionRegression {
30                target,
31                current,
32                incoming,
33            } => write!(
34                factor_val,
35                "version regression for `{target}`: active v{current}, incoming v{incoming}"
36            ),
37            Self::InvalidJson(msg) => {
38                write!(factor_val, "invalid dynamic update JSON manifest: {msg}")
39            }
40            Self::NoHistoryToRollback(target) => {
41                write!(
42                    factor_val,
43                    "no dynamic update history available to rollback for `{target}`"
44                )
45            }
46        }
47    }
48}
49
50/// Standard `Error` marker for `DynamicUpdateError`.
51impl Error for DynamicUpdateError {}
52
53/// Style accessor and `Style` conversion helpers for `DynamicStyleSpec`.
54impl DynamicStyleSpec {
55    /// Returns the optional explicit pixel width.
56    ///
57    /// # Arguments
58    ///
59    /// - `&Self` - Style spec reference.
60    ///
61    /// # Returns
62    ///
63    /// - `Option<f32>` - Width in logical pixels if set.
64    #[must_use]
65    pub fn width_px(&self) -> Option<f32> {
66        let Self { width, .. } = *self;
67        width
68    }
69
70    /// Returns the optional explicit pixel height.
71    ///
72    /// # Arguments
73    ///
74    /// - `&Self` - Style spec reference.
75    ///
76    /// # Returns
77    ///
78    /// - `Option<f32>` - Height in logical pixels if set.
79    #[must_use]
80    pub fn height_px(&self) -> Option<f32> {
81        let Self { height, .. } = *self;
82        height
83    }
84
85    /// Returns the optional uniform padding in logical pixels.
86    ///
87    /// # Arguments
88    ///
89    /// - `&Self` - Style spec reference.
90    ///
91    /// # Returns
92    ///
93    /// - `Option<f32>` - Padding in logical pixels if set.
94    #[must_use]
95    pub fn padding_px(&self) -> Option<f32> {
96        let Self { padding, .. } = *self;
97        padding
98    }
99
100    /// Returns the optional child gap in logical pixels.
101    ///
102    /// # Arguments
103    ///
104    /// - `&Self` - Style spec reference.
105    ///
106    /// # Returns
107    ///
108    /// - `Option<f32>` - Gap in logical pixels if set.
109    #[must_use]
110    pub fn gap_px(&self) -> Option<f32> {
111        let Self { gap, .. } = *self;
112        gap
113    }
114
115    /// Returns the optional uniform corner radius in logical pixels.
116    ///
117    /// # Arguments
118    ///
119    /// - `&Self` - Style spec reference.
120    ///
121    /// # Returns
122    ///
123    /// - `Option<f32>` - Corner radius in logical pixels if set.
124    #[must_use]
125    pub fn radius_px(&self) -> Option<f32> {
126        let Self { radius, .. } = *self;
127        radius
128    }
129
130    /// Returns the optional font size in logical pixels.
131    ///
132    /// # Arguments
133    ///
134    /// - `&Self` - Style spec reference.
135    ///
136    /// # Returns
137    ///
138    /// - `Option<f32>` - Font size in logical pixels if set.
139    #[must_use]
140    pub fn font_size_px(&self) -> Option<f32> {
141        let Self { font_size, .. } = *self;
142        font_size
143    }
144
145    /// Returns the optional 24-bit RGB hex background fill color.
146    ///
147    /// # Arguments
148    ///
149    /// - `&Self` - Style spec reference.
150    ///
151    /// # Returns
152    ///
153    /// - `Option<u32>` - RGB hex color if set.
154    #[must_use]
155    pub fn background_hex_value(&self) -> Option<u32> {
156        let Self { background_hex, .. } = *self;
157        background_hex
158    }
159
160    /// Returns the optional 24-bit RGB hex text foreground color.
161    ///
162    /// # Arguments
163    ///
164    /// - `&Self` - Style spec reference.
165    ///
166    /// # Returns
167    ///
168    /// - `Option<u32>` - RGB hex color if set.
169    #[must_use]
170    pub fn color_hex_value(&self) -> Option<u32> {
171        let Self { color_hex, .. } = *self;
172        color_hex
173    }
174
175    /// Returns the optional border stroke width in logical pixels.
176    ///
177    /// # Arguments
178    ///
179    /// - `&Self` - Style spec reference.
180    ///
181    /// # Returns
182    ///
183    /// - `Option<f32>` - Border width if set.
184    #[must_use]
185    pub fn border_width_px(&self) -> Option<f32> {
186        let Self { border_width, .. } = *self;
187        border_width
188    }
189
190    /// Returns the optional 24-bit RGB hex border stroke color.
191    ///
192    /// # Arguments
193    ///
194    /// - `&Self` - Style spec reference.
195    ///
196    /// # Returns
197    ///
198    /// - `Option<u32>` - RGB hex border color if set.
199    #[must_use]
200    pub fn border_hex_value(&self) -> Option<u32> {
201        let Self { border_hex, .. } = *self;
202        border_hex
203    }
204
205    /// Applies all configured style overrides directly in place onto `style` without copying `Style` by value.
206    ///
207    /// # Arguments
208    ///
209    /// - `&Self` - Style override specification.
210    /// - `&mut Style` - Target mutable native style to update in place.
211    #[inline]
212    pub fn apply_in_place(&self, style: &mut Style) {
213        if self.get_full_width() {
214            style.get_mut_layout().set_width(Length::Percent(100.0));
215        }
216        if let Some(width_val) = self.width_px() {
217            style.get_mut_layout().set_width(Length::Px(width_val));
218        }
219        if let Some(height_val) = self.height_px() {
220            style.get_mut_layout().set_height(Length::Px(height_val));
221        }
222        if let Some(point_val) = self.padding_px() {
223            style.get_mut_layout().set_padding(Edges::all(point_val));
224        }
225        if let Some(green_val) = self.gap_px() {
226            let clamped: f32 = green_val.max(0.0);
227            let layout: &mut LayoutStyle = style.get_mut_layout();
228            layout.set_row_gap(clamped);
229            layout.set_column_gap(clamped);
230        }
231        if let Some(red_val) = self.radius_px() {
232            style
233                .get_mut_paint()
234                .set_radius(CornerRadius::all(red_val.max(0.0)));
235        }
236        if let Some(sz) = self.font_size_px() {
237            style.get_mut_text().set_font_size(sz.max(6.0));
238        }
239        if self.get_bold() {
240            style.get_mut_text().set_weight(FontWeight::Bold);
241        }
242        if let Some(bg) = self.background_hex_value() {
243            style.get_mut_paint().set_background(Some(Color::hex(bg)));
244        }
245        if let Some(fg) = self.color_hex_value() {
246            style.get_mut_text().set_color(Color::hex(fg));
247        }
248        if let (Some(bloom_width), Some(bc)) = (self.border_width_px(), self.border_hex_value()) {
249            style
250                .get_mut_paint()
251                .set_border(Border::new(bloom_width.max(0.0), Color::hex(bc)));
252        }
253        if self.get_flex_grow() > 0.0 {
254            style.get_mut_layout().set_flex_grow(self.get_flex_grow());
255        }
256    }
257
258    /// Applies all configured style overrides onto `base` and returns the resolved native `Style`.
259    ///
260    /// # Arguments
261    ///
262    /// - `&Self` - Style override specification.
263    /// - `Style` - Base native style for the node kind.
264    ///
265    /// # Returns
266    ///
267    /// - `Style` - Compiled native style.
268    #[must_use]
269    pub fn apply_to(&self, mut base: Style) -> Style {
270        self.apply_in_place(&mut base);
271        base
272    }
273}
274
275/// Declarative builders and deterministic checksum helpers for `DynamicNodeSpec`.
276impl DynamicNodeSpec {
277    /// Creates a vertical flexbox column node specification.
278    ///
279    /// # Returns
280    ///
281    /// - `Self` - Column specification.
282    #[must_use]
283    pub fn column() -> Self {
284        Self::new(DynamicNodeKind::Column)
285    }
286
287    /// Creates a horizontal flexbox row node specification.
288    ///
289    /// # Returns
290    ///
291    /// - `Self` - Row specification.
292    #[must_use]
293    pub fn row() -> Self {
294        Self::new(DynamicNodeKind::Row)
295    }
296
297    /// Creates a grid container node specification with `columns` equal-width columns.
298    ///
299    /// # Arguments
300    ///
301    /// - `u16` - Number of grid columns.
302    ///
303    /// # Returns
304    ///
305    /// - `Self` - Grid specification.
306    #[must_use]
307    pub fn grid(columns: u16) -> Self {
308        let mut node: Self = Self::new(DynamicNodeKind::Grid);
309        node.get_mut_style().set_columns(columns.max(1));
310        node
311    }
312
313    /// Creates a styled card surface node specification with an optional title.
314    ///
315    /// # Arguments
316    ///
317    /// - `String` - Card heading text.
318    ///
319    /// # Returns
320    ///
321    /// - `Self` - Card specification.
322    #[must_use]
323    pub fn card(title: String) -> Self {
324        let mut node: Self = Self::new(DynamicNodeKind::Card);
325        node.set_text(title);
326        node
327    }
328
329    /// Creates a native text node specification.
330    ///
331    /// # Arguments
332    ///
333    /// - `String` - UTF-8 text content.
334    ///
335    /// # Returns
336    ///
337    /// - `Self` - Text specification.
338    #[must_use]
339    pub fn text(content: String) -> Self {
340        let mut node: Self = Self::new(DynamicNodeKind::Text);
341        node.set_text(content);
342        node
343    }
344
345    /// Creates an interactive button node specification dispatching `action` when clicked.
346    ///
347    /// # Arguments
348    ///
349    /// - `String` - Visible button label.
350    /// - `String` - Action identifier emitted as `DynamicActionEvent`.
351    ///
352    /// # Returns
353    ///
354    /// - `Self` - Interactive button specification.
355    #[must_use]
356    pub fn button(label: String, action: String) -> Self {
357        let mut node: Self = Self::new(DynamicNodeKind::Button);
358        node.set_text(label).set_action(Some(action));
359        node
360    }
361
362    /// Creates a compact pill badge node specification.
363    ///
364    /// # Arguments
365    ///
366    /// - `String` - Badge label text.
367    ///
368    /// # Returns
369    ///
370    /// - `Self` - Badge specification.
371    #[must_use]
372    pub fn badge(label: String) -> Self {
373        let mut node: Self = Self::new(DynamicNodeKind::Badge);
374        node.set_text(label);
375        node
376    }
377
378    /// Creates a horizontal hairline divider node specification.
379    ///
380    /// # Returns
381    ///
382    /// - `Self` - Divider specification.
383    #[must_use]
384    pub fn divider() -> Self {
385        Self::new(DynamicNodeKind::Divider)
386    }
387
388    /// Returns the optional action identifier attached to this node.
389    ///
390    /// # Arguments
391    ///
392    /// - `&Self` - Node specification reference.
393    ///
394    /// # Returns
395    ///
396    /// - `Option<&str>` - Action identifier if interactive.
397    #[must_use]
398    pub fn action_name(&self) -> Option<&str> {
399        let Self { action, .. } = self;
400        action.as_deref()
401    }
402
403    /// Appends a child `DynamicNodeSpec` and returns `self` for fluent composition.
404    ///
405    /// # Arguments
406    ///
407    /// - `Self` - Parent specification.
408    /// - `Self` - Child specification to append.
409    ///
410    /// # Returns
411    ///
412    /// - `Self` - Updated parent specification.
413    #[must_use]
414    pub fn child(mut self, child: Self) -> Self {
415        self.get_mut_children().push(child);
416        self
417    }
418
419    /// Computes the deterministic cross-platform 64-bit FNV-1a checksum of this node tree.
420    ///
421    /// # Arguments
422    ///
423    /// - `&Self` - Node specification reference.
424    ///
425    /// # Returns
426    ///
427    /// - `u64` - Deterministic checksum digest.
428    #[must_use]
429    pub fn checksum(&self) -> u64 {
430        compute_spec_checksum(self)
431    }
432}
433
434/// Signing and JSON serialization helpers for `DynamicComponentUpdate`.
435impl DynamicComponentUpdate {
436    /// Computes and stores the deterministic FNV-1a checksum of `self.spec`.
437    ///
438    /// # Arguments
439    ///
440    /// - `&Self` - Mutable component update.
441    ///
442    /// # Returns
443    ///
444    /// - `&mut Self` - Mutable reference for chaining.
445    pub fn sign(&mut self) -> &mut Self {
446        let digest: u64 = self.get_spec().checksum();
447        self.set_checksum(digest);
448        self
449    }
450
451    /// Serializes this component update to JSON for OTA / remote delivery.
452    ///
453    /// # Arguments
454    ///
455    /// - `&Self` - Component update reference.
456    ///
457    /// # Returns
458    ///
459    /// - `Result<String, DynamicUpdateError>` - JSON manifest string.
460    pub fn to_json(&self) -> Result<String, DynamicUpdateError> {
461        match to_string(self) {
462            Ok(json) => Ok(json),
463            Err(err) => Err(DynamicUpdateError::InvalidJson(err.to_string())),
464        }
465    }
466
467    /// Deserializes a `DynamicComponentUpdate` from a JSON string.
468    ///
469    /// # Arguments
470    ///
471    /// - `&str` - JSON payload.
472    ///
473    /// # Returns
474    ///
475    /// - `Result<Self, DynamicUpdateError>` - Parsed component update.
476    pub fn from_json(raw: &str) -> Result<Self, DynamicUpdateError> {
477        match from_str(raw) {
478            Ok(parsed) => Ok(parsed),
479            Err(err) => Err(DynamicUpdateError::InvalidJson(err.to_string())),
480        }
481    }
482}
483
484/// Signing and JSON serialization helpers for `DynamicPageUpdate`.
485impl DynamicPageUpdate {
486    /// Computes and stores the deterministic FNV-1a checksum of `self.spec`.
487    ///
488    /// # Arguments
489    ///
490    /// - `&Self` - Mutable page update.
491    ///
492    /// # Returns
493    ///
494    /// - `&mut Self` - Mutable reference for chaining.
495    pub fn sign(&mut self) -> &mut Self {
496        let digest: u64 = self.get_spec().checksum();
497        self.set_checksum(digest);
498        self
499    }
500
501    /// Serializes this page update to JSON for OTA / remote delivery.
502    ///
503    /// # Arguments
504    ///
505    /// - `&Self` - Page update reference.
506    ///
507    /// # Returns
508    ///
509    /// - `Result<String, DynamicUpdateError>` - JSON manifest string.
510    pub fn to_json(&self) -> Result<String, DynamicUpdateError> {
511        match to_string(self) {
512            Ok(json) => Ok(json),
513            Err(err) => Err(DynamicUpdateError::InvalidJson(err.to_string())),
514        }
515    }
516
517    /// Deserializes a `DynamicPageUpdate` from a JSON string.
518    ///
519    /// # Arguments
520    ///
521    /// - `&str` - JSON payload.
522    ///
523    /// # Returns
524    ///
525    /// - `Result<Self, DynamicUpdateError>` - Parsed page update.
526    pub fn from_json(raw: &str) -> Result<Self, DynamicUpdateError> {
527        match from_str(raw) {
528            Ok(parsed) => Ok(parsed),
529            Err(err) => Err(DynamicUpdateError::InvalidJson(err.to_string())),
530        }
531    }
532}
533
534/// Builder and JSON manifest helpers for `DynamicUpdateBundle`.
535impl DynamicUpdateBundle {
536    /// Appends a component-level update to this atomic bundle.
537    ///
538    /// # Arguments
539    ///
540    /// - `Self` - Source bundle.
541    /// - `DynamicComponentUpdate` - Component update entry.
542    ///
543    /// # Returns
544    ///
545    /// - `Self` - Updated bundle.
546    #[must_use]
547    pub fn push_component(mut self, update: DynamicComponentUpdate) -> Self {
548        self.get_mut_components().push(update);
549        self
550    }
551
552    /// Appends a page-level update to this atomic bundle.
553    ///
554    /// # Arguments
555    ///
556    /// - `Self` - Source bundle.
557    /// - `DynamicPageUpdate` - Page update entry.
558    ///
559    /// # Returns
560    ///
561    /// - `Self` - Updated bundle.
562    #[must_use]
563    pub fn push_page(mut self, update: DynamicPageUpdate) -> Self {
564        self.get_mut_pages().push(update);
565        self
566    }
567
568    /// Serializes the complete bundle manifest to pretty-printed JSON.
569    ///
570    /// # Arguments
571    ///
572    /// - `&Self` - Bundle reference.
573    ///
574    /// # Returns
575    ///
576    /// - `Result<String, DynamicUpdateError>` - JSON manifest string.
577    pub fn to_json(&self) -> Result<String, DynamicUpdateError> {
578        match to_string_pretty(self) {
579            Ok(json) => Ok(json),
580            Err(err) => Err(DynamicUpdateError::InvalidJson(err.to_string())),
581        }
582    }
583
584    /// Deserializes a `DynamicUpdateBundle` from a JSON manifest string.
585    ///
586    /// # Arguments
587    ///
588    /// - `&str` - JSON bundle manifest.
589    ///
590    /// # Returns
591    ///
592    /// - `Result<Self, DynamicUpdateError>` - Parsed bundle manifest.
593    pub fn from_json(raw: &str) -> Result<Self, DynamicUpdateError> {
594        match from_str(raw) {
595            Ok(parsed) => Ok(parsed),
596            Err(err) => Err(DynamicUpdateError::InvalidJson(err.to_string())),
597        }
598    }
599}
600
601/// Default empty `DynamicUpdateHub`.
602impl Default for DynamicUpdateHub {
603    /// Creates an empty `DynamicUpdateHub` backed by fresh reactive signals.
604    ///
605    /// # Returns
606    ///
607    /// - `Self` - Initialized hub.
608    fn default() -> Self {
609        Self::new()
610    }
611}
612
613/// Disposes all hub-owned detached signals when the final `DynamicUpdateHub` reference drops.
614impl Drop for DynamicHubState {
615    /// Releases every detached signal registered by this hub so repeated lifecycle cycles retain zero heap entries.
616    ///
617    /// # Arguments
618    ///
619    /// - `&Self` - Hub interior state being dropped.
620    fn drop(&mut self) {
621        let Self {
622            component_signals,
623            page_signals,
624            routes_signal,
625            telemetry_signal,
626            last_action,
627            hot_update_worker,
628            hot_update_status,
629            runtime_epoch,
630            ..
631        } = self;
632        if let Some(mut worker) = hot_update_worker.take() {
633            worker.stop();
634        }
635        if *runtime_epoch != current_runtime_epoch() {
636            return;
637        }
638        routes_signal.dispose();
639        telemetry_signal.dispose();
640        last_action.dispose();
641        hot_update_status.dispose();
642        for sig in component_signals.values() {
643            sig.dispose();
644        }
645        for sig in page_signals.values() {
646            sig.dispose();
647        }
648    }
649}
650
651/// Component-level, page-level, and atomic bundle dynamic update orchestration on `DynamicUpdateHub`.
652impl DynamicUpdateHub {
653    /// Creates a new `DynamicUpdateHub` with empty component/page registries and zero telemetry.
654    ///
655    /// # Returns
656    ///
657    /// - `Self` - Shared dynamic update hub handle.
658    #[must_use]
659    pub fn new() -> Self {
660        let state: DynamicHubState = DynamicHubState {
661            components: HashMap::new(),
662            component_signals: HashMap::new(),
663            pages: HashMap::new(),
664            page_signals: HashMap::new(),
665            routes_signal: Signal::new_detached(0),
666            telemetry_signal: Signal::new_detached(DynamicTelemetry::default()),
667            last_action: Signal::new_detached(None),
668            action_handlers: Vec::new(),
669            hot_update_worker: None,
670            hot_update_cache_dir: None,
671            hot_update_sandbox: WasmSandboxConfig::default(),
672            deferred_hot_candidate: None,
673            hot_update_status: Signal::new_detached(HotUpdateLiveStatus::default()),
674            hot_update_connected: false,
675            runtime_epoch: current_runtime_epoch(),
676        };
677        Self {
678            inner: Rc::new(RefCell::new(state)),
679            hot_update_attention: Arc::new(AtomicBool::new(false)),
680        }
681    }
682
683    /// Applies a validated component-level dynamic update and surgically re-renders only that component slot.
684    ///
685    /// # Arguments
686    ///
687    /// - `&Self` - Hub reference.
688    /// - `DynamicComponentUpdate` - Incoming versioned component update.
689    ///
690    /// # Returns
691    ///
692    /// - `Result<u64, DynamicUpdateError>` - Newly active component version on success.
693    pub fn apply_component(
694        &self,
695        update: DynamicComponentUpdate,
696    ) -> Result<u64, DynamicUpdateError> {
697        let id: String = update.get_id().trim().to_string();
698        if id.is_empty() {
699            self.record_rejection();
700            return Err(DynamicUpdateError::EmptyTargetId);
701        }
702        let actual_checksum: u64 = update.get_spec().checksum();
703        let expected_checksum: u64 = update.get_checksum();
704        if expected_checksum != 0 && expected_checksum != actual_checksum {
705            self.record_rejection();
706            return Err(DynamicUpdateError::ChecksumMismatch {
707                target: id,
708                expected: expected_checksum,
709                actual: actual_checksum,
710            });
711        }
712        let incoming_ver: u64 = update.get_version();
713        let allow_downgrade: bool = update.get_allow_downgrade();
714        let rev_sig_opt: Result<
715            (Signal<u64>, Signal<DynamicTelemetry>, DynamicTelemetry),
716            DynamicUpdateError,
717        > = self.with_state_mut(|state: &mut DynamicHubState| {
718            let active_ver: u64 = state
719                .components
720                .get(&id)
721                .and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
722                .map(|rec: &DynamicSlotRecord| rec.version)
723                .unwrap_or(0);
724            if !allow_downgrade && incoming_ver <= active_ver {
725                return Err(DynamicUpdateError::VersionRegression {
726                    target: id.clone(),
727                    current: active_ver,
728                    incoming: incoming_ver,
729                });
730            }
731            let record: DynamicSlotRecord = DynamicSlotRecord {
732                version: incoming_ver,
733                title: String::new(),
734                checksum: actual_checksum,
735                payload: DynamicPayload::Spec(update.spec),
736            };
737            if let Some(stack) = state.components.get_mut(&id) {
738                stack.push(record);
739            } else {
740                let _: Option<Vec<DynamicSlotRecord>> =
741                    state.components.insert(id.clone(), vec![record]);
742            }
743            let sig: Signal<u64> = if let Some(existing) = state.component_signals.get(&id) {
744                *existing
745            } else {
746                let created: Signal<u64> = Signal::new_detached(0);
747                let _: Option<Signal<u64>> = state.component_signals.insert(id, created);
748                created
749            };
750            let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
751            tel.set_components_applied(tel.get_components_applied().saturating_add(1));
752            Ok((sig, state.telemetry_signal, tel))
753        });
754        match rev_sig_opt {
755            Ok((sig, tel_sig, tel)) => {
756                if tel_sig.has_subscribers() {
757                    batch(|| {
758                        let _: bool = {
759                            if let Some(mut updated_value) = sig.try_get_untracked() {
760                                {
761                                    let item_val: &mut u64 = &mut updated_value;
762                                    *item_val = item_val.wrapping_add(1);
763                                }
764                                sig.set(updated_value)
765                            } else {
766                                false
767                            }
768                        };
769                        let _: bool = tel_sig.set(tel);
770                    });
771                } else {
772                    let _: bool = tel_sig.set(tel);
773                    let _: bool = {
774                        if let Some(mut updated_value) = sig.try_get_untracked() {
775                            {
776                                let tex_v: &mut u64 = &mut updated_value;
777                                *tex_v = tex_v.wrapping_add(1);
778                            }
779                            sig.set(updated_value)
780                        } else {
781                            false
782                        }
783                    };
784                }
785                Ok(incoming_ver)
786            }
787            Err(err) => {
788                self.record_rejection();
789                Err(err)
790            }
791        }
792    }
793
794    /// Parses and applies a JSON-encoded component-level dynamic update manifest.
795    ///
796    /// # Arguments
797    ///
798    /// - `&Self` - Hub reference.
799    /// - `&str` - JSON string encoding a `DynamicComponentUpdate`.
800    ///
801    /// # Returns
802    ///
803    /// - `Result<u64, DynamicUpdateError>` - Newly active component version on success.
804    pub fn apply_component_json(&self, json: &str) -> Result<u64, DynamicUpdateError> {
805        let update: DynamicComponentUpdate = match DynamicComponentUpdate::from_json(json) {
806            Ok(parsed) => parsed,
807            Err(err) => {
808                self.record_rejection();
809                return Err(err);
810            }
811        };
812        self.apply_component(update)
813    }
814
815    /// Hot-swaps a component slot with a native Rust builder closure without rebuilding sibling UI.
816    ///
817    /// # Arguments
818    ///
819    /// - `&Self` - Hub reference.
820    /// - `String` - Target component slot ID.
821    /// - `u64` - Monotonic version number.
822    /// - `CallbackFn` - Zero-context native Rust UI builder closure.
823    ///
824    /// # Returns
825    ///
826    /// - `Result<u64, DynamicUpdateError>` - Newly active component version on success.
827    pub fn swap_component_builder<CallbackFn>(
828        &self,
829        id: String,
830        version: u64,
831        builder: CallbackFn,
832    ) -> Result<u64, DynamicUpdateError>
833    where
834        CallbackFn: Fn() -> NodeId + 'static,
835    {
836        let trimmed: String = id.trim().to_string();
837        if trimmed.is_empty() {
838            self.record_rejection();
839            return Err(DynamicUpdateError::EmptyTargetId);
840        }
841        let builder_rc: Rc<dyn Fn() -> NodeId> = Rc::new(builder);
842        let res: Result<
843            (Signal<u64>, Signal<DynamicTelemetry>, DynamicTelemetry),
844            DynamicUpdateError,
845        > = self.with_state_mut(|state: &mut DynamicHubState| {
846            let active_ver: u64 = state
847                .components
848                .get(&trimmed)
849                .and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
850                .map(|rec: &DynamicSlotRecord| rec.version)
851                .unwrap_or(0);
852            if version <= active_ver {
853                return Err(DynamicUpdateError::VersionRegression {
854                    target: trimmed.clone(),
855                    current: active_ver,
856                    incoming: version,
857                });
858            }
859            let record: DynamicSlotRecord = DynamicSlotRecord {
860                version,
861                title: String::new(),
862                checksum: 0,
863                payload: DynamicPayload::Native(builder_rc),
864            };
865            state
866                .components
867                .entry(trimmed.clone())
868                .or_default()
869                .push(record);
870            let sig: Signal<u64> = *state
871                .component_signals
872                .entry(trimmed)
873                .or_insert_with(|| Signal::new_detached(0));
874            let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
875            tel.set_components_applied(tel.get_components_applied().saturating_add(1));
876            Ok((sig, state.telemetry_signal, tel))
877        });
878        match res {
879            Ok((sig, tel_sig, tel)) => {
880                batch(|| {
881                    let _: bool = {
882                        if let Some(mut updated_value) = sig.try_get_untracked() {
883                            {
884                                let item_val: &mut u64 = &mut updated_value;
885                                *item_val = item_val.wrapping_add(1);
886                            }
887                            sig.set(updated_value)
888                        } else {
889                            false
890                        }
891                    };
892                    let _: bool = tel_sig.set(tel);
893                });
894                Ok(version)
895            }
896            Err(err) => {
897                self.record_rejection();
898                Err(err)
899            }
900        }
901    }
902
903    /// Rolls back a component slot to its previous revision (or `0` compiled fallback when the stack empties).
904    ///
905    /// # Arguments
906    ///
907    /// - `&Self` - Hub reference.
908    /// - `&str` - Target component slot ID.
909    ///
910    /// # Returns
911    ///
912    /// - `Result<u64, DynamicUpdateError>` - Restored active version (`0` means compiled fallback).
913    pub fn rollback_component(&self, id: &str) -> Result<u64, DynamicUpdateError> {
914        let key: &str = id.trim();
915        let res: Result<
916            (u64, Signal<u64>, Signal<DynamicTelemetry>, DynamicTelemetry),
917            DynamicUpdateError,
918        > = self.with_state_mut(|state: &mut DynamicHubState| {
919            let popped: bool = state
920                .components
921                .get_mut(key)
922                .and_then(|stack: &mut Vec<DynamicSlotRecord>| stack.pop())
923                .is_some();
924            if !popped {
925                return Err(DynamicUpdateError::NoHistoryToRollback(key.to_string()));
926            }
927            let next_ver: u64 = state
928                .components
929                .get(key)
930                .and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
931                .map(|rec: &DynamicSlotRecord| rec.version)
932                .unwrap_or(0);
933            let sig: Signal<u64> = if let Some(existing) = state.component_signals.get(key) {
934                *existing
935            } else {
936                let created: Signal<u64> = Signal::new_detached(0);
937                let _: Option<Signal<u64>> =
938                    state.component_signals.insert(key.to_string(), created);
939                created
940            };
941            let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
942            tel.set_rollbacks(tel.get_rollbacks().saturating_add(1));
943            Ok((next_ver, sig, state.telemetry_signal, tel))
944        });
945        let (next_ver, sig, tel_sig, tel): (
946            u64,
947            Signal<u64>,
948            Signal<DynamicTelemetry>,
949            DynamicTelemetry,
950        ) = res?;
951        if tel_sig.has_subscribers() {
952            batch(|| {
953                let _: bool = {
954                    if let Some(mut updated_value) = sig.try_get_untracked() {
955                        {
956                            let item_val: &mut u64 = &mut updated_value;
957                            *item_val = item_val.wrapping_add(1);
958                        }
959                        sig.set(updated_value)
960                    } else {
961                        false
962                    }
963                };
964                let _: bool = tel_sig.set(tel);
965            });
966        } else {
967            let _: bool = tel_sig.set(tel);
968            let _: bool = {
969                if let Some(mut updated_value) = sig.try_get_untracked() {
970                    {
971                        let tex_v: &mut u64 = &mut updated_value;
972                        *tex_v = tex_v.wrapping_add(1);
973                    }
974                    sig.set(updated_value)
975                } else {
976                    false
977                }
978            };
979        }
980        Ok(next_ver)
981    }
982
983    /// Applies a validated page-level dynamic update (overriding an existing route or injecting a new one).
984    ///
985    /// # Arguments
986    ///
987    /// - `&Self` - Hub reference.
988    /// - `DynamicPageUpdate` - Incoming versioned page update.
989    ///
990    /// # Returns
991    ///
992    /// - `Result<u64, DynamicUpdateError>` - Newly active page version on success.
993    pub fn apply_page(&self, update: DynamicPageUpdate) -> Result<u64, DynamicUpdateError> {
994        let route: String = normalize_dynamic_route(update.get_route());
995        if route.is_empty() {
996            self.record_rejection();
997            return Err(DynamicUpdateError::EmptyTargetId);
998        }
999        let actual_checksum: u64 = update.get_spec().checksum();
1000        let expected_checksum: u64 = update.get_checksum();
1001        if expected_checksum != 0 && expected_checksum != actual_checksum {
1002            self.record_rejection();
1003            return Err(DynamicUpdateError::ChecksumMismatch {
1004                target: route,
1005                expected: expected_checksum,
1006                actual: actual_checksum,
1007            });
1008        }
1009        let incoming_ver: u64 = update.get_version();
1010        let allow_downgrade: bool = update.get_allow_downgrade();
1011        let res: Result<PageApplyCommit, DynamicUpdateError> =
1012            self.with_state_mut(|state: &mut DynamicHubState| {
1013                let is_new_route: bool = state
1014                    .pages
1015                    .get(&route)
1016                    .map(|stack: &Vec<DynamicSlotRecord>| stack.is_empty())
1017                    .unwrap_or(true);
1018                let active_ver: u64 = state
1019                    .pages
1020                    .get(&route)
1021                    .and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
1022                    .map(|rec: &DynamicSlotRecord| rec.version)
1023                    .unwrap_or(0);
1024                if !allow_downgrade && incoming_ver <= active_ver {
1025                    return Err(DynamicUpdateError::VersionRegression {
1026                        target: route.clone(),
1027                        current: active_ver,
1028                        incoming: incoming_ver,
1029                    });
1030                }
1031                let record: DynamicSlotRecord = DynamicSlotRecord {
1032                    version: incoming_ver,
1033                    title: update.title,
1034                    checksum: actual_checksum,
1035                    payload: DynamicPayload::Spec(update.spec),
1036                };
1037                state.pages.entry(route.clone()).or_default().push(record);
1038                let page_sig: Signal<u64> = *state
1039                    .page_signals
1040                    .entry(route)
1041                    .or_insert_with(|| Signal::new_detached(0));
1042                let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
1043                tel.set_pages_applied(tel.get_pages_applied().saturating_add(1));
1044                Ok(PageApplyCommit {
1045                    page_sig,
1046                    routes_sig: state.routes_signal,
1047                    tel_sig: state.telemetry_signal,
1048                    tel,
1049                    is_new_route,
1050                })
1051            });
1052        match res {
1053            Ok(PageApplyCommit {
1054                page_sig,
1055                routes_sig,
1056                tel_sig,
1057                tel,
1058                is_new_route,
1059            }) => {
1060                batch(|| {
1061                    let _: bool = {
1062                        if let Some(mut updated_value) = page_sig.try_get_untracked() {
1063                            {
1064                                let item_val: &mut u64 = &mut updated_value;
1065                                *item_val = item_val.wrapping_add(1);
1066                            }
1067                            page_sig.set(updated_value)
1068                        } else {
1069                            false
1070                        }
1071                    };
1072                    if is_new_route {
1073                        let _: bool = {
1074                            if let Some(mut updated_value) = routes_sig.try_get_untracked() {
1075                                {
1076                                    let tex_v: &mut u64 = &mut updated_value;
1077                                    *tex_v = tex_v.wrapping_add(1);
1078                                }
1079                                routes_sig.set(updated_value)
1080                            } else {
1081                                false
1082                            }
1083                        };
1084                    }
1085                    let _: bool = tel_sig.set(tel);
1086                });
1087                Ok(incoming_ver)
1088            }
1089            Err(err) => {
1090                self.record_rejection();
1091                Err(err)
1092            }
1093        }
1094    }
1095
1096    /// Parses and applies a JSON-encoded page-level dynamic update manifest.
1097    ///
1098    /// # Arguments
1099    ///
1100    /// - `&Self` - Hub reference.
1101    /// - `&str` - JSON string encoding a `DynamicPageUpdate`.
1102    ///
1103    /// # Returns
1104    ///
1105    /// - `Result<u64, DynamicUpdateError>` - Newly active page version on success.
1106    pub fn apply_page_json(&self, json: &str) -> Result<u64, DynamicUpdateError> {
1107        let update: DynamicPageUpdate = match DynamicPageUpdate::from_json(json) {
1108            Ok(parsed) => parsed,
1109            Err(err) => {
1110                self.record_rejection();
1111                return Err(err);
1112            }
1113        };
1114        self.apply_page(update)
1115    }
1116
1117    /// Hot-swaps a page route with a native Rust page builder closure.
1118    ///
1119    /// # Arguments
1120    ///
1121    /// - `&Self` - Hub reference.
1122    /// - `String` - Target route path.
1123    /// - `String` - Page title.
1124    /// - `u64` - Monotonic page version number.
1125    /// - `CallbackFn` - Zero-context native Rust page builder closure.
1126    ///
1127    /// # Returns
1128    ///
1129    /// - `Result<u64, DynamicUpdateError>` - Newly active page version on success.
1130    pub fn swap_page_builder<CallbackFn>(
1131        &self,
1132        route: String,
1133        title: String,
1134        version: u64,
1135        builder: CallbackFn,
1136    ) -> Result<u64, DynamicUpdateError>
1137    where
1138        CallbackFn: Fn() -> NodeId + 'static,
1139    {
1140        let normalized: String = normalize_dynamic_route(&route);
1141        if normalized.is_empty() {
1142            self.record_rejection();
1143            return Err(DynamicUpdateError::EmptyTargetId);
1144        }
1145        let builder_rc: Rc<dyn Fn() -> NodeId> = Rc::new(builder);
1146        let res: Result<PageApplyCommit, DynamicUpdateError> =
1147            self.with_state_mut(|state: &mut DynamicHubState| {
1148                let is_new_route: bool = state
1149                    .pages
1150                    .get(&normalized)
1151                    .map(|stack: &Vec<DynamicSlotRecord>| stack.is_empty())
1152                    .unwrap_or(true);
1153                let active_ver: u64 = state
1154                    .pages
1155                    .get(&normalized)
1156                    .and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
1157                    .map(|rec: &DynamicSlotRecord| rec.version)
1158                    .unwrap_or(0);
1159                if version <= active_ver {
1160                    return Err(DynamicUpdateError::VersionRegression {
1161                        target: normalized.clone(),
1162                        current: active_ver,
1163                        incoming: version,
1164                    });
1165                }
1166                let record: DynamicSlotRecord = DynamicSlotRecord {
1167                    version,
1168                    title,
1169                    checksum: 0,
1170                    payload: DynamicPayload::Native(builder_rc),
1171                };
1172                state
1173                    .pages
1174                    .entry(normalized.clone())
1175                    .or_default()
1176                    .push(record);
1177                let page_sig: Signal<u64> = *state
1178                    .page_signals
1179                    .entry(normalized)
1180                    .or_insert_with(|| Signal::new_detached(0));
1181                let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
1182                tel.set_pages_applied(tel.get_pages_applied().saturating_add(1));
1183                Ok(PageApplyCommit {
1184                    page_sig,
1185                    routes_sig: state.routes_signal,
1186                    tel_sig: state.telemetry_signal,
1187                    tel,
1188                    is_new_route,
1189                })
1190            });
1191        match res {
1192            Ok(PageApplyCommit {
1193                page_sig,
1194                routes_sig,
1195                tel_sig,
1196                tel,
1197                is_new_route,
1198            }) => {
1199                batch(|| {
1200                    let _: bool = {
1201                        if let Some(mut updated_value) = page_sig.try_get_untracked() {
1202                            {
1203                                let item_val: &mut u64 = &mut updated_value;
1204                                *item_val = item_val.wrapping_add(1);
1205                            }
1206                            page_sig.set(updated_value)
1207                        } else {
1208                            false
1209                        }
1210                    };
1211                    if is_new_route {
1212                        let _: bool = {
1213                            if let Some(mut updated_value) = routes_sig.try_get_untracked() {
1214                                {
1215                                    let tex_v: &mut u64 = &mut updated_value;
1216                                    *tex_v = tex_v.wrapping_add(1);
1217                                }
1218                                routes_sig.set(updated_value)
1219                            } else {
1220                                false
1221                            }
1222                        };
1223                    }
1224                    let _: bool = tel_sig.set(tel);
1225                });
1226                Ok(version)
1227            }
1228            Err(err) => {
1229                self.record_rejection();
1230                Err(err)
1231            }
1232        }
1233    }
1234
1235    /// Rolls back a dynamically updated page to its previous revision (or `0` compiled fallback).
1236    ///
1237    /// # Arguments
1238    ///
1239    /// - `&Self` - Hub reference.
1240    /// - `&str` - Target route path.
1241    ///
1242    /// # Returns
1243    ///
1244    /// - `Result<u64, DynamicUpdateError>` - Restored page version (`0` means fallback / removed).
1245    pub fn rollback_page(&self, route: &str) -> Result<u64, DynamicUpdateError> {
1246        let normalized: String = normalize_dynamic_route(route);
1247        let res: Result<PageRollbackCommit, DynamicUpdateError> =
1248            self.with_state_mut(|state: &mut DynamicHubState| {
1249                let popped: bool = state
1250                    .pages
1251                    .get_mut(&normalized)
1252                    .and_then(|stack: &mut Vec<DynamicSlotRecord>| stack.pop())
1253                    .is_some();
1254                if !popped {
1255                    return Err(DynamicUpdateError::NoHistoryToRollback(normalized.clone()));
1256                }
1257                let next_ver: u64 = state
1258                    .pages
1259                    .get(&normalized)
1260                    .and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
1261                    .map(|rec: &DynamicSlotRecord| rec.version)
1262                    .unwrap_or(0);
1263                let route_removed: bool = next_ver == 0;
1264                let page_sig: Signal<u64> = *state
1265                    .page_signals
1266                    .entry(normalized)
1267                    .or_insert_with(|| Signal::new_detached(0));
1268                let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
1269                tel.set_rollbacks(tel.get_rollbacks().saturating_add(1));
1270                Ok(PageRollbackCommit {
1271                    next_ver,
1272                    page_sig,
1273                    routes_sig: state.routes_signal,
1274                    tel_sig: state.telemetry_signal,
1275                    tel,
1276                    route_removed,
1277                })
1278            });
1279        let PageRollbackCommit {
1280            next_ver,
1281            page_sig,
1282            routes_sig,
1283            tel_sig,
1284            tel,
1285            route_removed,
1286        } = res?;
1287        batch(|| {
1288            let _: bool = {
1289                if let Some(mut updated_value) = page_sig.try_get_untracked() {
1290                    {
1291                        let item_val: &mut u64 = &mut updated_value;
1292                        *item_val = item_val.wrapping_add(1);
1293                    }
1294                    page_sig.set(updated_value)
1295                } else {
1296                    false
1297                }
1298            };
1299            if route_removed {
1300                let _: bool = {
1301                    if let Some(mut updated_value) = routes_sig.try_get_untracked() {
1302                        {
1303                            let tex_v: &mut u64 = &mut updated_value;
1304                            *tex_v = tex_v.wrapping_add(1);
1305                        }
1306                        routes_sig.set(updated_value)
1307                    } else {
1308                        false
1309                    }
1310                };
1311            }
1312            let _: bool = tel_sig.set(tel);
1313        });
1314        Ok(next_ver)
1315    }
1316
1317    /// Validates all component and page entries in `bundle` before committing them atomically in a single `batch`.
1318    ///
1319    /// # Arguments
1320    ///
1321    /// - `&Self` - Hub reference.
1322    /// - `DynamicUpdateBundle` - Multi-target atomic release bundle.
1323    ///
1324    /// # Returns
1325    ///
1326    /// - `Result<DynamicTelemetry, DynamicUpdateError>` - Updated telemetry snapshot on full commit, or error with zero partial mutation.
1327    pub fn apply_bundle(
1328        &self,
1329        bundle: DynamicUpdateBundle,
1330    ) -> Result<DynamicTelemetry, DynamicUpdateError> {
1331        let validation: Result<BundleApplyCommit, DynamicUpdateError> =
1332            self.with_state_mut(|state: &mut DynamicHubState| {
1333                let mut staged_comp_vers: HashMap<String, u64> = HashMap::new();
1334                let mut comp_checksums: Vec<u64> = Vec::with_capacity(bundle.components.len());
1335                for comp in bundle.components.iter() {
1336                    let id: String = comp.get_id().trim().to_string();
1337                    if id.is_empty() {
1338                        return Err(DynamicUpdateError::EmptyTargetId);
1339                    }
1340                    let actual: u64 = comp.get_spec().checksum();
1341                    let expected: u64 = comp.get_checksum();
1342                    if expected != 0 && expected != actual {
1343                        return Err(DynamicUpdateError::ChecksumMismatch {
1344                            target: id,
1345                            expected,
1346                            actual,
1347                        });
1348                    }
1349                    let cur: u64 = staged_comp_vers.get(&id).copied().unwrap_or_else(|| {
1350                        state
1351                            .components
1352                            .get(&id)
1353                            .and_then(|source_val: &Vec<DynamicSlotRecord>| source_val.last())
1354                            .map(|red_val: &DynamicSlotRecord| red_val.version)
1355                            .unwrap_or(0)
1356                    });
1357                    if !comp.get_allow_downgrade() && comp.get_version() <= cur {
1358                        return Err(DynamicUpdateError::VersionRegression {
1359                            target: id,
1360                            current: cur,
1361                            incoming: comp.get_version(),
1362                        });
1363                    }
1364                    staged_comp_vers.insert(id, comp.get_version());
1365                    comp_checksums.push(actual);
1366                }
1367                let mut staged_page_vers: HashMap<String, u64> = HashMap::new();
1368                let mut page_checksums: Vec<u64> = Vec::with_capacity(bundle.pages.len());
1369                for page in bundle.pages.iter() {
1370                    let route: String = normalize_dynamic_route(page.get_route());
1371                    if route.is_empty() {
1372                        return Err(DynamicUpdateError::EmptyTargetId);
1373                    }
1374                    let actual: u64 = page.get_spec().checksum();
1375                    let expected: u64 = page.get_checksum();
1376                    if expected != 0 && expected != actual {
1377                        return Err(DynamicUpdateError::ChecksumMismatch {
1378                            target: route,
1379                            expected,
1380                            actual,
1381                        });
1382                    }
1383                    let cur: u64 = staged_page_vers.get(&route).copied().unwrap_or_else(|| {
1384                        state
1385                            .pages
1386                            .get(&route)
1387                            .and_then(|scale_val: &Vec<DynamicSlotRecord>| scale_val.last())
1388                            .map(|radius_val: &DynamicSlotRecord| radius_val.version)
1389                            .unwrap_or(0)
1390                    });
1391                    if !page.get_allow_downgrade() && page.get_version() <= cur {
1392                        return Err(DynamicUpdateError::VersionRegression {
1393                            target: route,
1394                            current: cur,
1395                            incoming: page.get_version(),
1396                        });
1397                    }
1398                    staged_page_vers.insert(route, page.get_version());
1399                    page_checksums.push(actual);
1400                }
1401                let mut dirty_signals: Vec<Signal<u64>> =
1402                    Vec::with_capacity(bundle.components.len() + bundle.pages.len());
1403                let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
1404                for (comp, digest) in bundle.components.into_iter().zip(comp_checksums) {
1405                    let id: String = comp.get_id().trim().to_string();
1406                    let record: DynamicSlotRecord = DynamicSlotRecord {
1407                        version: comp.version,
1408                        title: String::new(),
1409                        checksum: digest,
1410                        payload: DynamicPayload::Spec(comp.spec),
1411                    };
1412                    state.components.entry(id.clone()).or_default().push(record);
1413                    let sig: Signal<u64> = *state
1414                        .component_signals
1415                        .entry(id)
1416                        .or_insert_with(|| Signal::new_detached(0));
1417                    dirty_signals.push(sig);
1418                    tel.set_components_applied(tel.get_components_applied().saturating_add(1));
1419                }
1420                let mut added_route: bool = false;
1421                for (page, digest) in bundle.pages.into_iter().zip(page_checksums) {
1422                    let route: String = normalize_dynamic_route(page.get_route());
1423                    let is_new: bool = state
1424                        .pages
1425                        .get(&route)
1426                        .map(|series_item: &Vec<DynamicSlotRecord>| series_item.is_empty())
1427                        .unwrap_or(true);
1428                    if is_new {
1429                        added_route = true;
1430                    }
1431                    let record: DynamicSlotRecord = DynamicSlotRecord {
1432                        version: page.version,
1433                        title: page.title,
1434                        checksum: digest,
1435                        payload: DynamicPayload::Spec(page.spec),
1436                    };
1437                    state.pages.entry(route.clone()).or_default().push(record);
1438                    let sig: Signal<u64> = *state
1439                        .page_signals
1440                        .entry(route)
1441                        .or_insert_with(|| Signal::new_detached(0));
1442                    dirty_signals.push(sig);
1443                    tel.set_pages_applied(tel.get_pages_applied().saturating_add(1));
1444                }
1445                Ok(BundleApplyCommit {
1446                    dirty_signals,
1447                    added_route,
1448                    routes_sig: state.routes_signal,
1449                    tel_sig: state.telemetry_signal,
1450                    tel,
1451                })
1452            });
1453        match validation {
1454            Ok(BundleApplyCommit {
1455                dirty_signals,
1456                added_route,
1457                routes_sig,
1458                tel_sig,
1459                tel,
1460            }) => {
1461                batch(|| {
1462                    for sig in dirty_signals.into_iter() {
1463                        let _: bool = {
1464                            if let Some(mut updated_value) = sig.try_get_untracked() {
1465                                {
1466                                    let item_val: &mut u64 = &mut updated_value;
1467                                    *item_val = item_val.wrapping_add(1);
1468                                }
1469                                sig.set(updated_value)
1470                            } else {
1471                                false
1472                            }
1473                        };
1474                    }
1475                    if added_route {
1476                        let _: bool = {
1477                            if let Some(mut updated_value) = routes_sig.try_get_untracked() {
1478                                {
1479                                    let tex_v: &mut u64 = &mut updated_value;
1480                                    *tex_v = tex_v.wrapping_add(1);
1481                                }
1482                                routes_sig.set(updated_value)
1483                            } else {
1484                                false
1485                            }
1486                        };
1487                    }
1488                    let _: bool = tel_sig.set(tel);
1489                });
1490                Ok(tel)
1491            }
1492            Err(err) => {
1493                self.record_rejection();
1494                Err(err)
1495            }
1496        }
1497    }
1498
1499    /// Parses and atomically applies a JSON-encoded `DynamicUpdateBundle` manifest.
1500    ///
1501    /// # Arguments
1502    ///
1503    /// - `&Self` - Hub reference.
1504    /// - `&str` - JSON bundle manifest string.
1505    ///
1506    /// # Returns
1507    ///
1508    /// - `Result<DynamicTelemetry, DynamicUpdateError>` - Updated telemetry snapshot on success.
1509    pub fn apply_bundle_json(&self, json: &str) -> Result<DynamicTelemetry, DynamicUpdateError> {
1510        let bundle: DynamicUpdateBundle = match DynamicUpdateBundle::from_json(json) {
1511            Ok(parsed) => parsed,
1512            Err(err) => {
1513                self.record_rejection();
1514                return Err(err);
1515            }
1516        };
1517        self.apply_bundle(bundle)
1518    }
1519
1520    /// Registers an action callback invoked whenever a button inside a dynamically updated component or page is clicked.
1521    ///
1522    /// # Arguments
1523    ///
1524    /// - `&Self` - Hub reference.
1525    /// - `CallbackFn` - Action callback receiving `&DynamicActionEvent`.
1526    pub fn on_action<CallbackFn>(&self, handler: CallbackFn)
1527    where
1528        CallbackFn: FnMut(&DynamicActionEvent) + 'static,
1529    {
1530        let callback_fn: DynamicActionCallback = Rc::new(RefCell::new(handler));
1531        self.with_state_mut(|state: &mut DynamicHubState| {
1532            state.action_handlers.push(callback_fn);
1533        });
1534    }
1535
1536    /// Dispatches a `DynamicActionEvent` to all registered handlers and updates `last_action` + telemetry.
1537    ///
1538    /// # Arguments
1539    ///
1540    /// - `&Self` - Hub reference.
1541    /// - `DynamicActionEvent` - Action event emitted by a dynamic control.
1542    pub fn dispatch_action(&self, event: DynamicActionEvent) {
1543        let (handlers, last_sig, tel_sig, next_tel): (
1544            Vec<DynamicActionCallback>,
1545            Signal<Option<DynamicActionEvent>>,
1546            Signal<DynamicTelemetry>,
1547            DynamicTelemetry,
1548        ) = self.with_state_mut(|state: &mut DynamicHubState| {
1549            let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
1550            tel.set_actions_dispatched(tel.get_actions_dispatched().saturating_add(1));
1551            (
1552                state.action_handlers.clone(),
1553                state.last_action,
1554                state.telemetry_signal,
1555                tel,
1556            )
1557        });
1558        batch(|| {
1559            let _: bool = last_sig.set(Some(event.clone()));
1560            let _: bool = tel_sig.set(next_tel);
1561        });
1562        for callback_fn in handlers.into_iter() {
1563            if let Ok(mut func) = callback_fn.try_borrow_mut() {
1564                func(&event);
1565            }
1566        }
1567    }
1568
1569    /// Returns the dedicated reactive revision signal for component slot `id`.
1570    ///
1571    /// # Arguments
1572    ///
1573    /// - `&Self` - Hub reference.
1574    /// - `&str` - Component slot identifier.
1575    ///
1576    /// # Returns
1577    ///
1578    /// - `Signal<u64>` - Surgical revision signal bumped only when `id` updates.
1579    #[must_use]
1580    pub fn component_revision_signal(&self, id: &str) -> Signal<u64> {
1581        let key: String = id.trim().to_string();
1582        self.with_state_mut(|state: &mut DynamicHubState| {
1583            *state
1584                .component_signals
1585                .entry(key)
1586                .or_insert_with(|| Signal::new_detached(0))
1587        })
1588    }
1589
1590    /// Returns the dedicated reactive revision signal for page `route`.
1591    ///
1592    /// # Arguments
1593    ///
1594    /// - `&Self` - Hub reference.
1595    /// - `&str` - Target route path.
1596    ///
1597    /// # Returns
1598    ///
1599    /// - `Signal<u64>` - Surgical revision signal bumped only when `route` updates.
1600    #[must_use]
1601    pub fn page_revision_signal(&self, route: &str) -> Signal<u64> {
1602        let key: String = normalize_dynamic_route(route);
1603        self.with_state_mut(|state: &mut DynamicHubState| {
1604            *state
1605                .page_signals
1606                .entry(key)
1607                .or_insert_with(|| Signal::new_detached(0))
1608        })
1609    }
1610
1611    /// Returns the currently active dynamic version for component slot `id` (`0` means compiled fallback).
1612    ///
1613    /// # Arguments
1614    ///
1615    /// - `&Self` - Hub reference.
1616    /// - `&str` - Component slot identifier.
1617    ///
1618    /// # Returns
1619    ///
1620    /// - `u64` - Active component version.
1621    #[must_use]
1622    pub fn component_version(&self, id: &str) -> u64 {
1623        let key: &str = id.trim();
1624        self.with_state(|state: &DynamicHubState| {
1625            state
1626                .components
1627                .get(key)
1628                .and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
1629                .map(|rec: &DynamicSlotRecord| rec.version)
1630                .unwrap_or(0)
1631        })
1632    }
1633
1634    /// Returns the number of stacked dynamic revisions retained for component slot `id`.
1635    ///
1636    /// # Arguments
1637    ///
1638    /// - `&Self` - Hub reference.
1639    /// - `&str` - Component slot identifier.
1640    ///
1641    /// # Returns
1642    ///
1643    /// - `usize` - Number of revisions on the rollback stack.
1644    #[must_use]
1645    pub fn component_history_len(&self, id: &str) -> usize {
1646        let key: &str = id.trim();
1647        self.with_state(|state: &DynamicHubState| {
1648            state
1649                .components
1650                .get(key)
1651                .map(|stack: &Vec<DynamicSlotRecord>| stack.len())
1652                .unwrap_or(0)
1653        })
1654    }
1655
1656    /// Returns the currently active dynamic version for page `route` (`0` means compiled fallback).
1657    ///
1658    /// # Arguments
1659    ///
1660    /// - `&Self` - Hub reference.
1661    /// - `&str` - Page route path.
1662    ///
1663    /// # Returns
1664    ///
1665    /// - `u64` - Active page version.
1666    #[must_use]
1667    pub fn page_version(&self, route: &str) -> u64 {
1668        let key: String = normalize_dynamic_route(route);
1669        self.with_state(|state: &DynamicHubState| {
1670            state
1671                .pages
1672                .get(&key)
1673                .and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
1674                .map(|rec: &DynamicSlotRecord| rec.version)
1675                .unwrap_or(0)
1676        })
1677    }
1678
1679    /// Returns the active dynamic page title for `route` if a dynamic page is mounted for it.
1680    ///
1681    /// # Arguments
1682    ///
1683    /// - `&Self` - Hub reference.
1684    /// - `&str` - Page route path.
1685    ///
1686    /// # Returns
1687    ///
1688    /// - `Option<String>` - Active dynamic page title if any.
1689    #[must_use]
1690    pub fn page_title(&self, route: &str) -> Option<String> {
1691        let key: String = normalize_dynamic_route(route);
1692        self.with_state(|state: &DynamicHubState| {
1693            state
1694                .pages
1695                .get(&key)
1696                .and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
1697                .map(|rec: &DynamicSlotRecord| rec.title.clone())
1698        })
1699    }
1700
1701    /// Returns `true` when `route` currently has an active dynamic page override or injected page.
1702    ///
1703    /// # Arguments
1704    ///
1705    /// - `&Self` - Hub reference.
1706    /// - `&str` - Page route path.
1707    ///
1708    /// # Returns
1709    ///
1710    /// - `bool` - True when a dynamic page payload is active for `route`.
1711    #[must_use]
1712    pub fn has_dynamic_page(&self, route: &str) -> bool {
1713        self.page_version(route) > 0
1714    }
1715
1716    /// Returns the sorted list of all routes currently carrying active dynamic page payloads.
1717    ///
1718    /// # Arguments
1719    ///
1720    /// - `&Self` - Hub reference.
1721    ///
1722    /// # Returns
1723    ///
1724    /// - `Vec<String>` - Sorted active dynamic route paths.
1725    #[must_use]
1726    pub fn registered_routes(&self) -> Vec<String> {
1727        self.with_state(|state: &DynamicHubState| {
1728            let mut routes: Vec<String> = state
1729                .pages
1730                .iter()
1731                .filter(|(_, stack): &(&String, &Vec<DynamicSlotRecord>)| !stack.is_empty())
1732                .map(|(route, _): (&String, &Vec<DynamicSlotRecord>)| route.clone())
1733                .collect();
1734            routes.sort();
1735            routes
1736        })
1737    }
1738
1739    /// Returns the reactive signal bumped whenever dynamic routes are added or removed.
1740    ///
1741    /// # Arguments
1742    ///
1743    /// - `&Self` - Hub reference.
1744    ///
1745    /// # Returns
1746    ///
1747    /// - `Signal<u64>` - Reactive route-set revision signal.
1748    #[must_use]
1749    pub fn routes_signal(&self) -> Signal<u64> {
1750        let Self { inner, .. } = self;
1751        inner
1752            .try_borrow()
1753            .map(|state: Ref<'_, DynamicHubState>| state.routes_signal)
1754            .unwrap_or_else(|_| Signal::new_detached(0))
1755    }
1756
1757    /// Returns the reactive telemetry snapshot signal.
1758    ///
1759    /// # Arguments
1760    ///
1761    /// - `&Self` - Hub reference.
1762    ///
1763    /// # Returns
1764    ///
1765    /// - `Signal<DynamicTelemetry>` - Reactive dynamic update telemetry signal.
1766    #[must_use]
1767    pub fn telemetry(&self) -> Signal<DynamicTelemetry> {
1768        let Self { inner, .. } = self;
1769        inner
1770            .try_borrow()
1771            .map(|state: Ref<'_, DynamicHubState>| state.telemetry_signal)
1772            .unwrap_or_else(|_| Signal::new_detached(DynamicTelemetry::default()))
1773    }
1774
1775    /// Returns the reactive signal storing the most recently dispatched `DynamicActionEvent`.
1776    ///
1777    /// # Arguments
1778    ///
1779    /// - `&Self` - Hub reference.
1780    ///
1781    /// # Returns
1782    ///
1783    /// - `Signal<Option<DynamicActionEvent>>` - Reactive latest action signal.
1784    #[must_use]
1785    pub fn last_action(&self) -> Signal<Option<DynamicActionEvent>> {
1786        let Self { inner, .. } = self;
1787        inner
1788            .try_borrow()
1789            .map(|state: Ref<'_, DynamicHubState>| state.last_action)
1790            .unwrap_or_else(|_| Signal::new_detached(None))
1791    }
1792
1793    /// Mounts the active dynamic payload for component slot `id`, or executes `fallback` if none is active.
1794    ///
1795    /// # Arguments
1796    ///
1797    /// - `&Self` - Hub reference.
1798    /// - `&str` - Component slot identifier.
1799    /// - `&DynamicSlotFallback` - Compiled fallback builder closure.
1800    ///
1801    /// # Returns
1802    ///
1803    /// - `NodeId` - Mounted native scene node handle.
1804    #[must_use]
1805    pub fn mount_component_or_fallback(&self, id: &str, node_id: &DynamicSlotFallback) -> NodeId {
1806        let key: &str = id.trim();
1807        let Self { inner, .. } = self;
1808        let native_builder: Option<DynamicSlotFallback> = if let Ok(state) = inner.try_borrow() {
1809            match state
1810                .components
1811                .get(key)
1812                .and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
1813                .map(|rec: &DynamicSlotRecord| &rec.payload)
1814            {
1815                Some(DynamicPayload::Spec(spec)) => {
1816                    return mount_dynamic_spec(spec, key, self);
1817                }
1818                Some(DynamicPayload::Native(builder)) => Some(Rc::clone(builder)),
1819                None => None,
1820            }
1821        } else {
1822            None
1823        };
1824        if let Some(builder) = native_builder {
1825            builder()
1826        } else {
1827            node_id()
1828        }
1829    }
1830
1831    /// Mounts the active dynamic payload for page `route`, or executes `fallback` if none is active.
1832    ///
1833    /// # Arguments
1834    ///
1835    /// - `&Self` - Hub reference.
1836    /// - `&str` - Target route path.
1837    /// - `&DynamicSlotFallback` - Compiled fallback page builder closure.
1838    ///
1839    /// # Returns
1840    ///
1841    /// - `NodeId` - Mounted native page node handle.
1842    #[must_use]
1843    pub fn mount_page_or_fallback(&self, route: &str, fallback: &DynamicSlotFallback) -> NodeId {
1844        let trimmed: &str = route.trim();
1845        let owned_key: String = if trimmed.is_empty() || trimmed.starts_with('/') {
1846            String::new()
1847        } else {
1848            format!("/{trimmed}")
1849        };
1850        let key: &str = if owned_key.is_empty() {
1851            trimmed
1852        } else {
1853            owned_key.as_str()
1854        };
1855        let Self { inner, .. } = self;
1856        let native_builder: Option<Rc<dyn Fn() -> NodeId>> = if let Ok(state) = inner.try_borrow() {
1857            match state
1858                .pages
1859                .get(key)
1860                .and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
1861                .map(|rec: &DynamicSlotRecord| &rec.payload)
1862            {
1863                Some(DynamicPayload::Spec(spec)) => {
1864                    return mount_dynamic_spec(spec, key, self);
1865                }
1866                Some(DynamicPayload::Native(builder)) => Some(Rc::clone(builder)),
1867                None => None,
1868            }
1869        } else {
1870            None
1871        };
1872        if let Some(builder) = native_builder {
1873            builder()
1874        } else {
1875            fallback()
1876        }
1877    }
1878
1879    /// Increments the rejected-update telemetry counter safely outside any active state borrow.
1880    ///
1881    /// # Arguments
1882    ///
1883    /// - `&Self` - Hub reference.
1884    fn record_rejection(&self) {
1885        let tel_sig: Signal<DynamicTelemetry> = self.telemetry();
1886        let mut next_tel: DynamicTelemetry = tel_sig.get_untracked();
1887        next_tel.set_rejected(next_tel.get_rejected().saturating_add(1));
1888        let _: bool = tel_sig.set(next_tel);
1889    }
1890
1891    /// Executes a read-only closure on the internal `DynamicHubState` via safe `try_borrow`.
1892    ///
1893    /// # Arguments
1894    ///
1895    /// - `&Self` - Hub reference.
1896    /// - `CallbackFn` - Reader closure.
1897    ///
1898    /// # Returns
1899    ///
1900    /// - `ReturnValue` - Closure return value or `R::default()` if re-entrantly borrowed.
1901    fn with_state<CallbackFn, ReturnValue>(&self, operation: CallbackFn) -> ReturnValue
1902    where
1903        CallbackFn: FnOnce(&DynamicHubState) -> ReturnValue,
1904        ReturnValue: Default,
1905    {
1906        let Self { inner, .. } = self;
1907        match inner.try_borrow() {
1908            Ok(guard) => operation(&guard),
1909            Err(_) => ReturnValue::default(),
1910        }
1911    }
1912
1913    /// Executes a mutable closure on the internal `DynamicHubState` via safe `try_borrow_mut`.
1914    ///
1915    /// # Arguments
1916    ///
1917    /// - `&Self` - Hub reference.
1918    /// - `CallbackFn` - Mutator closure.
1919    ///
1920    /// # Returns
1921    ///
1922    /// - `ReturnValue` - Closure return value.
1923    fn with_state_mut<CallbackFn, ReturnValue>(&self, operation: CallbackFn) -> ReturnValue
1924    where
1925        CallbackFn: FnOnce(&mut DynamicHubState) -> ReturnValue,
1926    {
1927        let Self { inner, .. } = self;
1928        if let Ok(mut guard) = inner.try_borrow_mut() {
1929            return operation(&mut guard);
1930        }
1931        let mut fallback: DynamicHubState = DynamicHubState {
1932            components: HashMap::new(),
1933            component_signals: HashMap::new(),
1934            pages: HashMap::new(),
1935            page_signals: HashMap::new(),
1936            routes_signal: Signal::new_detached(0),
1937            telemetry_signal: Signal::new_detached(DynamicTelemetry::default()),
1938            last_action: Signal::new_detached(None),
1939            action_handlers: Vec::new(),
1940            hot_update_worker: None,
1941            hot_update_cache_dir: None,
1942            hot_update_sandbox: WasmSandboxConfig::default(),
1943            deferred_hot_candidate: None,
1944            hot_update_status: Signal::new_detached(HotUpdateLiveStatus::default()),
1945            hot_update_connected: false,
1946            runtime_epoch: current_runtime_epoch(),
1947        };
1948        operation(&mut fallback)
1949    }
1950}
1951
1952/// Default `Lifecycle` hooks for `DynamicComponentSlot`.
1953impl Lifecycle for DynamicComponentSlot {}
1954
1955/// `Component` implementation mounting a surgically updatable component slot.
1956impl Component for DynamicComponentSlot {
1957    /// Renders the host container and subscribes ONLY to this slot's dedicated revision signal.
1958    ///
1959    /// # Arguments
1960    ///
1961    /// - `&Self` - Component slot descriptor.
1962    ///
1963    /// # Returns
1964    ///
1965    /// - `NodeId` - Mounted slot host handle.
1966    fn render(&self) -> NodeId {
1967        let mut ctx: Context = current_context();
1968        let host_style: Style = self.get_style();
1969        let Self {
1970            id, fallback, hub, ..
1971        } = self;
1972        let slot_id: String = id.clone();
1973        let node_id: Rc<dyn Fn() -> NodeId> = fallback.clone();
1974        let active_hub: DynamicUpdateHub =
1975            hub.clone().unwrap_or_else(|| ctx.get_dynamic_hub().clone());
1976        let rev_sig: Signal<u64> = active_hub.component_revision_signal(&slot_id);
1977        let effective_style: Style = if host_style == Style::default() {
1978            Style::default().column().width(Length::Percent(100.0))
1979        } else {
1980            host_style
1981        };
1982        let host: NodeId = ctx.view(effective_style);
1983        let safe_sig: Signal<SafeAreaInsets> = ctx.get_safe_area();
1984        ctx.bind_children(host, move || {
1985            let _: u64 = rev_sig.get();
1986            let mounted: NodeId = active_hub.mount_component_or_fallback(&slot_id, &node_id);
1987            if slot_id == WASM_GLOBAL_ROOT_SLOT && active_hub.component_version(&slot_id) > 0 {
1988                let safe: SafeAreaInsets = safe_sig.get();
1989                let mut ui_context: Context = current_context();
1990                let scroller: NodeId = ui_context.scroll_view(
1991                    Style::default()
1992                        .column()
1993                        .width(Length::Percent(100.0))
1994                        .height(Length::Percent(100.0))
1995                        .align(AlignItems::Center)
1996                        .background(Color::hex(0xF8FAFC))
1997                        .padding(Edges::new(
1998                            safe.get_top() + 16.0,
1999                            safe.get_right() + 16.0,
2000                            safe.get_bottom() + 24.0,
2001                            safe.get_left() + 16.0,
2002                        )),
2003                );
2004                let container: NodeId = ui_context.view(
2005                    Style::default()
2006                        .column()
2007                        .width(Length::Percent(100.0))
2008                        .max_width(Length::Px(1040.0)),
2009                );
2010                ui_context.append(container, mounted);
2011                ui_context.append(scroller, container);
2012                vec![scroller]
2013            } else {
2014                vec![mounted]
2015            }
2016        });
2017        host
2018    }
2019}
2020
2021/// Default `Lifecycle` hooks for `DynamicPageSlot`.
2022impl Lifecycle for DynamicPageSlot {}
2023
2024/// `Component` implementation mounting a surgically updatable page slot for a fixed route.
2025impl Component for DynamicPageSlot {
2026    /// Renders the page container and subscribes ONLY to this route's dedicated revision signal.
2027    ///
2028    /// # Arguments
2029    ///
2030    /// - `&Self` - Page slot descriptor.
2031    ///
2032    /// # Returns
2033    ///
2034    /// - `NodeId` - Mounted page slot host handle.
2035    fn render(&self) -> NodeId {
2036        let mut ctx: Context = current_context();
2037        let host_style: Style = self.get_style();
2038        let Self {
2039            route,
2040            fallback,
2041            hub,
2042            ..
2043        } = self;
2044        let normalized: String = normalize_dynamic_route(route);
2045        let node_id: Rc<dyn Fn() -> NodeId> = fallback.clone();
2046        let active_hub: DynamicUpdateHub =
2047            hub.clone().unwrap_or_else(|| ctx.get_dynamic_hub().clone());
2048        let rev_sig: Signal<u64> = active_hub.page_revision_signal(&normalized);
2049        let effective_style: Style = if host_style == Style::default() {
2050            Style::default().column().width(Length::Percent(100.0))
2051        } else {
2052            host_style
2053        };
2054        let host: NodeId = ctx.view(effective_style);
2055        ctx.bind_children(host, move || {
2056            let _: u64 = rev_sig.get();
2057            vec![active_hub.mount_page_or_fallback(&normalized, &node_id)]
2058        });
2059        host
2060    }
2061}
2062
2063/// Default `Lifecycle` hooks for `DynamicPageOutlet`.
2064impl Lifecycle for DynamicPageOutlet {}
2065
2066/// `Component` implementation mounting a reactive route-driven dynamic page outlet.
2067impl Component for DynamicPageOutlet {
2068    /// Renders a dynamic route outlet reacting to both route switches and live page-level updates.
2069    ///
2070    /// # Arguments
2071    ///
2072    /// - `&Self` - Page outlet descriptor.
2073    ///
2074    /// # Returns
2075    ///
2076    /// - `NodeId` - Mounted outlet host handle.
2077    fn render(&self) -> NodeId {
2078        let mut ctx: Context = current_context();
2079        let route_sig: Signal<String> = self.get_route();
2080        let host_style: Style = self.get_style();
2081        let Self { fallback, hub, .. } = self;
2082        let fb_outer: Rc<dyn Fn(&str) -> NodeId> = fallback.clone();
2083        let active_hub: DynamicUpdateHub =
2084            hub.clone().unwrap_or_else(|| ctx.get_dynamic_hub().clone());
2085        let effective_style: Style = if host_style == Style::default() {
2086            Style::default().column().width(Length::Percent(100.0))
2087        } else {
2088            host_style
2089        };
2090        let host: NodeId = ctx.view(effective_style);
2091        let scene_for_anim: SceneHandle = ctx.get_scene().clone();
2092        let prev_route_cell: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
2093        ctx.bind_children(host, move || {
2094            let active_route: String = normalize_dynamic_route(&route_sig.get());
2095            let page_rev_sig: Signal<u64> = active_hub.page_revision_signal(&active_route);
2096            let _: u64 = page_rev_sig.get();
2097            let fallback_c: Rc<dyn Fn(&str) -> NodeId> = fb_outer.clone();
2098            let route_for_fb: String = active_route.clone();
2099            let node_id: Rc<dyn Fn() -> NodeId> = Rc::new(move || fallback_c(&route_for_fb));
2100            let page_node: NodeId = active_hub.mount_page_or_fallback(&active_route, &node_id);
2101            let should_animate: bool = match prev_route_cell.try_borrow_mut() {
2102                Ok(mut slot) => {
2103                    let changed: bool = slot
2104                        .as_deref()
2105                        .map(|prev: &str| prev != active_route.as_str())
2106                        .unwrap_or(false);
2107                    *slot = Some(active_route.clone());
2108                    changed
2109                }
2110                Err(_) => false,
2111            };
2112            if should_animate {
2113                scene_for_anim.start_transition(NodeTransition::route_enter(page_node));
2114            }
2115            vec![page_node]
2116        });
2117        host
2118    }
2119}