euv-ui 0.42.0

Cross-platform UI component library and 17-scheme design system for the euv framework with pixel-consistent rendering across Web, Android, iOS, iPadOS, macOS, Windows, and Linux.
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
use super::*;

/// History stack navigation, pattern matching, lazy page lifecycle, and system-back integration for `EuvRouter`.
impl EuvRouter {
    /// Creates a new `EuvRouter` initialized at `initial_path` with `PageRetention::Freeze` as default retention.
    ///
    /// # Arguments
    ///
    /// - `&str` - Starting route path (e.g. `"/"`).
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized reactive router handle.
    #[must_use]
    pub fn new(initial_path: &str) -> Self {
        let start: String = initial_path.to_string();
        let inner: EuvRouterInner = EuvRouterInner {
            routes: Vec::new(),
            history: vec![start.clone()],
            cursor: 0,
            dynamic_hub: None,
            default_retention: PageRetention::Freeze,
        };
        Self {
            current_path: Signal::new(start),
            can_go_back: Signal::new(false),
            can_go_forward: Signal::new(false),
            history_len: Signal::new(1),
            frozen_count: Signal::new(0),
            alive_count: Signal::new(0),
            lifecycle_entries: Signal::new(Vec::new()),
            inner: Rc::new(RefCell::new(inner)),
        }
    }

    /// Configures the default `PageRetention` policy for routes whose components do not specify an override.
    ///
    /// # Arguments
    ///
    /// - `Self` - Source router.
    /// - `PageRetention` - Default retention strategy (`Destroy`, `Freeze`, or `Alive`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated router.
    #[must_use]
    pub fn with_default_retention(self, retention: PageRetention) -> Self {
        if let Ok(mut guard) = self.get_inner().try_borrow_mut() {
            guard.set_default_retention(retention);
        }
        self
    }

    /// Registers a declarative route `pattern` (supporting `:param` segments) with a lazy page builder.
    ///
    /// # Arguments
    ///
    /// - `Self` - Source router.
    /// - `&str` - Route pattern (e.g. `"/media"` or `"/items/:id"`).
    /// - `&str` - Human-readable page title.
    /// - `F` - Lazy page builder receiving `&EuvRouteMatch`.
    ///
    /// # Returns
    ///
    /// - `Self` - Router with the route registered.
    #[must_use]
    pub fn route<F>(self, pattern: &str, title: &str, builder: F) -> Self
    where
        F: Fn(&EuvRouteMatch) -> NodeId + 'static,
    {
        if let Ok(mut guard) = self.get_inner().try_borrow_mut() {
            guard.get_mut_routes().push(EuvRouteDef {
                pattern: pattern.to_string(),
                title: title.to_string(),
                retention: None,
                builder: Rc::new(builder),
            });
        }
        self
    }

    /// Registers a declarative route with an explicit `PageRetention` policy override (`Destroy`, `Freeze`, or `Alive`).
    ///
    /// # Arguments
    ///
    /// - `Self` - Source router.
    /// - `&str` - Route pattern.
    /// - `&str` - Human-readable page title.
    /// - `PageRetention` - Explicit retention strategy when leaving this route.
    /// - `F` - Lazy page builder receiving `&EuvRouteMatch`.
    ///
    /// # Returns
    ///
    /// - `Self` - Router with the route registered.
    #[must_use]
    pub fn route_with_retention<F>(
        self,
        pattern: &str,
        title: &str,
        retention: PageRetention,
        builder: F,
    ) -> Self
    where
        F: Fn(&EuvRouteMatch) -> NodeId + 'static,
    {
        if let Ok(mut guard) = self.get_inner().try_borrow_mut() {
            guard.get_mut_routes().push(EuvRouteDef {
                pattern: pattern.to_string(),
                title: title.to_string(),
                retention: Some(retention),
                builder: Rc::new(builder),
            });
        }
        self
    }

    /// Registers a typed `Component` page factory whose `Lifecycle::retention_policy` drives freeze/destroy/alive behavior.
    ///
    /// # Arguments
    ///
    /// - `Self` - Source router.
    /// - `&str` - Route pattern.
    /// - `&str` - Human-readable page title.
    /// - `F` - Lazy factory constructing a `Component` page instance.
    ///
    /// # Returns
    ///
    /// - `Self` - Router with the typed component route registered.
    #[must_use]
    pub fn route_component<C, F>(self, pattern: &str, title: &str, factory: F) -> Self
    where
        C: Component,
        F: Fn(&EuvRouteMatch) -> C + 'static,
    {
        self.route(pattern, title, move |matched: &EuvRouteMatch| {
            factory(matched).mount()
        })
    }

    /// Attaches an optional `DynamicUpdateHub` so OTA hot-updated routes seamlessly override local builders.
    ///
    /// # Arguments
    ///
    /// - `Self` - Source router.
    /// - `DynamicUpdateHub` - Live dynamic update hub.
    ///
    /// # Returns
    ///
    /// - `Self` - Router connected to `hub`.
    #[must_use]
    pub fn with_dynamic_hub(self, hub: DynamicUpdateHub) -> Self {
        if let Ok(mut guard) = self.get_inner().try_borrow_mut() {
            guard.dynamic_hub = Some(hub);
        }
        self
    }

    /// Synchronizes reactive router signals after any history mutation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Router reference.
    fn sync_signals(&self) {
        let snapshot: Option<(String, bool, bool, usize)> =
            self.get_inner()
                .try_borrow()
                .ok()
                .map(|guard: Ref<'_, EuvRouterInner>| {
                    let path: String = guard
                        .get_history()
                        .get(guard.get_cursor())
                        .cloned()
                        .unwrap_or_else(|| "/".to_string());
                    let len: usize = guard.get_history().len();
                    let back: bool = guard.get_cursor() > 0;
                    let fwd: bool = guard.get_cursor() + 1 < len;
                    (path, back, fwd, len)
                });
        if let Some((path, back, fwd, len)) = snapshot {
            batch(|| {
                let _: bool = self.get_current_path().set_if_changed(path);
                let _: bool = self.get_can_go_back().set_if_changed(back);
                let _: bool = self.get_can_go_forward().set_if_changed(fwd);
                let _: bool = self.get_history_len().set_if_changed(len);
            });
        }
    }

    /// Publishes live cached route lifecycle telemetry (`frozen_count`, `alive_count`, `lifecycle_entries`).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Router reference.
    /// - `&HashMap<String, EuvCachedPage>` - Active outlet page cache.
    fn publish_lifecycle_telemetry(&self, cache: &HashMap<String, EuvCachedPage>) {
        let mut frozen: usize = 0;
        let mut alive: usize = 0;
        let mut entries: Vec<EuvRouteLifecycleEntry> = Vec::with_capacity(cache.len());
        for (path, entry) in cache.iter() {
            if entry.phase == LifecyclePhase::Frozen {
                frozen += 1;
            } else if entry.phase == LifecyclePhase::Mounted
                && entry.retention == PageRetention::Alive
            {
                alive += 1;
            }
            entries.push(EuvRouteLifecycleEntry {
                path: path.clone(),
                retention: entry.retention,
                phase: entry.phase,
                activations: entry.activations,
            });
        }
        entries.sort_by(|a: &EuvRouteLifecycleEntry, b: &EuvRouteLifecycleEntry| {
            a.get_path().cmp(b.get_path())
        });
        let frozen_sig: Signal<usize> = self.get_frozen_count();
        let alive_sig: Signal<usize> = self.get_alive_count();
        let entries_sig: Signal<Vec<EuvRouteLifecycleEntry>> = self.get_lifecycle_entries();
        batch(|| {
            let _: bool = frozen_sig.set_if_changed(frozen);
            let _: bool = alive_sig.set_if_changed(alive);
            let _: bool = entries_sig.set_if_changed(entries);
        });
    }

    /// Pushes `path` onto the navigation history stack (no-op if already on `path`).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Router reference.
    /// - `&str` - Destination route path.
    pub fn push(&self, path: &str) {
        let mut changed: bool = false;
        if let Ok(mut guard) = self.get_inner().try_borrow_mut() {
            let cur: String = guard
                .get_history()
                .get(guard.get_cursor())
                .cloned()
                .unwrap_or_default();
            if cur != path {
                let next_idx: usize = guard.get_cursor() + 1;
                guard.get_mut_history().truncate(next_idx);
                guard.get_mut_history().push(path.to_string());
                guard.set_cursor(next_idx);
                changed = true;
            }
        }
        if changed {
            self.sync_signals();
        }
    }

    /// Replaces the current history entry with `path` without growing stack depth.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Router reference.
    /// - `&str` - Replacement route path.
    pub fn replace(&self, path: &str) {
        if let Ok(mut guard) = self.get_inner().try_borrow_mut() {
            let idx: usize = guard.get_cursor();
            if let Some(slot) = guard.get_mut_history().get_mut(idx) {
                *slot = path.to_string();
            } else {
                guard.get_mut_history().push(path.to_string());
                guard.set_cursor(0);
            }
        }
        self.sync_signals();
    }

    /// Navigates one step backward in history if available.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Router reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if navigated back; `false` if already at root.
    pub fn back(&self) -> bool {
        let moved: bool = if let Ok(mut guard) = self.get_inner().try_borrow_mut() {
            if guard.get_cursor() > 0 {
                let prev: usize = guard.get_cursor() - 1;
                guard.set_cursor(prev);
                true
            } else {
                false
            }
        } else {
            false
        };
        if moved {
            self.sync_signals();
        }
        moved
    }

    /// Navigates one step forward in history if available.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Router reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if navigated forward; `false` if at head of stack.
    pub fn forward(&self) -> bool {
        let moved: bool = if let Ok(mut guard) = self.get_inner().try_borrow_mut() {
            if guard.get_cursor() + 1 < guard.get_history().len() {
                let next: usize = guard.get_cursor() + 1;
                guard.set_cursor(next);
                true
            } else {
                false
            }
        } else {
            false
        };
        if moved {
            self.sync_signals();
        }
        moved
    }

    /// Unified OS Back handler: closes topmost overlay in `EuvOverlayStack` first, then pops router history.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Router reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when consumed by an overlay or route pop; `false` when at app root.
    pub fn handle_system_back(&self) -> bool {
        if EuvOverlayStack::dismiss_top() {
            return true;
        }
        self.back()
    }

    /// Parses and matches `raw_path` against registered routes, extracting `:param`, `?query`, and optional retention override.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Router reference.
    /// - `&str` - Raw path possibly containing `?k=v&k2=v2`.
    ///
    /// # Returns
    ///
    /// - `EuvRouteResolvePolicy` - Match metadata, optional builder, and optional retention policy.
    #[must_use]
    pub fn resolve_with_policy(&self, raw_path: &str) -> EuvRouteResolvePolicy {
        let (clean_path, query_part): (&str, &str) = match raw_path.split_once('?') {
            Some((p, q)) => (p, q),
            None => (raw_path, ""),
        };
        let mut query: HashMap<String, String> = HashMap::new();
        for pair in query_part.split('&') {
            if let Some((k, v)) = pair.split_once('=')
                && !k.is_empty()
            {
                let _: Option<String> = query.insert(k.to_string(), v.to_string());
            }
        }
        let path_segs: Vec<&str> = clean_path
            .split('/')
            .filter(|s: &&str| !s.is_empty())
            .collect();
        if let Ok(guard) = self.get_inner().try_borrow() {
            for def in guard.get_routes().iter() {
                let pat_segs: Vec<&str> = def
                    .get_pattern()
                    .split('/')
                    .filter(|s: &&str| !s.is_empty())
                    .collect();
                if pat_segs.len() != path_segs.len() {
                    continue;
                }
                let mut params: HashMap<String, String> = HashMap::new();
                let mut matched: bool = true;
                for (pat, seg) in pat_segs.iter().zip(path_segs.iter()) {
                    if let Some(key) = pat.strip_prefix(':') {
                        let _: Option<String> = params.insert(key.to_string(), (*seg).to_string());
                    } else if pat != seg {
                        matched = false;
                        break;
                    }
                }
                if matched {
                    let EuvRouteDef {
                        builder, retention, ..
                    } = def;
                    return (
                        EuvRouteMatch {
                            path: clean_path.to_string(),
                            pattern: def.get_pattern().clone(),
                            title: def.get_title().clone(),
                            params,
                            query,
                        },
                        Some(Rc::clone(builder)),
                        *retention,
                    );
                }
            }
        }
        (
            EuvRouteMatch {
                path: clean_path.to_string(),
                pattern: String::new(),
                title: String::new(),
                params: HashMap::new(),
                query,
            },
            None,
            None,
        )
    }

    /// Parses and matches `raw_path` against registered routes, extracting `:param` and `?query` values.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Router reference.
    /// - `&str` - Raw path possibly containing `?k=v&k2=v2`.
    ///
    /// # Returns
    ///
    /// - `(EuvRouteMatch, Option<EuvRouteBuilder>)` - Parsed match metadata and matched builder if found.
    #[must_use]
    pub fn resolve(&self, raw_path: &str) -> (EuvRouteMatch, Option<EuvRouteBuilder>) {
        let (matched, builder, _): (
            EuvRouteMatch,
            Option<EuvRouteBuilder>,
            Option<PageRetention>,
        ) = self.resolve_with_policy(raw_path);
        (matched, builder)
    }

    /// Creates a reactive `EuvRouterOutlet` bound to this router with a fallback builder.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Router reference.
    /// - `F` - Fallback page builder for unmatched paths.
    ///
    /// # Returns
    ///
    /// - `EuvRouterOutlet` - Component-backed reactive router outlet.
    #[must_use]
    pub fn outlet<F>(&self, fallback: F) -> EuvRouterOutlet
    where
        F: Fn(&EuvRouteMatch) -> NodeId + 'static,
    {
        EuvRouterOutlet {
            router: self.clone(),
            fallback: Rc::new(fallback),
            theme: None,
            double_back_exit: false,
            exit_prompt: DOUBLE_BACK_EXIT_PROMPT.to_string(),
        }
    }
}

/// Builder modifiers for `EuvRouterOutlet`.
impl EuvRouterOutlet {
    /// Connects a reactive `UiThemeState` so frozen pages incur zero work on theme switches and refresh cleanly when resumed.
    ///
    /// # Arguments
    ///
    /// - `Self` - Source outlet.
    /// - `UiThemeState` - Reactive theme state.
    ///
    /// # Returns
    ///
    /// - `Self` - Theme-aware router outlet.
    #[must_use]
    pub fn with_theme(mut self, theme: UiThemeState) -> Self {
        self.set_theme(Some(theme));
        self
    }

    /// Enables standard app double-back-to-exit behavior at the root route when no overlay or previous route remains.
    ///
    /// # Arguments
    ///
    /// - `Self` - Source outlet.
    /// - `bool` - Whether pressing Back twice consecutively at the root route shows a bottom prompt then exits the app.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated router outlet.
    #[must_use]
    pub fn with_double_back_exit(mut self, enabled: bool) -> Self {
        self.set_double_back_exit(enabled);
        self
    }

    /// Customizes the bottom prompt text displayed on the first Back press at the root route.
    ///
    /// # Arguments
    ///
    /// - `Self` - Source outlet.
    /// - `String` - Prompt copy displayed at the bottom of the app.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated router outlet.
    #[must_use]
    pub fn with_exit_prompt(mut self, prompt: String) -> Self {
        self.set_exit_prompt(prompt);
        self
    }
}

/// Declarative `#[component]` implementation for `EuvRouterOutlet` providing lazy page mounting, `PageRetention` (`Destroy`/`Freeze`/`Alive`), cross-page coalesced resume, and automatic OS Back + double-back-to-exit wiring.
#[component]
/// Inherent implementation of [`EuvRouterOutlet`].
impl EuvRouterOutlet {
    /// Renders the lazy lifecycle-managed router outlet into the ambient `Context`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Router outlet reference.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Mounted router outlet container handle.
    fn render(&self) -> NodeId {
        let mut ctx: Context = current_context();
        let host: NodeId = ctx.view(
            Style::default()
                .column()
                .width(Length::Percent(100.0))
                .align(AlignItems::Center)
                .gap(SPACE_LG),
        );
        let router: EuvRouter = self.get_router().clone();
        let fallback: EuvRouteBuilder = {
            let Self { fallback, .. } = self;
            Rc::clone(fallback)
        };
        let theme_opt: Option<UiThemeState> = {
            let Self { theme, .. } = self;
            theme.clone()
        };
        let double_back_enabled: bool = self.get_double_back_exit();
        let exit_prompt_text: String = self.get_exit_prompt().clone();
        let exit_toast_opt: Option<NodeId> = if double_back_enabled {
            let safe_area_sig: Signal<SafeAreaInsets> = ctx.get_safe_area();
            let toast_text_clone: String = exit_prompt_text.clone();
            let toast_node: NodeId = view! {
                portal {
                    display: Display::None
                    position: Position::Fixed
                    inset: (
                        None,
                        Some(0.0),
                        Some(EXIT_TOAST_BOTTOM_OFFSET + safe_area_sig.get_untracked().get_bottom()),
                        Some(0.0)
                    )
                    width: Length::Percent(100.0)
                    justify: JustifyContent::Center
                    align: AlignItems::Center
                    pointer_events: PointerEvents::None
                    z_index: Z_INDEX_EXIT_TOAST
                    row {
                        padding: Edges::symmetric(10.0, 20.0)
                        background: Color::rgba(17, 24, 39, 236)
                        border: (1.0, Color::rgba(255, 255, 255, 36))
                        radius: 999.0
                        shadow: Shadow::new(0.0, 8.0, 24.0, 0.0, Color::rgba(0, 0, 0, 84))
                        text {
                            font_size: 13.5
                            font_weight: FontWeight::Medium
                            color: Color::rgb(248, 250, 252)
                            text_align: TextAlign::Center
                            { toast_text_clone }
                        }
                    }
                }
            };
            ctx.append(host, toast_node);
            Some(toast_node)
        } else {
            None
        };
        let router_back: EuvRouter = router.clone();
        let sys_back_sig: Signal<u64> = ctx.get_system_back();
        let last_back_seq: Rc<Cell<u64>> = Rc::new(Cell::new(sys_back_sig.get_untracked()));
        let armed_exit_at_ms: Rc<Cell<Option<u64>>> = Rc::new(Cell::new(None));
        let armed_exit_route: Rc<Cell<Option<u64>>> = Rc::clone(&armed_exit_at_ms);
        let (hub_opt, default_ret): (Option<DynamicUpdateHub>, PageRetention) = router
            .get_inner()
            .try_borrow()
            .ok()
            .map(|g: Ref<'_, EuvRouterInner>| (g.dynamic_hub.clone(), g.get_default_retention()))
            .unwrap_or((None, PageRetention::Freeze));
        let path_sig: Signal<String> = router.get_current_path();
        let ctx_spawn: Context = ctx.clone();
        let ctx_back: Context = ctx.clone();
        let scene: SceneHandle = ctx.get_scene().clone();
        let scene_back: SceneHandle = scene.clone();
        let cache: Rc<RefCell<HashMap<String, EuvCachedPage>>> =
            Rc::new(RefCell::new(HashMap::new()));
        let active_key_cell: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
        let cache_cleanup: Rc<RefCell<HashMap<String, EuvCachedPage>>> = Rc::clone(&cache);
        let (outlet_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
            on_cleanup(move || {
                if let Ok(mut map) = cache_cleanup.try_borrow_mut() {
                    for (_, entry) in map.drain() {
                        entry.scope.dispose();
                    }
                }
            });
            let _: Effect = Effect::new(move || {
                let seq: u64 = sys_back_sig.get();
                if seq != last_back_seq.replace(seq) {
                    let consumed: bool = router_back.handle_system_back();
                    if consumed {
                        armed_exit_at_ms.set(None);
                        if let Some(tid) = exit_toast_opt {
                            scene_back.with_write(
                                |tree: &mut SceneTree| {
                                    if let Some(n) = tree.get_node_mut(tid) {
                                        let mut st: Style = n.get_style();
                                        st.get_mut_layout().set_display(Display::None);
                                        n.set_style(st);
                                    }
                                    tree.cancel_subtree_transitions(tid);
                                    tree.mark_dirty(tid, DIRTY_LAYOUT | DIRTY_PAINT);
                                },
                                (),
                            );
                        }
                    } else if double_back_enabled {
                        let now_ms: u64 = ctx_back.elapsed_ms();
                        let second_press: bool = armed_exit_at_ms
                            .get()
                            .map(|prev: u64| {
                                now_ms.saturating_sub(prev) <= DOUBLE_BACK_EXIT_WINDOW_MS
                            })
                            .unwrap_or(false);
                        if second_press {
                            armed_exit_at_ms.set(None);
                            if let Some(tid) = exit_toast_opt {
                                scene_back.with_write(
                                    |tree: &mut SceneTree| {
                                        if let Some(n) = tree.get_node_mut(tid) {
                                            let mut st: Style = n.get_style();
                                            st.get_mut_layout().set_display(Display::None);
                                            n.set_style(st);
                                        }
                                        tree.cancel_subtree_transitions(tid);
                                        tree.mark_dirty(tid, DIRTY_LAYOUT | DIRTY_PAINT);
                                    },
                                    (),
                                );
                            }
                            ctx_back.request_exit();
                        } else {
                            armed_exit_at_ms.set(Some(now_ms));
                            let handled_by_os: bool =
                                dispatch_native_action(NATIVE_ACTION_TOAST, &exit_prompt_text, "");
                            if !handled_by_os && let Some(tid) = exit_toast_opt {
                                scene_back.with_write(
                                    |tree: &mut SceneTree| {
                                        if let Some(n) = tree.get_node_mut(tid) {
                                            let mut st: Style = n.get_style();
                                            st.get_mut_layout().set_display(Display::Flex);
                                            st.get_mut_paint().set_opacity(1.0);
                                            n.set_style(st);
                                        }
                                        tree.mark_dirty(tid, DIRTY_LAYOUT | DIRTY_PAINT);
                                    },
                                    (),
                                );
                                scene_back.start_transition(
                                    NodeTransition::fade(
                                        tid,
                                        1.0,
                                        0.0,
                                        DOUBLE_BACK_TOAST_FADE_SECS,
                                        true,
                                    )
                                    .with_delay(DOUBLE_BACK_TOAST_HOLD_SECS)
                                    .with_easing(Easing::EaseOutCubic),
                                );
                            }
                        }
                    }
                }
            });
            Effect::new(move || {
                let active_path: String = path_sig.get();
                let cur_theme: Option<(DesignScheme, ThemeMode)> =
                    theme_opt.as_ref().map(|t: &UiThemeState| {
                        let _tok: ThemeTokens = t.get_tokens().get();
                        (t.get_scheme().get_untracked(), t.get_mode().get_untracked())
                    });
                let cur_dyn_rev: u64 = hub_opt
                    .as_ref()
                    .map(|h: &DynamicUpdateHub| {
                        let _routes_rev: u64 = h.routes_signal().get();
                        h.page_revision_signal(&active_path).get()
                    })
                    .unwrap_or(0);
                let prev_path_opt: Option<String> = active_key_cell
                    .try_borrow()
                    .ok()
                    .and_then(|g: Ref<'_, Option<String>>| g.clone());
                let route_changed: bool = prev_path_opt.as_deref() != Some(active_path.as_str());
                if route_changed {
                    armed_exit_route.set(None);
                    if let Some(tid) = exit_toast_opt {
                        scene.with_write(
                            |tree: &mut SceneTree| {
                                if let Some(n) = tree.get_node_mut(tid)
                                    && n.get_style().get_layout().get_display() != Display::None
                                {
                                    let mut st: Style = n.get_style();
                                    st.get_mut_layout().set_display(Display::None);
                                    n.set_style(st);
                                    tree.cancel_subtree_transitions(tid);
                                    tree.mark_dirty(tid, DIRTY_LAYOUT | DIRTY_PAINT);
                                }
                            },
                            (),
                        );
                    }
                }
                if route_changed && let Some(prev_path) = prev_path_opt {
                    let leave_entry: Option<EuvCachedPage> = cache.try_borrow_mut().ok().and_then(
                        |mut map: RefMut<'_, HashMap<String, EuvCachedPage>>| {
                            let ret: PageRetention = map
                                .get(&prev_path)
                                .map(|e: &EuvCachedPage| e.retention)
                                .unwrap_or(default_ret);
                            if ret == PageRetention::Destroy {
                                map.remove(&prev_path)
                            } else {
                                if let Some(entry) = map.get_mut(&prev_path) {
                                    entry.phase = if ret == PageRetention::Freeze {
                                        LifecyclePhase::Frozen
                                    } else {
                                        LifecyclePhase::Mounted
                                    };
                                    Some(entry.clone())
                                } else {
                                    None
                                }
                            }
                        },
                    );
                    if let Some(prev_entry) = leave_entry {
                        match prev_entry.retention {
                            PageRetention::Destroy => {
                                scene.remove_and_dispose_child(host, prev_entry.wrapper);
                                prev_entry.scope.dispose();
                            }
                            PageRetention::Freeze => {
                                prev_entry.scope.freeze();
                                scene.freeze_subtree(prev_entry.wrapper);
                            }
                            PageRetention::Alive => {
                                scene.with_write(
                                    |tree: &mut SceneTree| {
                                        if let Some(n) = tree.get_node_mut(prev_entry.wrapper) {
                                            let mut st: Style = n.get_style();
                                            st.get_mut_layout().set_display(Display::None);
                                            n.set_style(st);
                                        }
                                        tree.mark_dirty(
                                            prev_entry.wrapper,
                                            DIRTY_LAYOUT | DIRTY_PAINT,
                                        );
                                    },
                                    (),
                                );
                            }
                        }
                    }
                }
                let cached_hit: Option<EuvCachedPage> = cache.try_borrow().ok().and_then(
                    |map: Ref<'_, HashMap<String, EuvCachedPage>>| map.get(&active_path).cloned(),
                );
                let reusable: bool = cached_hit
                    .as_ref()
                    .map(|e: &EuvCachedPage| {
                        e.theme_key == cur_theme && e.dynamic_rev == cur_dyn_rev
                    })
                    .unwrap_or(false);
                if reusable && let Some(hit) = cached_hit {
                    if hit.phase == LifecyclePhase::Frozen {
                        scene.resume_subtree(hit.wrapper);
                        hit.scope.resume();
                    } else if hit.phase != LifecyclePhase::Active {
                        scene.with_write(
                            |tree: &mut SceneTree| {
                                if let Some(n) = tree.get_node_mut(hit.wrapper) {
                                    let mut st: Style = n.get_style();
                                    if st.get_layout().get_display() == Display::None {
                                        st.get_mut_layout().set_display(Display::Flex);
                                        n.set_style(st);
                                    }
                                }
                                tree.mark_dirty(hit.wrapper, DIRTY_LAYOUT | DIRTY_PAINT);
                            },
                            (),
                        );
                    }
                    if let Ok(mut map) = cache.try_borrow_mut()
                        && let Some(entry) = map.get_mut(&active_path)
                    {
                        entry.phase = LifecyclePhase::Active;
                        entry.activations = entry.activations.saturating_add(1);
                    }
                    scene.activate_subtree(hit.page_node);
                    if route_changed {
                        scene.start_transition(NodeTransition::route_enter(hit.page_node));
                    }
                } else {
                    if let Some(stale) = cached_hit {
                        if let Ok(mut map) = cache.try_borrow_mut() {
                            let _: Option<EuvCachedPage> = map.remove(&active_path);
                        }
                        scene.remove_and_dispose_child(host, stale.wrapper);
                        stale.scope.dispose();
                    }
                    let (matched, builder_opt, route_ret): (
                        EuvRouteMatch,
                        Option<EuvRouteBuilder>,
                        Option<PageRetention>,
                    ) = router.resolve_with_policy(&active_path);
                    let fb_c: EuvRouteBuilder = Rc::clone(&fallback);
                    let hub_c: Option<DynamicUpdateHub> = hub_opt.clone();
                    let active_p_c: String = active_path.clone();
                    let (page_scope, page_node): (Scope, NodeId) = Scope::run(|_: Scope| {
                        with_context(ctx_spawn.clone(), || {
                            if let Some(hub) = hub_c.as_ref() {
                                let local_fb: Rc<dyn Fn() -> NodeId> = Rc::new(move || {
                                    if let Some(builder) = builder_opt.as_ref() {
                                        builder(&matched)
                                    } else {
                                        fb_c(&matched)
                                    }
                                });
                                hub.mount_page_or_fallback(&active_p_c, &local_fb)
                            } else if let Some(builder) = builder_opt {
                                builder(&matched)
                            } else {
                                fb_c(&matched)
                            }
                        })
                    });
                    let comp_ret: Option<PageRetention> = scene.with_read(
                        |tree: &SceneTree| {
                            tree.get_node(page_node).and_then(|n: &SceneNode| {
                                n.lifecycle_observers()
                                    .last()
                                    .map(|h: &Rc<dyn Lifecycle>| h.retention_policy())
                            })
                        },
                        None,
                    );
                    let resolved_ret: PageRetention = route_ret.or(comp_ret).unwrap_or(default_ret);
                    let wrapper: NodeId = scene.with_write(
                        |tree: &mut SceneTree| {
                            let w: NodeId = tree.create_view(
                                Style::default()
                                    .column()
                                    .width(Length::Percent(100.0))
                                    .align(AlignItems::Center)
                                    .gap(SPACE_LG),
                            );
                            tree.append_child(w, page_node);
                            tree.append_child(host, w);
                            w
                        },
                        NodeId::default(),
                    );
                    if let Ok(mut map) = cache.try_borrow_mut() {
                        let _: Option<EuvCachedPage> = map.insert(
                            active_path.clone(),
                            EuvCachedPage {
                                wrapper,
                                page_node,
                                scope: page_scope,
                                retention: resolved_ret,
                                phase: LifecyclePhase::Active,
                                theme_key: cur_theme,
                                dynamic_rev: cur_dyn_rev,
                                activations: 1,
                            },
                        );
                    }
                    scene.activate_subtree(page_node);
                    let is_initial: bool = active_key_cell
                        .try_borrow()
                        .ok()
                        .map(|g: Ref<'_, Option<String>>| g.is_none())
                        .unwrap_or(true);
                    if !is_initial {
                        scene.start_transition(NodeTransition::route_enter(page_node));
                    }
                }
                if let Ok(mut active_slot) = active_key_cell.try_borrow_mut() {
                    *active_slot = Some(active_path);
                }
                if let Ok(map) = cache.try_borrow() {
                    router.publish_lifecycle_telemetry(&map);
                }
            })
        });
        ctx.get_scene().with_write(
            |tree: &mut SceneTree| {
                tree.attach_scope(host, outlet_scope);
            },
            (),
        );
        host
    }
}

/// Declarative `#[component]` implementation for `EuvLink`.
#[component]
/// Inherent implementation of [`EuvLink`].
impl EuvLink {
    /// Renders a clickable link button that pushes `to` onto `router`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Link component reference.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Mounted link node handle.
    fn render(&self) -> NodeId {
        let tokens: ThemeTokens = self.get_tokens();
        let to: String = self.get_to().clone();
        let label: String = self.get_label().clone();
        let router: EuvRouter = self.get_router().clone();
        EuvButton::new(label, tokens)
            .ghost()
            .sm()
            .on_click(move |_: &UiEvent| {
                router.push(&to);
            })
            .mount()
    }
}