euv-ui 0.48.10

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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
use super::*;

/// Returns the thread-local reactive fullscreen signal, resetting refcount cleanly if the reactive runtime was recreated.
///
/// # Returns
///
/// - `Signal<bool>` - Live reactive signal reporting whether any fullscreen portal is active.
fn fullscreen_signal() -> Signal<bool> {
    FULLSCREEN_ACTIVE_SIG.with(|slot: &RefCell<Option<Signal<bool>>>| {
        if let Ok(guard) = slot.try_borrow()
            && let Some(sig) = *guard
            && untracked(|| sig.try_get().is_some())
        {
            return sig;
        }
        FULLSCREEN_DEPTH.with(|depth: &Cell<usize>| depth.set(0));
        let fresh: Signal<bool> = Signal::new(false);
        if let Ok(mut guard) = slot.try_borrow_mut() {
            *guard = Some(fresh);
        }
        fresh
    })
}

/// Returns the shared reactive fullscreen signal observed by `EuvAppShell` and fullscreen-aware components.
///
/// # Returns
///
/// - `Signal<bool>` - Reactive fullscreen active flag (`true` while one or more fullscreen portals are open).
#[must_use]
pub fn use_fullscreen_active() -> Signal<bool> {
    fullscreen_signal()
}

/// Returns whether any fullscreen portal is currently active without creating a reactive dependency.
///
/// # Returns
///
/// - `bool` - `true` while fullscreen depth is greater than zero.
#[must_use]
pub fn is_fullscreen_active() -> bool {
    let sig: Signal<bool> = fullscreen_signal();
    untracked(|| sig.try_get()).unwrap_or(false)
}

/// Registers the live application `Context` so UI fullscreen transitions stay synchronized with `Context::immersive_fullscreen`.
///
/// Installs a single deduplicated root-attached observer so external fullscreen exits (e.g. browser `Esc`/`fullscreenchange` or OS exit) automatically dismiss all open fullscreen portals and restore pre-fullscreen inline layouts.
///
/// # Arguments
///
/// - `&Context` - Live application context handle.
pub fn bind_fullscreen_context(ctx: &Context) {
    FULLSCREEN_CTX_HANDLE.with(|slot: &RefCell<Option<Context>>| {
        if let Ok(mut guard) = slot.try_borrow_mut() {
            *guard = Some(ctx.clone());
        }
    });
    let ctx_fs_sig: Signal<bool> = ctx.immersive_fullscreen_signal();
    let target_id: SignalId = ctx_fs_sig.id();
    let already_watching: bool =
        FULLSCREEN_WATCHER_GUARD.with(|slot: &RefCell<Option<FullscreenWatcherGuard>>| {
            slot.try_borrow()
                .ok()
                .and_then(|guard: Ref<'_, Option<FullscreenWatcherGuard>>| {
                    guard.as_ref().map(|entry: &FullscreenWatcherGuard| {
                        entry.signal_id == target_id && entry.alive.get()
                    })
                })
                .unwrap_or(false)
        });
    if already_watching {
        return;
    }
    let alive: Rc<Cell<bool>> = Rc::new(Cell::new(true));
    let alive_cleanup: Rc<Cell<bool>> = Rc::clone(&alive);
    let prev_ctx_fs: Cell<bool> = Cell::new(untracked(|| ctx_fs_sig.try_get()).unwrap_or(false));
    let (watch_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
        on_cleanup(move || {
            alive_cleanup.set(false);
        });
        Effect::new(move || {
            let cur: bool = ctx_fs_sig.get();
            let was: bool = prev_ctx_fs.replace(cur);
            if was && !cur {
                let _: usize = sync_external_fullscreen_exit();
            }
        })
    });
    FULLSCREEN_WATCHER_GUARD.with(|slot: &RefCell<Option<FullscreenWatcherGuard>>| {
        if let Ok(mut guard) = slot.try_borrow_mut() {
            *guard = Some(FullscreenWatcherGuard {
                signal_id: target_id,
                alive,
            });
        }
    });
    ctx.get_scene().with_write(
        |tree: &mut SceneTree| {
            let root: NodeId = tree.get_root();
            tree.attach_scope(root, watch_scope);
        },
        (),
    );
}

/// Returns the currently bound live `Context` if its reactive runtime is still active.
///
/// # Returns
///
/// - `Option<Context>` - Bound live context, or `None` if unbound or disposed.
fn live_fullscreen_context() -> Option<Context> {
    FULLSCREEN_CTX_HANDLE.with(|slot: &RefCell<Option<Context>>| {
        let candidate: Option<Context> = slot
            .try_borrow()
            .ok()
            .and_then(|guard: Ref<'_, Option<Context>>| guard.clone());
        candidate.filter(|ctx: &Context| {
            untracked(|| ctx.immersive_fullscreen_signal().try_get().is_some())
        })
    })
}

/// Verifies that `portal` is a live, visible, non-empty fullscreen portal in `tree` with no hidden ancestor.
///
/// # Arguments
///
/// - `&SceneTree` - Retained scene tree.
/// - `NodeId` - Fullscreen portal node handle.
///
/// # Returns
///
/// - `bool` - `true` only when `portal` is mounted as `NodeKind::Portal`, visible (`Display != None`, `opacity > 0.0`), has children, and has no hidden or zero-opacity ancestor.
#[must_use]
pub fn is_fullscreen_portal_visible(tree: &SceneTree, portal: NodeId) -> bool {
    if portal == NodeId::default() {
        return false;
    }
    let Some(node) = tree.get_node(portal) else {
        return false;
    };
    if !matches!(node.get_kind(), NodeKind::Portal) {
        return false;
    }
    if node.style_ref().get_layout().get_display() == Display::None
        || node.style_ref().get_paint().get_opacity() <= 0.0
        || !tree.has_children(portal)
    {
        return false;
    }
    let mut cur: Option<NodeId> = node.parent_id();
    while let Some(anc_id) = cur {
        let Some(anc) = tree.get_node(anc_id) else {
            return false;
        };
        if anc.style_ref().get_layout().get_display() == Display::None
            || anc.style_ref().get_paint().get_opacity() <= 0.0
        {
            return false;
        }
        cur = anc.parent_id();
    }
    true
}

/// Enters OS immersive fullscreen strictly when `portal` is verified live and visible in `ctx`'s scene tree.
///
/// Guarantees strong 1:1 consistency between fullscreen component visibility and system fullscreen state: if the portal failed to mount, was hidden, or has no children, system fullscreen is not invoked.
///
/// # Arguments
///
/// - `&Context` - Live application context handle.
/// - `NodeId` - Fullscreen portal node handle expected to be visible.
///
/// # Returns
///
/// - `bool` - `true` when `portal` is verified visible and fullscreen entry succeeded; `false` otherwise.
#[must_use]
pub fn enter_fullscreen_for_portal(ctx: &Context, portal: NodeId) -> bool {
    bind_fullscreen_context(ctx);
    let visible: bool = ctx.get_scene().with_read(
        |tree: &SceneTree| is_fullscreen_portal_visible(tree, portal),
        false,
    );
    if !visible {
        return false;
    }
    enter_fullscreen();
    true
}

/// Increments the global fullscreen depth counter, hiding shell navigation chrome and requesting OS immersive fullscreen on `0 -> 1`.
pub fn enter_fullscreen() {
    let sig: Signal<bool> = fullscreen_signal();
    let prev: usize = FULLSCREEN_DEPTH.with(|depth: &Cell<usize>| {
        let cur: usize = depth.get();
        depth.set(cur.saturating_add(1));
        cur
    });
    if let Some(ctx) = live_fullscreen_context() {
        ctx.enter_immersive_fullscreen();
    }
    if prev == 0 {
        let _: bool = sig.set_if_changed(true);
        let _: bool = dispatch_native_action(NATIVE_ACTION_FULLSCREEN, FULLSCREEN_ACTION_ON, "");
    }
}

/// Decrements the global fullscreen depth counter, restoring shell navigation chrome, dismissing any remaining fullscreen portals, and exiting OS immersive fullscreen on `1 -> 0`.
pub fn exit_fullscreen() {
    let sig: Signal<bool> = fullscreen_signal();
    let prev: usize = FULLSCREEN_DEPTH.with(|depth: &Cell<usize>| {
        let cur: usize = depth.get();
        depth.set(cur.saturating_sub(1));
        cur
    });
    if let Some(ctx) = live_fullscreen_context() {
        ctx.exit_immersive_fullscreen();
    }
    if prev == 1 {
        let _: bool = sig.set_if_changed(false);
        let _: usize = EuvOverlayStack::dismiss_fullscreen();
        let _: bool = dispatch_native_action(NATIVE_ACTION_FULLSCREEN, FULLSCREEN_ACTION_OFF, "");
        notify_frame_needed();
    }
}

/// Synchronizes an external browser or OS fullscreen exit (`Esc`, `fullscreenchange`, window exit) by dismissing all open fullscreen portals (`Z_INDEX_FULLSCREEN`) and resetting global immersive fullscreen state.
///
/// # Returns
///
/// - `usize` - Number of open fullscreen component portals dismissed back to inline layout.
pub fn sync_external_fullscreen_exit() -> usize {
    let dismissed: usize = EuvOverlayStack::dismiss_fullscreen();
    FULLSCREEN_DEPTH.with(|depth: &Cell<usize>| depth.set(0));
    if let Some(ctx) = live_fullscreen_context() {
        ctx.set_immersive_fullscreen(false);
    }
    FULLSCREEN_ACTIVE_SIG.with(|slot: &RefCell<Option<Signal<bool>>>| {
        if let Ok(guard) = slot.try_borrow()
            && let Some(sig) = *guard
            && untracked(|| sig.try_get().is_some())
        {
            let _: bool = sig.set_if_changed(false);
        }
    });
    notify_frame_needed();
    dismissed
}

/// Resets the global fullscreen depth counter to zero and restores chrome visibility (useful for test cleanup).
pub fn reset_fullscreen_state() {
    let was_active: bool = FULLSCREEN_DEPTH.with(|depth: &Cell<usize>| depth.replace(0) > 0);
    if let Some(ctx) = live_fullscreen_context() {
        ctx.set_immersive_fullscreen(false);
    }
    FULLSCREEN_CTX_HANDLE.with(|slot: &RefCell<Option<Context>>| {
        if let Ok(mut guard) = slot.try_borrow_mut() {
            *guard = None;
        }
    });
    FULLSCREEN_WATCHER_GUARD.with(|slot: &RefCell<Option<FullscreenWatcherGuard>>| {
        if let Ok(mut guard) = slot.try_borrow_mut() {
            *guard = None;
        }
    });
    FULLSCREEN_ACTIVE_SIG.with(|slot: &RefCell<Option<Signal<bool>>>| {
        if let Ok(guard) = slot.try_borrow()
            && let Some(sig) = *guard
            && untracked(|| sig.try_get().is_some())
        {
            let _: bool = sig.set_if_changed(false);
        }
    });
    if was_active {
        let _: bool = dispatch_native_action(NATIVE_ACTION_FULLSCREEN, FULLSCREEN_ACTION_OFF, "");
    }
}

/// Returns the thread-local reactive generation signal notified whenever the ambient theme provider changes.
///
/// # Returns
///
/// - `Signal<u64>` - Live generation counter signal in the active reactive runtime.
fn theme_provider_signal() -> Signal<u64> {
    ACTIVE_THEME_GEN.with(|slot: &RefCell<Option<Signal<u64>>>| {
        if let Ok(guard) = slot.try_borrow()
            && let Some(sig) = *guard
            && untracked(|| sig.try_get().is_some())
        {
            return sig;
        }
        let fresh: Signal<u64> = Signal::new(0);
        if let Ok(mut guard) = slot.try_borrow_mut() {
            *guard = Some(fresh);
        }
        fresh
    })
}

/// Registers the active application `UiThemeState` for reactive in-place theme updates across components.
///
/// # Arguments
///
/// - `UiThemeState` - Reactive theme controller to install as the ambient theme.
pub fn provide_theme(theme: UiThemeState) {
    ACTIVE_THEME_STATE.with(|slot: &RefCell<Option<UiThemeState>>| {
        if let Ok(mut guard) = slot.try_borrow_mut() {
            *guard = Some(theme);
        }
    });
    let gen_sig: Signal<u64> = theme_provider_signal();
    let next_gen: u64 = gen_sig.get_untracked().wrapping_add(1);
    let _: bool = gen_sig.set(next_gen);
}

/// Clears any ambient `UiThemeState` registered on the current thread.
pub fn clear_provided_theme() {
    ACTIVE_THEME_STATE.with(|slot: &RefCell<Option<UiThemeState>>| {
        if let Ok(mut guard) = slot.try_borrow_mut() {
            *guard = None;
        }
    });
    ACTIVE_THEME_GEN.with(|slot: &RefCell<Option<Signal<u64>>>| {
        if let Ok(guard) = slot.try_borrow()
            && let Some(sig) = *guard
            && untracked(|| sig.try_get().is_some())
        {
            let next_gen: u64 = sig.get_untracked().wrapping_add(1);
            let _: bool = sig.set(next_gen);
        }
    });
}

/// Returns the ambient `UiThemeState` if one is active and its reactive signals are still alive.
///
/// # Returns
///
/// - `Option<UiThemeState>` - Active reactive theme controller, or `None` when none is provided.
#[must_use]
pub fn active_theme_state() -> Option<UiThemeState> {
    ACTIVE_THEME_STATE.with(|slot: &RefCell<Option<UiThemeState>>| {
        let candidate: Option<UiThemeState> = slot
            .try_borrow()
            .ok()
            .and_then(|guard: Ref<'_, Option<UiThemeState>>| guard.clone());
        candidate
            .filter(|theme: &UiThemeState| untracked(|| theme.get_tokens().try_get().is_some()))
    })
}

/// Resolves live `ThemeTokens` reactively from the ambient `UiThemeState`, falling back to `fallback`.
///
/// # Arguments
///
/// - `ThemeTokens` - Static fallback tokens used when no ambient theme is provided.
///
/// # Returns
///
/// - `ThemeTokens` - Current theme tokens (subscribing the active reactive observer when ambient theme exists).
#[must_use]
pub fn use_live_tokens(fallback: ThemeTokens) -> ThemeTokens {
    let _: u64 = theme_provider_signal().get();
    match active_theme_state() {
        Some(theme) => theme.get_tokens().try_get().unwrap_or(fallback),
        None => fallback,
    }
}

/// Resolves live `ThemeTokens` without subscribing reactive observers (suitable for canvas painters and handlers).
///
/// # Arguments
///
/// - `ThemeTokens` - Static fallback tokens used when no ambient theme is provided.
///
/// # Returns
///
/// - `ThemeTokens` - Current theme tokens read without reactive tracking.
#[must_use]
pub fn live_tokens_untracked(fallback: ThemeTokens) -> ThemeTokens {
    match active_theme_state() {
        Some(theme) => untracked(|| theme.get_tokens().try_get()).unwrap_or(fallback),
        None => fallback,
    }
}

/// Remaps one RGB-matched color entry from `pairs` while preserving `color`'s alpha channel.
///
/// # Arguments
///
/// - `Color` - Existing color value.
/// - `&[(Color, Color)]` - Ordered `(old_color, new_color)` semantic lookup pairs.
///
/// # Returns
///
/// - `Option<Color>` - Remapped color preserving original alpha if matched.
fn remap_color_from_pairs(color: Color, pairs: &[(Color, Color)]) -> Option<Color> {
    if color.get_a() == 0 {
        return None;
    }
    let r: u8 = color.get_r();
    let g: u8 = color.get_g();
    let b: u8 = color.get_b();
    let a: u8 = color.get_a();
    for &(old_c, new_c) in pairs.iter() {
        if old_c.get_r() == r && old_c.get_g() == g && old_c.get_b() == b {
            let next_a: u8 = if old_c.get_a() == a && old_c.get_a() != 255 {
                new_c.get_a()
            } else {
                a
            };
            return Some(Color::rgba(
                new_c.get_r(),
                new_c.get_g(),
                new_c.get_b(),
                next_a,
            ));
        }
    }
    None
}

/// Remaps `color` through `pairs`, returning the original color when no semantic token matches.
///
/// # Arguments
///
/// - `Color` - Existing color value.
/// - `&[(Color, Color)]` - Ordered `(old_color, new_color)` semantic lookup pairs.
///
/// # Returns
///
/// - `Color` - Remapped (or unchanged) color.
fn remap_color_or_keep(color: Color, pairs: &[(Color, Color)]) -> Color {
    remap_color_from_pairs(color, pairs).unwrap_or(color)
}

/// Remaps a single foreground / icon color from `from` theme tokens onto `to` theme tokens.
///
/// Useful for canvas painters (such as `EuvIcon`) that receive a resolved color at mount time and need to stay
/// synchronized when the ambient `UiThemeState` switches themes in-place.
///
/// # Arguments
///
/// - `Color` - Color captured under `from`.
/// - `ThemeTokens` - Origin theme tokens at mount time.
/// - `ThemeTokens` - Live target theme tokens.
///
/// # Returns
///
/// - `Color` - Remapped foreground / icon color (unchanged when `from == to` or no token matches).
#[must_use]
pub fn remap_theme_color(color: Color, from: ThemeTokens, to: ThemeTokens) -> Color {
    if from == to || color.get_a() == 0 {
        return color;
    }
    let pairs: ThemeRemapPairs = build_theme_remap_pairs(from, to);
    let ThemeRemapPairs { text, .. } = pairs;
    remap_color_or_keep(color, &text)
}

/// Remaps a `Shadow` matching one of `old_g`'s elevation levels onto `new_g`.
///
/// # Arguments
///
/// - `Shadow` - Existing shadow specification.
/// - `ThemeGeometry` - Previous theme geometry tokens.
/// - `ThemeGeometry` - Next theme geometry tokens.
///
/// # Returns
///
/// - `Shadow` - Updated shadow specification.
fn remap_theme_shadow(shadow: Shadow, old_g: ThemeGeometry, new_g: ThemeGeometry) -> Shadow {
    if shadow == old_g.get_shadow_lg() {
        new_g.get_shadow_lg()
    } else if shadow == old_g.get_shadow_md() {
        new_g.get_shadow_md()
    } else if shadow == old_g.get_shadow_sm() {
        new_g.get_shadow_sm()
    } else if shadow == old_g.get_shadow_xs() {
        new_g.get_shadow_xs()
    } else {
        shadow
    }
}

/// Builds the directed semantic `(from, to)` color and geometry lookup tables for one theme hop.
///
/// # Arguments
///
/// - `ThemeTokens` - Source theme tokens.
/// - `ThemeTokens` - Target theme tokens.
///
/// # Returns
///
/// - `ThemeRemapPairs` - Precomputed surface, border, and text lookup tables.
pub(crate) fn build_theme_remap_pairs(from: ThemeTokens, to: ThemeTokens) -> ThemeRemapPairs {
    let op: ThemePalette = from.get_palette();
    let np: ThemePalette = to.get_palette();
    let oe: CodeThemePalette = CodeThemePalette::resolve(from.get_mode());
    let ne: CodeThemePalette = CodeThemePalette::resolve(to.get_mode());
    let surface: [(Color, Color); THEME_SURFACE_PAIR_COUNT] = [
        (op.get_card(), np.get_card()),
        (op.get_background(), np.get_background()),
        (op.get_muted(), np.get_muted()),
        (op.get_secondary(), np.get_secondary()),
        (op.get_accent(), np.get_accent()),
        (op.get_primary(), np.get_primary()),
        (op.get_destructive(), np.get_destructive()),
        (op.get_success(), np.get_success()),
        (op.get_warning(), np.get_warning()),
        (op.get_overlay(), np.get_overlay()),
        (op.get_switch_track_off(), np.get_switch_track_off()),
        (op.get_switch_thumb(), np.get_switch_thumb()),
        (op.get_media_surface(), np.get_media_surface()),
        (op.get_border(), np.get_border()),
        (op.get_foreground(), np.get_foreground()),
        (op.get_primary_foreground(), np.get_primary_foreground()),
        (op.get_secondary_foreground(), np.get_secondary_foreground()),
        (op.get_muted_foreground(), np.get_muted_foreground()),
        (op.get_card_foreground(), np.get_card_foreground()),
        (
            op.get_destructive_foreground(),
            np.get_destructive_foreground(),
        ),
        (op.get_success_foreground(), np.get_success_foreground()),
        (op.get_warning_foreground(), np.get_warning_foreground()),
        (op.get_ring(), np.get_ring()),
        (oe.get_background(), ne.get_background()),
        (oe.get_header_bg(), ne.get_header_bg()),
        (oe.get_line_highlight(), ne.get_line_highlight()),
        (oe.get_inline_code_bg(), ne.get_inline_code_bg()),
        (oe.get_quote_bg(), ne.get_quote_bg()),
        (oe.get_border(), ne.get_border()),
        (oe.get_quote_border(), ne.get_quote_border()),
        (oe.get_keyword(), ne.get_keyword()),
        (oe.get_link(), ne.get_link()),
        (oe.get_diff_add(), ne.get_diff_add()),
        (oe.get_diff_del(), ne.get_diff_del()),
    ];
    let border: [(Color, Color); THEME_BORDER_PAIR_COUNT] = [
        (op.get_border(), np.get_border()),
        (oe.get_border(), ne.get_border()),
        (op.get_primary(), np.get_primary()),
        (op.get_ring(), np.get_ring()),
        (oe.get_quote_border(), ne.get_quote_border()),
        (op.get_destructive(), np.get_destructive()),
        (op.get_success(), np.get_success()),
        (op.get_warning(), np.get_warning()),
        (oe.get_link(), ne.get_link()),
        (oe.get_diff_add(), ne.get_diff_add()),
        (oe.get_diff_del(), ne.get_diff_del()),
        (oe.get_keyword(), ne.get_keyword()),
        (op.get_accent(), np.get_accent()),
        (op.get_muted(), np.get_muted()),
        (op.get_foreground(), np.get_foreground()),
        (op.get_muted_foreground(), np.get_muted_foreground()),
        (op.get_card(), np.get_card()),
        (op.get_background(), np.get_background()),
        (op.get_secondary(), np.get_secondary()),
        (op.get_switch_track_off(), np.get_switch_track_off()),
        (op.get_primary_foreground(), np.get_primary_foreground()),
        (op.get_card_foreground(), np.get_card_foreground()),
    ];
    let text: [(Color, Color); THEME_TEXT_PAIR_COUNT] = [
        (op.get_foreground(), np.get_foreground()),
        (op.get_card_foreground(), np.get_card_foreground()),
        (op.get_muted_foreground(), np.get_muted_foreground()),
        (op.get_primary_foreground(), np.get_primary_foreground()),
        (op.get_primary(), np.get_primary()),
        (op.get_secondary_foreground(), np.get_secondary_foreground()),
        (
            op.get_destructive_foreground(),
            np.get_destructive_foreground(),
        ),
        (op.get_destructive(), np.get_destructive()),
        (op.get_success_foreground(), np.get_success_foreground()),
        (op.get_success(), np.get_success()),
        (op.get_warning_foreground(), np.get_warning_foreground()),
        (op.get_warning(), np.get_warning()),
        (op.get_background(), np.get_background()),
        (op.get_card(), np.get_card()),
        (op.get_muted(), np.get_muted()),
        (op.get_accent(), np.get_accent()),
        (op.get_border(), np.get_border()),
        (oe.get_foreground(), ne.get_foreground()),
        (oe.get_line_number(), ne.get_line_number()),
        (oe.get_comment(), ne.get_comment()),
        (oe.get_keyword(), ne.get_keyword()),
        (oe.get_control(), ne.get_control()),
        (oe.get_operator(), ne.get_operator()),
        (oe.get_string(), ne.get_string()),
        (oe.get_number(), ne.get_number()),
        (oe.get_constant(), ne.get_constant()),
        (oe.get_function(), ne.get_function()),
        (oe.get_ty(), ne.get_ty()),
        (oe.get_primitive(), ne.get_primitive()),
        (oe.get_property(), ne.get_property()),
        (oe.get_punctuation(), ne.get_punctuation()),
        (oe.get_inline_code_fg(), ne.get_inline_code_fg()),
        (oe.get_link(), ne.get_link()),
        (oe.get_diff_add(), ne.get_diff_add()),
        (oe.get_diff_del(), ne.get_diff_del()),
    ];
    ThemeRemapPairs {
        surface,
        border,
        text,
        from_geometry: from.get_geometry(),
        to_geometry: to.get_geometry(),
    }
}

/// Remaps every theme-dependent paint property (background, gradient stops, border, shadow, focus ring) of `paint`.
///
/// Corner radii, sizes, and layout are never touched: every `DesignScheme` shares one canonical geometry, so a theme
/// switch is a pure paint update.
///
/// # Arguments
///
/// - `PaintStyle` - Source paint captured under the source theme.
/// - `&ThemeRemapPairs` - Directed semantic lookup tables.
///
/// # Returns
///
/// - `PaintStyle` - Paint restyled for the target theme (non-theme fields untouched).
pub(crate) fn remap_theme_paint(paint: PaintStyle, pairs: &ThemeRemapPairs) -> PaintStyle {
    let ThemeRemapPairs {
        surface,
        border,
        from_geometry,
        to_geometry,
        ..
    } = pairs;
    let mut next: PaintStyle = paint;
    if let Some(bg) = paint.background_color() {
        next.set_background(Some(remap_color_or_keep(bg, surface)));
    }
    if let Some(gradient) = paint.background_gradient() {
        next.set_gradient(Some(LinearGradient::new(
            gradient.get_angle_deg(),
            remap_color_or_keep(gradient.get_start_color(), surface),
            remap_color_or_keep(gradient.get_end_color(), surface),
        )));
    }
    let stroke: Border = paint.get_border();
    if stroke.get_width() > 0.0 {
        next.set_border(Border::new(
            stroke.get_width(),
            remap_color_or_keep(stroke.get_color(), border),
        ));
    }
    if let Some(ring) = paint.focus_ring_border() {
        next.set_focus_ring(Some(Border::new(
            ring.get_width(),
            remap_color_or_keep(ring.get_color(), border),
        )));
    }
    if let Some(sh) = paint.box_shadow() {
        next.set_shadow(Some(remap_theme_shadow(sh, *from_geometry, *to_geometry)));
    }
    next
}

/// Returns whether two paints agree on every theme-dependent color property (ignores radii, opacity, transform, cursor, events).
///
/// # Arguments
///
/// - `&PaintStyle` - Left paint.
/// - `&PaintStyle` - Right paint.
///
/// # Returns
///
/// - `bool` - `true` when background, gradient, border, shadow, and focus ring are identical.
fn theme_paint_eq(lhs: &PaintStyle, rhs: &PaintStyle) -> bool {
    lhs.background_color() == rhs.background_color()
        && lhs.background_gradient() == rhs.background_gradient()
        && lhs.get_border() == rhs.get_border()
        && lhs.box_shadow() == rhs.box_shadow()
        && lhs.focus_ring_border() == rhs.focus_ring_border()
}

/// Returns whether `paint` / `text` carry any visible theme-dependent color worth recording as a theme origin.
///
/// # Arguments
///
/// - `&PaintStyle` - Node paint.
/// - `Color` - Node text color.
///
/// # Returns
///
/// - `bool` - `true` when a background, gradient, border, shadow, focus ring, or visible text color exists.
fn has_theme_paint(paint: &PaintStyle, text: Color) -> bool {
    paint.background_color().is_some()
        || paint.background_gradient().is_some()
        || paint.get_border().get_width() > 0.0
        || paint.box_shadow().is_some()
        || paint.focus_ring_border().is_some()
        || text.get_a() > 0
}

/// Copies every theme-dependent color property from `themed` onto `target`, preserving radii and dynamic non-theme state.
///
/// # Arguments
///
/// - `&mut PaintStyle` - Live paint to update in place.
/// - `&PaintStyle` - Paint carrying the new theme-dependent values.
fn apply_theme_paint(target: &mut PaintStyle, themed: &PaintStyle) {
    target
        .set_background(themed.background_color())
        .set_gradient(themed.background_gradient())
        .set_border(themed.get_border())
        .set_shadow(themed.box_shadow())
        .set_focus_ring(themed.focus_ring_border());
}

/// Returns the cached directed lookup tables for `(from, to)`, building and caching them on first use.
///
/// # Arguments
///
/// - `&mut Vec<(ThemeKey, ThemeKey, ThemeRemapPairs)>` - Per-remap pair cache.
/// - `ThemeTokens` - Source theme tokens.
/// - `ThemeTokens` - Target theme tokens.
///
/// # Returns
///
/// - `ThemeRemapPairs` - Directed lookup tables.
fn cached_remap_pairs(
    cache: &mut Vec<(ThemeKey, ThemeKey, ThemeRemapPairs)>,
    from: ThemeTokens,
    to: ThemeTokens,
) -> ThemeRemapPairs {
    let from_key: ThemeKey = from.key();
    let to_key: ThemeKey = to.key();
    if let Some(&(_, _, pairs)) =
        cache
            .iter()
            .find(|entry: &&(ThemeKey, ThemeKey, ThemeRemapPairs)| {
                entry.0 == from_key && entry.1 == to_key
            })
    {
        return pairs;
    }
    let pairs: ThemeRemapPairs = build_theme_remap_pairs(from, to);
    cache.push((from_key, to_key, pairs));
    pairs
}

/// Marks every node in `nodes` as reactively theme-owned so generic in-place theme remaps skip their paint.
///
/// Components whose themed paint depends on interactive state (switch tracks, checkbox boxes, active tabs, slider
/// fills, ...) MUST mark those nodes and repaint them from `use_live_tokens()` inside their own reactive `Effect`.
///
/// # Arguments
///
/// - `&mut SceneTree` - Active retained scene tree.
/// - `&[NodeId]` - Component-owned node handles.
pub fn mark_theme_owned(tree: &mut SceneTree, nodes: &[NodeId]) {
    for &nid in nodes.iter() {
        tree.set_theme_owned(nid, true);
    }
}

/// Remaps colors, borders, radii, and shadows in-place across the scene subtree rooted at `root` without tearing down nodes or resetting scroll positions.
///
/// # Arguments
///
/// - `&mut SceneTree` - Active retained scene tree.
/// - `NodeId` - Root node handle of the subtree to restyle in-place.
/// - `ThemeTokens` - Previously applied theme tokens.
/// - `ThemeTokens` - Newly active theme tokens.
pub fn remap_subtree_theme_in_place(
    tree: &mut SceneTree,
    root: NodeId,
    old_tokens: ThemeTokens,
    new_tokens: ThemeTokens,
) {
    remap_subtree_theme_excluding(tree, root, None, old_tokens, new_tokens);
}

/// Remaps colors, borders, radii, and shadows in-place across the scene subtree rooted at `root`, optionally skipping an independently managed child subtree `exclude`.
///
/// # Arguments
///
/// - `&mut SceneTree` - Active retained scene tree.
/// - `NodeId` - Root node handle of the subtree to restyle in-place.
/// - `Option<NodeId>` - Optional descendant root handle excluded from traversal.
/// - `ThemeTokens` - Previously applied theme tokens.
/// - `ThemeTokens` - Newly active theme tokens.
pub fn remap_subtree_theme_excluding(
    tree: &mut SceneTree,
    root: NodeId,
    exclude: Option<NodeId>,
    old_tokens: ThemeTokens,
    new_tokens: ThemeTokens,
) {
    let excluded: &[NodeId] = exclude.as_slice();
    remap_subtree_theme_excluding_nodes(tree, root, excluded, old_tokens, new_tokens);
}

/// Returns whether two colors have identical RGB channels (ignoring alpha).
///
/// # Arguments
///
/// - `Color` - Left color.
/// - `Color` - Right color.
///
/// # Returns
///
/// - `bool` - `true` when red, green, and blue channels match.
fn rgb_eq(lhs: Color, rhs: Color) -> bool {
    lhs.get_r() == rhs.get_r() && lhs.get_g() == rhs.get_g() && lhs.get_b() == rhs.get_b()
}

/// Composites an optional node background fill over its inherited opaque ancestor background.
///
/// # Arguments
///
/// - `Option<Color>` - Node background fill, if any.
/// - `Color` - Inherited opaque ancestor background.
///
/// # Returns
///
/// - `Color` - Resulting opaque effective background.
fn effective_bg_over(bg: Option<Color>, parent_bg: Color) -> Color {
    match bg {
        Some(fill) if fill.get_a() > 0 => blend_over(fill, parent_bg),
        _ => parent_bg,
    }
}

/// Returns whether `color` matches one of `palette`'s primary surface fill tokens.
///
/// # Arguments
///
/// - `Color` - Candidate opaque color.
/// - `ThemePalette` - Palette to compare against.
///
/// # Returns
///
/// - `bool` - `true` when `color` matches a semantic surface role in `palette`.
fn is_palette_surface(color: Color, palette: ThemePalette) -> bool {
    rgb_eq(color, palette.get_background())
        || rgb_eq(color, palette.get_card())
        || rgb_eq(color, palette.get_muted())
        || rgb_eq(color, palette.get_secondary())
        || rgb_eq(color, palette.get_accent())
        || rgb_eq(color, palette.get_primary())
        || rgb_eq(color, palette.get_destructive())
        || rgb_eq(color, palette.get_success())
        || rgb_eq(color, palette.get_warning())
}

/// Resolves `(init_old_bg, init_new_bg)` behind `root`, handling both callers that already updated ancestor chrome to
/// `new_tokens` (such as `EuvAppShell`) and callers whose ancestors are still painted in `old_tokens`.
///
/// # Arguments
///
/// - `&SceneTree` - Retained scene tree.
/// - `NodeId` - Subtree root being remapped.
/// - `ThemeTokens` - Source theme tokens.
/// - `ThemeTokens` - Target theme tokens.
/// - `&ThemeRemapPairs` - Directed `(old_tokens -> new_tokens)` lookup tables.
///
/// # Returns
///
/// - `(Color, Color)` - `(parent_old_bg, parent_new_bg)` behind `root`.
fn resolve_root_ancestor_bgs(
    tree: &SceneTree,
    root: NodeId,
    old_tokens: ThemeTokens,
    new_tokens: ThemeTokens,
    hop_pairs: &ThemeRemapPairs,
) -> (Color, Color) {
    let op: ThemePalette = old_tokens.get_palette();
    let np: ThemePalette = new_tokens.get_palette();
    let mut chain: Vec<Color> = Vec::new();
    let mut cur: Option<NodeId> = tree.get_node(root).and_then(SceneNode::parent_id);
    while let Some(pid) = cur {
        let Some(pnode) = tree.get_node(pid) else {
            break;
        };
        if let Some(bg) = pnode.style_ref().get_paint().background_color()
            && bg.get_a() > 0
        {
            chain.push(bg);
            if bg.get_a() == 255 {
                break;
            }
        }
        cur = pnode.parent_id();
    }
    if chain.is_empty() {
        return (op.get_background(), np.get_background());
    }
    let mut eff_anc: Color = np.get_background().with_alpha(255);
    for bg in chain.into_iter().rev() {
        eff_anc = blend_over(bg, eff_anc);
    }
    if is_palette_surface(eff_anc, np) && !is_palette_surface(eff_anc, op) {
        let rev_pairs: ThemeRemapPairs = build_theme_remap_pairs(new_tokens, old_tokens);
        let init_old_bg: Color = remap_color_or_keep(eff_anc, &rev_pairs.surface);
        (init_old_bg, eff_anc)
    } else {
        let init_new_bg: Color = remap_color_or_keep(eff_anc, &hop_pairs.surface);
        (eff_anc, init_new_bg)
    }
}

/// Remaps a text color contextually against its origin ancestor background and enforces a hard WCAG contrast floor
/// against `new_eff_bg` so invisible text (`fg ~= bg`) is impossible after any theme switch.
///
/// # Arguments
///
/// - `Color` - Original text color captured under `from`.
/// - `Color` - Effective opaque background behind the node under `from`.
/// - `Color` - Effective opaque background behind the node under `to`.
/// - `ThemeTokens` - Origin theme tokens.
/// - `ThemeTokens` - Target theme tokens.
/// - `&ThemeRemapPairs` - Directed semantic lookup tables for `(from, to)`.
/// - `bool` - Whether to enforce the hard WCAG contrast floor (enabled for text and input nodes).
///
/// # Returns
///
/// - `Color` - Contrast-safe remapped text color.
fn remap_contextual_text(
    origin_text: Color,
    origin_eff_bg: Color,
    new_eff_bg: Color,
    from: ThemeTokens,
    to: ThemeTokens,
    pairs: &ThemeRemapPairs,
    enforce_contrast: bool,
) -> Color {
    if origin_text.get_a() == 0 {
        return origin_text;
    }
    let op: ThemePalette = from.get_palette();
    let np: ThemePalette = to.get_palette();
    let contextual: Option<Color> = if rgb_eq(origin_eff_bg, op.get_primary())
        && rgb_eq(origin_text, op.get_primary_foreground())
    {
        Some(np.get_primary_foreground())
    } else if rgb_eq(origin_eff_bg, op.get_destructive())
        && rgb_eq(origin_text, op.get_destructive_foreground())
    {
        Some(np.get_destructive_foreground())
    } else if rgb_eq(origin_eff_bg, op.get_success())
        && rgb_eq(origin_text, op.get_success_foreground())
    {
        Some(np.get_success_foreground())
    } else if rgb_eq(origin_eff_bg, op.get_warning())
        && rgb_eq(origin_text, op.get_warning_foreground())
    {
        Some(np.get_warning_foreground())
    } else if rgb_eq(origin_eff_bg, op.get_secondary())
        && rgb_eq(origin_text, op.get_secondary_foreground())
    {
        Some(np.get_secondary_foreground())
    } else if rgb_eq(origin_eff_bg, op.get_card()) && rgb_eq(origin_text, op.get_card_foreground())
    {
        Some(np.get_card_foreground())
    } else if (rgb_eq(origin_eff_bg, op.get_background())
        || rgb_eq(origin_eff_bg, op.get_muted())
        || rgb_eq(origin_eff_bg, op.get_accent()))
        && rgb_eq(origin_text, op.get_foreground())
    {
        Some(np.get_foreground())
    } else if (rgb_eq(origin_eff_bg, op.get_background())
        || rgb_eq(origin_eff_bg, op.get_card())
        || rgb_eq(origin_eff_bg, op.get_muted())
        || rgb_eq(origin_eff_bg, op.get_accent()))
        && rgb_eq(origin_text, op.get_muted_foreground())
    {
        Some(np.get_muted_foreground())
    } else {
        None
    };
    let oe: CodeThemePalette = CodeThemePalette::resolve(from.get_mode());
    let ne: CodeThemePalette = CodeThemePalette::resolve(to.get_mode());
    let is_code_surface: bool = rgb_eq(origin_eff_bg, oe.get_background())
        || rgb_eq(origin_eff_bg, oe.get_line_highlight())
        || rgb_eq(origin_eff_bg, oe.get_header_bg())
        || rgb_eq(origin_eff_bg, oe.get_inline_code_bg());
    let code_pairs: [(Color, Color); 18] = [
        (oe.get_foreground(), ne.get_foreground()),
        (oe.get_line_number(), ne.get_line_number()),
        (oe.get_comment(), ne.get_comment()),
        (oe.get_keyword(), ne.get_keyword()),
        (oe.get_control(), ne.get_control()),
        (oe.get_operator(), ne.get_operator()),
        (oe.get_string(), ne.get_string()),
        (oe.get_number(), ne.get_number()),
        (oe.get_constant(), ne.get_constant()),
        (oe.get_function(), ne.get_function()),
        (oe.get_ty(), ne.get_ty()),
        (oe.get_primitive(), ne.get_primitive()),
        (oe.get_property(), ne.get_property()),
        (oe.get_punctuation(), ne.get_punctuation()),
        (oe.get_inline_code_fg(), ne.get_inline_code_fg()),
        (oe.get_link(), ne.get_link()),
        (oe.get_diff_add(), ne.get_diff_add()),
        (oe.get_diff_del(), ne.get_diff_del()),
    ];
    let code_mapped: Option<Color> = remap_color_from_pairs(origin_text, &code_pairs);
    if is_code_surface && let Some(matched) = code_mapped {
        return matched;
    }
    let ThemeRemapPairs { text, .. } = pairs;
    let candidate: Color = match contextual {
        Some(matched) => matched.with_alpha(origin_text.get_a()),
        None => remap_color_or_keep(origin_text, text),
    };
    if !enforce_contrast {
        return candidate;
    }
    let is_muted: bool = rgb_eq(origin_text, op.get_muted_foreground())
        || rgb_eq(origin_text, oe.get_comment())
        || rgb_eq(origin_text, oe.get_line_number())
        || code_mapped.is_some();
    let min_ratio: f32 = if is_muted {
        CONTRAST_MIN_MUTED
    } else {
        CONTRAST_MIN_TEXT
    };
    if contrast_ratio(candidate, new_eff_bg) >= min_ratio {
        return candidate;
    }
    let safe: Color = np.readable_foreground_on(new_eff_bg);
    if origin_text.get_a() < 255 {
        let preserved: Color = safe.with_alpha(origin_text.get_a());
        if contrast_ratio(preserved, new_eff_bg) >= min_ratio {
            return preserved;
        }
    }
    safe
}

/// Remaps an optional `hover_style` while ensuring any hover background remains readable beneath the container's resting text polarity.
///
/// # Arguments
///
/// - `Option<PaintStyle>` - Original hover paint style.
/// - `&ThemeRemapPairs` - Directed lookup tables.
/// - `ThemePalette` - Target theme palette.
/// - `Color` - Target effective background behind the node's parent.
/// - `Color` - Target effective resting background of this node.
///
/// # Returns
///
/// - `Option<PaintStyle>` - Contrast-safe remapped hover paint style.
fn remap_safe_hover(
    hover: Option<PaintStyle>,
    pairs: &ThemeRemapPairs,
    np: ThemePalette,
    parent_new_bg: Color,
    resting_new_bg: Color,
) -> Option<PaintStyle> {
    hover.map(|paint: PaintStyle| {
        let mut next: PaintStyle = remap_theme_paint(paint, pairs);
        if let Some(hover_bg) = next.background_color()
            && hover_bg.get_a() > 0
        {
            let eff_hover: Color = blend_over(hover_bg, parent_new_bg);
            let resting_fg: Color = np.readable_foreground_on(resting_new_bg);
            if contrast_ratio(resting_fg, eff_hover) < CONTRAST_MIN_MUTED {
                let accent_eff: Color = blend_over(np.get_accent(), parent_new_bg);
                let safe_bg: Color = if contrast_ratio(resting_fg, accent_eff) >= CONTRAST_MIN_TEXT
                {
                    np.get_accent()
                } else {
                    resting_new_bg
                };
                next.set_background(Some(safe_bg));
            }
        }
        next
    })
}

/// Remaps colors, borders, radii, and shadows in-place across the scene subtree rooted at `root`, skipping every descendant root listed in `excluded`.
///
/// Every node is restyled from its recorded theme-origin snapshot (single hop) rather than from the previously
/// applied theme, carrying `(old_eff_bg, new_eff_bg)` down the tree for contextual foreground pairing and enforcing
/// a hard WCAG contrast safety net so multi-hop switches never accumulate drift or produce invisible text.
///
/// # Arguments
///
/// - `&mut SceneTree` - Active retained scene tree.
/// - `NodeId` - Root node handle of the subtree to restyle in-place.
/// - `&[NodeId]` - Descendant root handles excluded from traversal.
/// - `ThemeTokens` - Previously applied theme tokens.
/// - `ThemeTokens` - Newly active theme tokens.
pub(crate) fn remap_subtree_theme_excluding_nodes(
    tree: &mut SceneTree,
    root: NodeId,
    excluded: &[NodeId],
    old_tokens: ThemeTokens,
    new_tokens: ThemeTokens,
) {
    if old_tokens == new_tokens {
        return;
    }
    let old_key_idx: u16 = old_tokens.key().lut_index() as u16;
    let np: ThemePalette = new_tokens.get_palette();
    let mut pair_cache: Vec<(ThemeKey, ThemeKey, ThemeRemapPairs)> = Vec::with_capacity(4);
    let hop_pairs: ThemeRemapPairs = cached_remap_pairs(&mut pair_cache, old_tokens, new_tokens);
    let (init_old_bg, init_new_bg): (Color, Color) =
        resolve_root_ancestor_bgs(tree, root, old_tokens, new_tokens, &hop_pairs);
    let mut stack: Vec<(NodeId, Color, Color)> = vec![(root, init_old_bg, init_new_bg)];
    while let Some((nid, parent_old_bg, parent_new_bg)) = stack.pop() {
        if excluded.contains(&nid) {
            continue;
        }
        let Some((cur_style, cur_hover, is_canvas, is_text_like)) = tree
            .get_node(nid)
            .filter(|node: &&SceneNode| node.get_alive())
            .map(|node: &SceneNode| {
                (
                    node.get_style(),
                    node.hover_paint(),
                    matches!(node.get_kind(), NodeKind::Canvas(_)),
                    matches!(node.get_kind(), NodeKind::Text(_) | NodeKind::Input(_)),
                )
            })
        else {
            continue;
        };
        let cur_paint: PaintStyle = cur_style.get_paint();
        let cur_eff_bg: Color = effective_bg_over(cur_paint.background_color(), parent_old_bg);
        if tree.is_theme_owned(nid) {
            let op: ThemePalette = old_tokens.get_palette();
            let (owned_old_bg, owned_new_bg): (Color, Color) = match cur_paint.background_color() {
                Some(bg) if bg.get_a() > 0 => {
                    if is_palette_surface(bg, np) && !is_palette_surface(bg, op) {
                        let rev_pairs: ThemeRemapPairs =
                            cached_remap_pairs(&mut pair_cache, new_tokens, old_tokens);
                        let prev_bg: Color = remap_color_or_keep(bg, &rev_pairs.surface);
                        (
                            blend_over(prev_bg, parent_old_bg),
                            blend_over(bg, parent_new_bg),
                        )
                    } else {
                        let next_bg: Color = remap_color_or_keep(bg, &hop_pairs.surface);
                        (
                            blend_over(bg, parent_old_bg),
                            blend_over(next_bg, parent_new_bg),
                        )
                    }
                }
                _ => (parent_old_bg, parent_new_bg),
            };
            for child in tree.children_iter(nid) {
                stack.push((child, owned_old_bg, owned_new_bg));
            }
            if is_canvas {
                tree.mark_dirty(nid, DIRTY_PAINT);
            }
            continue;
        }
        let cur_text: Color = cur_style.get_text().get_color();
        let recorded: Option<(ThemeTokens, ThemeBaseline)> =
            tree.theme_baseline(nid).and_then(|base: ThemeBaseline| {
                ThemeKey::from_lut_index(base.get_origin_key() as usize)
                    .map(|key: ThemeKey| (key.resolve(), base))
            });
        let consistent: Option<(ThemeTokens, ThemeBaseline)> =
            recorded.filter(|&(origin_tok, base): &(ThemeTokens, ThemeBaseline)| {
                let to_old: ThemeRemapPairs =
                    cached_remap_pairs(&mut pair_cache, origin_tok, old_tokens);
                let expected_paint: PaintStyle = remap_theme_paint(base.get_paint(), &to_old);
                let expected_text: Color = remap_contextual_text(
                    base.get_text_color(),
                    base.get_origin_eff_bg(),
                    cur_eff_bg,
                    origin_tok,
                    old_tokens,
                    &to_old,
                    is_text_like,
                );
                theme_paint_eq(&expected_paint, &cur_paint) && expected_text == cur_text
            });
        let (origin_tok, origin_paint, origin_text, origin_eff_bg, origin_hover, needs_record): (
            ThemeTokens,
            PaintStyle,
            Color,
            Color,
            Option<PaintStyle>,
            bool,
        ) = match consistent {
            Some((tok, base)) => (
                tok,
                base.get_paint(),
                base.get_text_color(),
                base.get_origin_eff_bg(),
                base.get_hover(),
                false,
            ),
            None => (old_tokens, cur_paint, cur_text, cur_eff_bg, cur_hover, true),
        };
        let to_new: ThemeRemapPairs = cached_remap_pairs(&mut pair_cache, origin_tok, new_tokens);
        let next_paint: PaintStyle = remap_theme_paint(origin_paint, &to_new);
        let next_eff_bg: Color = effective_bg_over(next_paint.background_color(), parent_new_bg);
        let next_text: Color = remap_contextual_text(
            origin_text,
            origin_eff_bg,
            next_eff_bg,
            origin_tok,
            new_tokens,
            &to_new,
            is_text_like,
        );
        let next_hover: Option<PaintStyle> =
            remap_safe_hover(origin_hover, &to_new, np, parent_new_bg, next_eff_bg);
        for child in tree.children_iter(nid) {
            stack.push((child, cur_eff_bg, next_eff_bg));
        }
        let paint_changed: bool = !theme_paint_eq(&next_paint, &cur_paint) || next_text != cur_text;
        let hover_changed: bool = next_hover != cur_hover;
        if needs_record && (has_theme_paint(&cur_paint, cur_text) || cur_hover.is_some()) {
            tree.set_theme_baseline(
                nid,
                Some(ThemeBaseline::new(
                    old_key_idx,
                    cur_paint,
                    cur_text,
                    cur_eff_bg,
                    cur_hover,
                )),
            );
        }
        let mut paint_dirty: bool = is_canvas;
        if let Some(node) = tree.get_node_mut(nid) {
            if paint_changed {
                let mut st: Style = node.get_style();
                apply_theme_paint(st.get_mut_paint(), &next_paint);
                st.get_mut_text().set_color(next_text);
                node.set_style(st);
                paint_dirty = true;
            }
            if hover_changed {
                node.set_hover_style(next_hover);
                paint_dirty = true;
            }
        }
        if paint_dirty {
            tree.mark_dirty(nid, DIRTY_PAINT);
        }
    }
    tree.mark_dirty(root, DIRTY_PAINT);
}