frust-widgets 0.6.2

Baseline widget set for Frust: text, buttons, images, flex, stack and scroll containers, and the authoring helpers for custom widgets.
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
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
//! Keyed single-slot child-switch container: [`PatternSwitcher`], Flutter's
//! `PageTransitionSwitcher`/`AnimatedSwitcher` analog. It stages an
//! outgoing/incoming child pair under a
//! [`TransitionPattern`](super::patterns::TransitionPattern) whenever its
//! declared child changes *identity* (a [`ChildKey`](crate::ChildKey)).
//!
//! # Identity, not equality, drives the transition
//!
//! The switcher holds one child plus a caller-supplied `key`. On a rebuild
//! whose `key` is **unchanged**, the child reconciles in place like any
//! single-child wrapper — no transition (an every-frame rebuild is free). On a
//! **changed** `key`, the current child widget is *frozen* and retained as the
//! **exiting** child while a fresh **incoming** child is built in its place;
//! both then stage under the pattern, driven `0→1` off the frame clock
//! (advance-during-paint, `request_frame` — the crate's shared animation
//! contract). Same identity ⇒ same widget, state preserved; changed identity ⇒
//! a real subtree swap with an animated hand-off. This mirrors Flutter's
//! `PageTransitionSwitcher` "identity = type + key" rule.
//!
//! # Frozen exiting child: cancelled, torn down at the switch, only pixels survive
//!
//! While a transition runs the exiting child is inert: it keeps *painting* its
//! last state but is removed from the event path entirely — pointer routing
//! goes to the incoming child only ([`event`](PatternSwitcherWidget::event)).
//! At the instant it is frozen it receives the navigator's
//! **container-suppresses-routing** sequence verbatim (`docs/CODE_STANDARDS.md`):
//! a synthetic `Cancel` unwinds any in-flight capture, its focus flag is
//! cleared, and a cleared IME surface is published on the next paint — in that
//! order.
//!
//! **Then, in the same rebuild, the outgoing subtree is torn down**
//! (`View::teardown` through the view that last built it). From that point it
//! is logically out of the retained tree: every navigator under it reports
//! `is_mounted() == false` (and so claims no back press), every back
//! registrant's liveness count drops, and every
//! [`Component`](frust_core::Component) disposes its reactive owner — on the
//! very frame the key changes, not when the exit animation ends. What the
//! switcher keeps is only the torn-down widget tree's **pixels**: the pod is
//! laid out and painted until progress reaches `1.0`, never rebuilt and never
//! routed, then dropped on the next rebuild (or when a newer switch supersedes
//! it, or in the switcher's own teardown) — a plain drop each time, never a
//! second teardown.
//!
//! The teardown has to happen at the freeze because that is the only point at
//! which both halves are in hand: the old view (`prev.child`, gone after this
//! rebuild — an [`AnyView`] is not `Clone`, and the widget is not generic over
//! `State`, so it cannot be stashed until settle) and the old pod. A bare drop
//! at settle would skip `View::teardown` entirely, so a navigator or a back
//! fallback under a switched-away section would stay "mounted" forever and
//! keep swallowing back presses everywhere else in the app.
//!
//! Painting after teardown is sound for the widgets a switcher hosts: a
//! navigator's teardown finalizes any in-flight page transition and tears its
//! pages down but keeps their pods, which it paints like any static stack; a
//! [`frust_core::ComponentWidget`]'s paint is a pass-through to its pod that
//! never touches its (now disposed) owner, and its defensive `Drop` disposal is
//! idempotent; a plain leaf's teardown is a no-op. The focus contract above has
//! already cleared the pod's focus link before the teardown runs, so the
//! teardown's own focus-orphan gate sees no live link and releases nothing a
//! second time.
//!
//! # Compositing: paint-only, route-to-incoming keeps input correct
//!
//! A resolved [`PatternLayer`](super::patterns::PatternLayer) is applied as a
//! pod-origin offset (so a slide's paint and hit-test move together), a
//! `push_layer` opacity, and a `push_transform` scale about the child's centre.
//! `push_layer`/`push_transform` are **paint-only** (no hit-test effect); it is
//! the route-to-incoming-only rule above — not the transforms — that keeps
//! input correct mid-transition.
//!
//! # Timing & reduced motion
//!
//! Timing defaults from the theme's [`MotionScheme`](frust_theme::MotionScheme)
//! (`durations.base` + `easing.effects`), overridable with
//! [`.timing(...)`](PatternSwitcherView::timing); with no theme threaded it
//! falls back to [`FALLBACK_DURATION`] + [`Curve::Emphasized`]. A
//! `reduce_motion` theme collapses *every* pattern to a fast
//! ([`REDUCE_MOTION_DURATION`]) linear [`FadeThrough`] crossfade — the same hard
//! accessibility rule `nav::transition::resolve_spec` enforces.
//!
//! # Scaffold contract
//!
//! This file owns its own contents only — it never edits `motion/mod.rs`'s
//! module list or re-export block (see that module's docs; the facade
//! re-exports `motion` wholesale, so these types ride along under
//! `frust::motion::*`).

use std::time::Duration;

use frust_core::{
    AnyView, BoxConstraints, BuildCtx, ChangeFlags, ChildPod, Curve, DiscardScene, EditingState,
    EventCtx, EventResult, ImeState, InputEvent, LayoutCtx, PaintCtx, PaintScene, RetainedKey,
    SemanticsCtx, View, Widget, any,
};
use frust_theme::Theme;
use kurbo::{Affine, Point, Size, Vec2};

use crate::ChildKey;
use crate::Timing;
use crate::motion::patterns::{FadeThrough, PatternLayer, TransitionPattern};
use crate::nav::transition::{TransitionDriver, make_driver};
use crate::repaint_boundary::{RetainedBoundary, within};

/// The unthemed fallback transition duration (the Glyph `base` token, 220ms) —
/// used when no theme is threaded to resolve a `MotionScheme` from (bare-core
/// tests, pre-theme apps). See the [module docs](self)'s timing section.
pub const FALLBACK_DURATION: Duration = Duration::from_millis(220);

/// The reduced-motion collapse duration: `reduce_motion` flattens every pattern
/// to a `≤120ms` linear [`FadeThrough`] crossfade — the Glyph design system's
/// hard accessibility rule, matching `nav::transition`'s
/// [`REDUCE_MOTION_DURATION`](crate::nav::transition) collapse.
pub const REDUCE_MOTION_DURATION: Duration = Duration::from_millis(120);

/// Resolve the effective [`Timing`] for a switch: an explicit builder value
/// always wins; otherwise the theme's `base` duration + `effects` easing,
/// falling back to [`FALLBACK_DURATION`] + [`Curve::Emphasized`] when no theme
/// is threaded.
fn resolve_switch_timing(theme: Option<&Theme>, explicit: Option<Timing>) -> Timing {
    explicit.unwrap_or_else(|| match theme {
        Some(theme) => Timing::Duration(
            Duration::from_secs_f64(theme.motion.durations.base / 1000.0),
            theme.motion.easing.effects,
        ),
        None => Timing::Duration(FALLBACK_DURATION, Curve::Emphasized),
    })
}

/// Paint one staged child: offset its pod origin by the layer's `dx`/`dy` (so
/// paint and hit-testing move together), then paint it the way
/// `nav::navigator`'s `paint_page_layer` paints a transition page.
///
/// When `alpha == 0` the child is fully invisible this frame: rather than
/// rasterize it under a zero-opacity layer, it paints into a [`DiscardScene`]
/// sink — the pass still has to run for its side effects (animating
/// descendants advancing), but nothing it records is ever composited. A step
/// with no scale component (a slide, a fade) paints through the child's
/// retained-page `boundary` at the slid origin and the layer's alpha: both the
/// live and the frozen exiting child are usually static during a switch (only
/// their position/alpha move), so the first frame — progress 0, the exiting
/// child still at rest — records the page and later frames composite it. The
/// boundary only records while the child lies wholly inside the switcher's own
/// rect. A step with a scale component paints inline under a `push_transform`
/// scale about the child's centre and a `push_layer` when `alpha < 1`, since a
/// page is only ever served at the scale it was recorded at.
fn paint_staged_child(
    pod: &mut ChildPod,
    boundary: &mut RetainedBoundary,
    ctx: &mut PaintCtx,
    scene: &mut dyn PaintScene,
    layer: PatternLayer,
) {
    pod.set_origin(Point::new(layer.dx, layer.dy));
    let alpha = layer.alpha.clamp(0.0, 1.0);

    if alpha <= 0.0 {
        boundary.paint_plain(pod, ctx, &mut DiscardScene);
        return;
    }

    let origin = ctx.origin();
    let size = ctx.size();
    let child_origin = origin + Vec2::new(layer.dx, layer.dy);

    if (layer.scale - 1.0).abs() <= f64::EPSILON {
        let may_record = within(child_origin, size, origin, size);
        boundary.paint(pod, ctx, scene, child_origin, size, alpha, may_record);
        return;
    }

    let center = Point::new(
        child_origin.x + size.width / 2.0,
        child_origin.y + size.height / 2.0,
    );
    let layered = alpha < 1.0;
    scene.push_transform(Affine::scale_about(layer.scale, center));
    if layered {
        scene.push_layer(child_origin, size, alpha);
    }
    boundary.paint_plain(pod, ctx, scene);
    if layered {
        scene.pop_layer();
    }
    scene.pop_transform();
}

/// The cleared/inactive IME surface published after a switch so the platform
/// keyboard hides deterministically (mirrors `nav::navigator`'s
/// `cleared_ime_state`).
fn cleared_ime_state() -> ImeState {
    ImeState {
        active: false,
        editing: EditingState {
            text: String::new(),
            selection_base: -1,
            selection_extent: -1,
            composing_base: -1,
            composing_extent: -1,
        },
        caret: None,
        content_type: Default::default(),
        suppress_soft_keyboard: false,
    }
}

/// A keyed single-slot child-switch container. See the [module docs](self).
pub struct PatternSwitcherView<State: 'static, P: TransitionPattern + Clone + 'static> {
    key: ChildKey,
    pattern: P,
    timing: Option<Timing>,
    reverse: bool,
    child: AnyView<State>,
}

/// Stage a keyed child switch under `pattern`: whenever `key` changes identity,
/// the previous child animates out and `child` animates in. See the
/// [module docs](self).
pub fn pattern_switcher<State, P, V>(
    key: impl Into<ChildKey>,
    pattern: P,
    child: V,
) -> PatternSwitcherView<State, P>
where
    State: 'static,
    P: TransitionPattern + Clone + 'static,
    V: View<State>,
{
    PatternSwitcherView {
        key: key.into(),
        pattern,
        timing: None,
        reverse: false,
        child: any(child),
    }
}

/// PascalCase alias for [`pattern_switcher`] (mirrors the `AnimatedOpacity`/
/// `animated_opacity` dual naming).
#[allow(non_snake_case)]
pub fn PatternSwitcher<State, P, V>(
    key: impl Into<ChildKey>,
    pattern: P,
    child: V,
) -> PatternSwitcherView<State, P>
where
    State: 'static,
    P: TransitionPattern + Clone + 'static,
    V: View<State>,
{
    pattern_switcher(key, pattern, child)
}

impl<State: 'static, P: TransitionPattern + Clone + 'static> PatternSwitcherView<State, P> {
    /// Override the default (theme-resolved) transition timing.
    pub fn timing(mut self, timing: Timing) -> Self {
        self.timing = Some(timing);
        self
    }

    /// Flip the pattern's directional motion (a "back"/reverse switch). Has no
    /// effect on the non-directional patterns ([`FadeThrough`]/`FadeScale`).
    pub fn reverse(mut self, reverse: bool) -> Self {
        self.reverse = reverse;
        self
    }
}

/// The retained widget for a [`PatternSwitcherView`]. Generic only over the
/// pattern `P` (the frozen exiting child is retained as a bare
/// [`ChildPod`](frust_core::ChildPod), so no `State` is captured — which is why
/// it is torn down at the switch; see the [module docs](self)'s frozen-child
/// section).
pub struct PatternSwitcherWidget<P: TransitionPattern + Clone + 'static> {
    key: ChildKey,
    child: ChildPod,
    /// The frozen outgoing child: already torn down at the switch, retained
    /// only to paint its last state until the transition settles, then
    /// dropped (never torn down a second time).
    exiting: Option<ChildPod>,
    pattern: P,
    explicit_timing: Option<Timing>,
    reverse: bool,
    /// The `0→1` progress driver, created lazily on the first paint of a
    /// transition (a `BuildCtx` has no theme to resolve timing/`reduce_motion`
    /// from — mirrors `motion::animated`'s deferred retarget).
    driver: Option<TransitionDriver>,
    /// A transition was staged by the last rebuild; the next paint resolves
    /// timing and creates [`Self::driver`].
    pending_start: bool,
    /// The driver reached rest this paint; the next rebuild finalizes (drops the
    /// exiting child).
    settled: bool,
    /// The active transition collapsed to a `reduce_motion` crossfade (resolved
    /// once at start, stable for the whole transition).
    reduce_motion: bool,
    /// A cleared IME surface must be published on the next paint (deterministic
    /// keyboard hide after the switch).
    needs_ime_clear: bool,
    /// The retained-page boundary the live child paints through. With
    /// [`exiting_boundary`](Self::exiting_boundary) it draws on a pair of keys
    /// reserved once from [`frust_core::RetainedKey::mint_range`] at
    /// construction and stable for the widget's lifetime. Both children can be
    /// on screen staged together, so they need distinct keys — one key for both
    /// would alias their pages. A switch hands the live child's boundary to the
    /// frozen exiting pod with the pod itself, so a page recorded while the
    /// child was live still serves it as it leaves.
    child_boundary: RetainedBoundary,
    /// The retained-page boundary the frozen exiting child paints through (see
    /// [`child_boundary`](Self::child_boundary)).
    exiting_boundary: RetainedBoundary,
}

impl<State: 'static, P: TransitionPattern + Clone + 'static> View<State>
    for PatternSwitcherView<State, P>
{
    type Element = PatternSwitcherWidget<P>;

    fn build(&self, ctx: &mut BuildCtx<'_>) -> PatternSwitcherWidget<P> {
        let keys = RetainedKey::mint_range(2);
        PatternSwitcherWidget {
            key: self.key,
            child: crate::authoring::build_child(&self.child, ctx),
            exiting: None,
            pattern: self.pattern.clone(),
            explicit_timing: self.timing,
            reverse: self.reverse,
            driver: None,
            pending_start: false,
            settled: false,
            reduce_motion: false,
            needs_ime_clear: false,
            child_boundary: RetainedBoundary::with_key(keys),
            exiting_boundary: RetainedBoundary::with_key(RetainedKey(keys.get() + 1)),
        }
    }

    fn rebuild(
        &self,
        prev: &Self,
        element: &mut PatternSwitcherWidget<P>,
        ctx: &mut BuildCtx<'_>,
    ) -> ChangeFlags {
        let mut flags = ChangeFlags::NONE;

        // Pattern/timing/reverse are paint-time inputs; refresh them (a pattern
        // swap mid-flight is unusual but harmless — the running driver is
        // untouched). Only flag PAINT when a value actually changed.
        element.pattern = self.pattern.clone();
        if element.explicit_timing != self.timing {
            element.explicit_timing = self.timing;
            flags |= ChangeFlags::PAINT;
        }
        if element.reverse != self.reverse {
            element.reverse = self.reverse;
            flags |= ChangeFlags::PAINT;
        }

        // Finalize a just-settled transition (paint flagged `settled` and
        // requested this frame): drop the frozen exiting child. It was already
        // torn down at the switch, so this is a plain drop — never a second
        // teardown (a `ComponentWidget`'s `Drop` disposal is idempotent).
        if element.settled {
            element.exiting = None;
            element.driver = None;
            element.settled = false;
        }

        if self.key != element.key {
            // --- Identity change: stage a transition. ---
            // A new switch supersedes any still-running one: drop its exiting
            // pod, which was torn down when IT was frozen — a plain drop here.
            element.exiting = None;
            element.driver = None;
            element.reduce_motion = false;

            // Freeze the current incoming child as the exiting child; build the
            // new incoming child fresh in its place.
            let mut old = std::mem::replace(
                &mut element.child,
                crate::authoring::build_child(&self.child, ctx),
            );

            // Container-suppresses-routing contract (docs/CODE_STANDARDS.md):
            // synthetic Cancel -> focus clear -> cleared-IME publish, in order.
            if old.is_active() {
                crate::authoring::cancel_pod(&mut old);
                old.set_active(false);
            }
            if old.is_focused() {
                old.set_focused(false);
                // The cleared-IME publish is the third step of that contract, and
                // it belongs INSIDE this arm: publishing an inactive surface is a
                // full focus/IME **session release** at the root, not a value
                // update (`docs/CORE_ARCHITECTURE.md`'s Focus/IME Lifecycle), and
                // it bubbles last-write-wins. A switcher whose own child never
                // held focus has no session to end — raising the flag anyway
                // would release whatever *unrelated* subtree does own one (a
                // field painted earlier in the same frame), with no self-heal.
                //
                // Gated on the same composition every severing site in the crate
                // uses (`frust-widgets`' `mark_orphan_if_live`): the outgoing
                // pod's own link ANDed with the rebuild-pass chain down to this
                // switcher, so a *stale* flag under an already-blurred ancestor
                // publishes nothing either. `ctx.has_focus()` is unaffected by the
                // `build_child` above — that descent restores the chain on the
                // way out.
                if ctx.has_focus() {
                    element.needs_ime_clear = true;
                }
            }

            // Tear the outgoing subtree down NOW, through the view that last
            // built it — the only point where `prev.child` and the old pod are
            // both in hand (module docs). Navigators under it unmount and stop
            // claiming back, back registrants drop their liveness, components
            // dispose their owners. The pod is kept only to paint its pixels
            // until settle. The capture/focus steps above already ran, so
            // `teardown_child` finds the pod neither active (no second
            // `Cancel`) nor focused (its orphan gate sees no live link, and the
            // descent runs under a cleared chain, so nothing below re-releases
            // the session the IME clear above already ends).
            crate::authoring::teardown_child(&prev.child, &mut old, ctx);

            element.exiting = Some(old);
            // The frozen pod keeps its boundary (and any page it recorded
            // while live); the fresh child takes the other key, forgetting
            // whatever that key last recorded for a previous exiting child.
            std::mem::swap(&mut element.child_boundary, &mut element.exiting_boundary);
            element.child_boundary = RetainedBoundary::with_key(element.child_boundary.key());
            element.key = self.key;
            element.pending_start = true;
            flags |= ChangeFlags::LAYOUT | ChangeFlags::PAINT;
        } else {
            // --- Same identity: an ordinary in-place reconcile, no transition. ---
            flags |=
                crate::authoring::rebuild_child(&prev.child, &self.child, &mut element.child, ctx);
        }

        flags
    }

    fn teardown(&self, element: &mut PatternSwitcherWidget<P>, ctx: &mut BuildCtx<'_>) {
        crate::authoring::teardown_child(&self.child, &mut element.child, ctx);
        // The frozen exiting child (if a transition is still running) was torn
        // down at the switch that froze it; only its pixels were left, so a
        // plain drop finishes it — never a second teardown (module docs).
        element.exiting = None;
    }
}

impl<P: TransitionPattern + Clone + 'static> Widget for PatternSwitcherWidget<P> {
    fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
        let size = self.child.layout_child(ctx, bc);
        self.child.set_origin(Point::ZERO);
        // Lay out the frozen exiting child too (under the same constraints) so it
        // has a valid size to paint at during the transition. Its origin is set
        // per-frame in `paint` from the pattern layer.
        if let Some(exiting) = &mut self.exiting {
            exiting.layout_child(ctx, bc);
            exiting.set_origin(Point::ZERO);
        }
        size
    }

    fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
        // Lazily create the driver now a theme is in scope (reduce_motion +
        // timing resolution), mirroring `motion::animated`'s deferred retarget.
        if self.pending_start {
            let theme = Theme::from_paint_ctx(ctx);
            let reduce = theme.map(|t| t.motion.reduce_motion).unwrap_or(false);
            let timing = if reduce {
                Timing::Duration(REDUCE_MOTION_DURATION, Curve::Linear)
            } else {
                resolve_switch_timing(theme, self.explicit_timing)
            };
            self.driver = Some(make_driver(timing).0);
            self.reduce_motion = reduce;
            self.pending_start = false;
        }

        if let (Some(exiting), Some(driver)) = (self.exiting.as_mut(), self.driver.as_mut()) {
            let adv = driver.advance(ctx.frame_time());
            let size = ctx.size();
            // reduce_motion collapses any pattern to a FadeThrough crossfade.
            let (incoming_layer, exiting_layer) = if self.reduce_motion {
                FadeThrough.resolve(adv.value, self.reverse, size)
            } else {
                self.pattern.resolve(adv.value, self.reverse, size)
            };
            // Paint the exiting child (below) then the incoming child (on top),
            // each through its own boundary — see `Self::child_boundary`.
            paint_staged_child(
                exiting,
                &mut self.exiting_boundary,
                ctx,
                scene,
                exiting_layer,
            );
            paint_staged_child(
                &mut self.child,
                &mut self.child_boundary,
                ctx,
                scene,
                incoming_layer,
            );

            if adv.animating {
                ctx.request_frame();
            }
            if adv.done {
                // Settle: finalize on the next rebuild; request one more frame so
                // that rebuild runs (mirrors the navigator's settle contract).
                self.settled = true;
                ctx.request_frame();
            }
        } else {
            self.child_boundary.paint_plain(&mut self.child, ctx, scene);
        }

        // Deterministic IME hide after a switch (navigator contract). Publishing
        // a cleared surface bubbles up through `ChildPod::paint_child`.
        if self.needs_ime_clear {
            ctx.publish_ime_state(cleared_ime_state());
            self.needs_ime_clear = false;
        }
    }

    fn event(&mut self, ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
        // Route only to the incoming child; the frozen exiting child left the
        // event path at transition start (synthetically cancelled) — module docs.
        crate::authoring::route_event_single(&mut self.child, ctx, event)
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        // Forward the incoming (destination) child; the transient exiting child
        // is mid-removal and is not reported.
        self.child.semantics_child(ctx);
    }

    crate::authoring::visit_children!(exiting, child);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::motion::patterns::{FadeScale, SharedAxis};
    use crate::test_support::{RecordingScene, leaf_any};
    use crate::{FlexView, column};
    use frust_core::{
        FrameTime, PointerButton, PointerEvent, PointerPhase, RenderRoot, RetainedLedger,
    };
    use kurbo::Rect;
    use std::cell::Cell;
    use std::rc::Rc;

    fn ft_ms(ms: f64) -> FrameTime {
        FrameTime::from_nanos((ms * 1_000_000.0) as u64)
    }

    fn build<S: 'static, V: View<S>>(view: &V) -> V::Element {
        let mut counter = 0u64;
        view.build(&mut BuildCtx::new(&mut counter))
    }

    fn down(x: f64, y: f64) -> InputEvent {
        InputEvent::Pointer(PointerEvent {
            phase: PointerPhase::Down,
            position: Point::new(x, y),
            button: PointerButton::Primary,
        })
    }

    fn loose() -> BoxConstraints {
        BoxConstraints::loose(Size::new(100.0, 100.0))
    }

    /// A recording scene that separates `push_retained`/`pop_retained` calls
    /// from `push_layer`/`push_transform` ones. `crate::test_support`'s shared
    /// `RecordingScene` doesn't override `push_retained`, so it would fold a
    /// retained bracket into the trait's emulating default — a `push_transform`
    /// and `push_layer` pair — indistinguishable from a plain bracket. This one
    /// keeps them apart so a test can assert a staged child painted through
    /// the retained bracket specifically, and through no other bracket.
    #[derive(Default)]
    struct RetainedRecordingScene {
        rects: Vec<(Point, Size)>,
        layers: Vec<(Point, Size, f32)>,
        transform_pushes: u32,
        retained_pushes: Vec<(u64, Point, Size, f32, f64)>,
        retained_pops: u32,
        draws: Vec<(u64, Point, Size, f32, f64)>,
    }
    impl PaintScene for RetainedRecordingScene {
        fn fill_rect(&mut self, origin: Point, size: Size, _color: peniko::Color) {
            self.rects.push((origin, size));
        }
        fn draw_text(&mut self, _origin: Point, _text: &str) {}
        fn push_layer(&mut self, origin: Point, size: Size, alpha: f32) {
            self.layers.push((origin, size, alpha));
        }
        fn push_transform(&mut self, _transform: kurbo::Affine) {
            self.transform_pushes += 1;
        }
        fn push_retained(&mut self, key: u64, origin: Point, size: Size, alpha: f32, scale: f64) {
            self.retained_pushes.push((key, origin, size, alpha, scale));
        }
        fn pop_retained(&mut self) {
            self.retained_pops += 1;
        }
        fn draw_retained(&mut self, key: u64, origin: Point, size: Size, alpha: f32, scale: f64) {
            self.draws.push((key, origin, size, alpha, scale));
        }
    }

    /// An interactive child that captures the pointer + takes focus on `Down`,
    /// records a synthetic `Cancel` into a shared cell, records its widget's
    /// drop into `torn`, and its `View::teardown` into `teardowns` — the
    /// recording interactive child the tests below assert against (mirrors the
    /// navigator's recording tests). The two counters are kept apart on
    /// purpose: a frozen exiting child is torn down at the switch but dropped
    /// only at settle.
    struct Recorder {
        cancelled: Rc<Cell<bool>>,
        torn: Rc<Cell<u32>>,
        teardowns: Rc<Cell<u32>>,
    }
    struct RecorderWidget {
        cancelled: Rc<Cell<bool>>,
        torn: Rc<Cell<u32>>,
    }
    impl View<()> for Recorder {
        type Element = RecorderWidget;
        fn build(&self, _ctx: &mut BuildCtx<'_>) -> RecorderWidget {
            RecorderWidget {
                cancelled: self.cancelled.clone(),
                torn: self.torn.clone(),
            }
        }
        fn rebuild(
            &self,
            _prev: &Self,
            _element: &mut RecorderWidget,
            _ctx: &mut BuildCtx<'_>,
        ) -> ChangeFlags {
            ChangeFlags::NONE
        }
        fn teardown(&self, _element: &mut RecorderWidget, _ctx: &mut BuildCtx<'_>) {
            self.teardowns.set(self.teardowns.get() + 1);
        }
    }
    impl Widget for RecorderWidget {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.max()
        }
        fn paint(&mut self, _ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {}
        fn event(&mut self, ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
            if let InputEvent::Pointer(p) = event {
                match p.phase {
                    PointerPhase::Down => {
                        ctx.capture_pointer();
                        ctx.request_focus();
                        return EventResult::Handled;
                    }
                    // A Cancel arm only clears internal flags (never app state) —
                    // recording into an owned `Rc<Cell>` is an internal flag.
                    PointerPhase::Cancel => {
                        self.cancelled.set(true);
                        return EventResult::Handled;
                    }
                    _ => {}
                }
            }
            EventResult::Ignored
        }
    }
    impl Drop for RecorderWidget {
        fn drop(&mut self) {
            self.torn.set(self.torn.get() + 1);
        }
    }

    fn recorder(cancelled: &Rc<Cell<bool>>, torn: &Rc<Cell<u32>>) -> Recorder {
        Recorder {
            cancelled: cancelled.clone(),
            torn: torn.clone(),
            teardowns: Rc::new(Cell::new(0)),
        }
    }

    /// A [`Recorder`] whose `View::teardown` count is observable too.
    fn counting_recorder(torn: &Rc<Cell<u32>>, teardowns: &Rc<Cell<u32>>) -> Recorder {
        Recorder {
            cancelled: Rc::new(Cell::new(false)),
            torn: torn.clone(),
            teardowns: teardowns.clone(),
        }
    }

    fn reduced_motion_theme() -> Theme {
        let mut theme = Theme::neutral();
        theme.motion.reduce_motion = true;
        theme
    }

    // --- Identity change transitions; same identity doesn't ---

    #[test]
    fn same_identity_rebuild_does_not_transition_but_changed_identity_does() {
        let v1: PatternSwitcherView<(), _> =
            pattern_switcher(1u32, FadeThrough, leaf_any(10.0, 10.0));
        let mut w = build(&v1);
        assert!(w.exiting.is_none());

        // Same key: an ordinary reconcile, no transition staged.
        let v2: PatternSwitcherView<(), _> =
            pattern_switcher(1u32, FadeThrough, leaf_any(20.0, 20.0));
        let mut counter = 0u64;
        v2.rebuild(&v1, &mut w, &mut BuildCtx::new(&mut counter));
        assert!(
            w.exiting.is_none(),
            "same identity must not stage a transition"
        );
        assert!(!w.pending_start);

        // Changed key: the old child is frozen as the exiting child.
        let v3: PatternSwitcherView<(), _> =
            pattern_switcher(2u32, FadeThrough, leaf_any(30.0, 30.0));
        v3.rebuild(&v2, &mut w, &mut BuildCtx::new(&mut counter));
        assert!(
            w.exiting.is_some(),
            "an identity change must retain the exiting child"
        );
        assert!(w.pending_start, "the next paint starts the driver");
        assert_eq!(w.key, 2u32.into());
    }

    // --- Exiting child gets Cancel + focus/IME clear ---

    #[test]
    fn identity_change_cancels_focus_and_clears_ime_on_the_exiting_child() {
        let cancelled = Rc::new(Cell::new(false));
        let torn = Rc::new(Cell::new(0u32));
        let v1: PatternSwitcherView<(), _> =
            pattern_switcher(1u32, FadeThrough, recorder(&cancelled, &torn));
        let mut w = build(&v1);
        let size = w.layout(&mut LayoutCtx::new(), &loose());

        // Arm the child: a Down captures the pointer and takes focus.
        let mut st = ();
        let mut ectx = EventCtx::new(&mut st, Point::ZERO, size);
        w.event(&mut ectx, &down(5.0, 5.0));
        assert!(w.child.is_active(), "the child captured the pointer");
        assert!(w.child.is_focused(), "the child took focus");

        // Switch identity: the armed child becomes the exiting child and gets the
        // capture-cancel -> focus-clear -> IME-clear sequence.
        let v2: PatternSwitcherView<(), _> =
            pattern_switcher(2u32, FadeThrough, leaf_any(10.0, 10.0));
        let mut counter = 0u64;
        v2.rebuild(&v1, &mut w, &mut BuildCtx::new(&mut counter));

        assert!(
            cancelled.get(),
            "the exiting child received a synthetic Cancel"
        );
        let exiting = w.exiting.as_ref().expect("exiting child retained");
        assert!(
            !exiting.is_focused(),
            "the exiting child's focus was cleared"
        );
        assert!(!exiting.is_active(), "its capture path was released");
        assert!(
            w.needs_ime_clear,
            "an IME clear is queued for the next paint"
        );

        // The paint after the switch publishes the cleared IME surface.
        let mut pctx = PaintCtx::new(Point::ZERO, size);
        let mut scene = RecordingScene::default();
        w.paint(&mut pctx, &mut scene);
        let ime = pctx
            .take_ime_state()
            .expect("a cleared IME surface was published on the post-switch paint");
        assert!(!ime.active);
        assert!(ime.editing.text.is_empty());
        assert!(!w.needs_ime_clear, "the queued clear was consumed");
    }

    // --- The freeze-time teardown releases no session a second time: the
    //     focus link is cleared before `teardown_child` runs, so its orphan
    //     gate sees nothing live; the IME clear stays the one release. ---

    #[test]
    fn freeze_teardown_of_a_focused_child_raises_no_second_focus_release() {
        let cancelled = Rc::new(Cell::new(false));
        let torn = Rc::new(Cell::new(0u32));
        let teardowns = Rc::new(Cell::new(0u32));
        let v1: PatternSwitcherView<(), _> = pattern_switcher(
            1u32,
            FadeThrough,
            Recorder {
                cancelled: cancelled.clone(),
                torn: torn.clone(),
                teardowns: teardowns.clone(),
            },
        );
        let mut w = build(&v1);
        let size = w.layout(&mut LayoutCtx::new(), &loose());
        let mut st = ();
        let mut ectx = EventCtx::new(&mut st, Point::ZERO, size);
        w.event(&mut ectx, &down(5.0, 5.0));
        assert!(w.child.is_active() && w.child.is_focused());

        let _ = frust_core::take_focus_orphaned();
        let v2: PatternSwitcherView<(), _> =
            pattern_switcher(2u32, FadeThrough, leaf_any(10.0, 10.0));
        let mut counter = 0u64;
        // `BuildCtx::new` seeds a live chain: the focused pod WAS on it.
        v2.rebuild(&v1, &mut w, &mut BuildCtx::new(&mut counter));

        assert_eq!(
            teardowns.get(),
            1,
            "the focused child was torn down at the switch"
        );
        assert!(cancelled.get(), "cancelled exactly as before");
        assert!(w.needs_ime_clear, "the IME clear is the session release");
        assert!(
            !frust_core::take_focus_orphaned(),
            "the teardown must not raise a second (orphan) release"
        );
    }

    // --- Cross-subtree survival: a switcher whose OWN child never held focus
    //     must not release somebody else's live session (review-fix-3, FC). ---

    /// The IME surface the sibling field owns for the whole test below.
    fn field_surface() -> ImeState {
        ImeState {
            active: true,
            editing: EditingState {
                text: "query".to_string(),
                selection_base: 5,
                selection_extent: 5,
                composing_base: -1,
                composing_extent: -1,
            },
            caret: Some(Rect::new(0.0, 0.0, 1.0, 12.0)),
            content_type: Default::default(),
            suppress_soft_keyboard: false,
        }
    }

    /// A **persistent** field-shaped leaf: it claims focus and publishes on
    /// `Down`, and republishes the same surface on every paint while it still
    /// holds focus — a real `TextInput`'s behavior, and the reason paint order
    /// (field first, switcher second) decides the last write. Bounded size so it
    /// can sit as an inflexible child on a `Column`'s unbounded main axis.
    struct PersistentField {
        size: Size,
    }
    struct PersistentFieldWidget {
        size: Size,
    }
    impl<S: 'static> View<S> for PersistentField {
        type Element = PersistentFieldWidget;
        fn build(&self, _ctx: &mut BuildCtx<'_>) -> PersistentFieldWidget {
            PersistentFieldWidget { size: self.size }
        }
        fn rebuild(
            &self,
            _prev: &Self,
            _element: &mut PersistentFieldWidget,
            _ctx: &mut BuildCtx<'_>,
        ) -> ChangeFlags {
            ChangeFlags::NONE
        }
    }
    impl Widget for PersistentFieldWidget {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.constrain(self.size)
        }
        fn paint(&mut self, ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {
            if ctx.has_focus() {
                ctx.publish_ime_state(field_surface());
            }
        }
        fn event(&mut self, ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
            if let InputEvent::Pointer(p) = event
                && p.phase == PointerPhase::Down
            {
                ctx.request_focus();
                ctx.publish_ime_state(field_surface());
                return EventResult::Handled;
            }
            EventResult::Ignored
        }
    }

    #[test]
    fn identity_change_in_an_unfocused_switcher_leaves_a_sibling_fields_session_alive() {
        // A persistent field as the EARLIER sibling of an unrelated switcher, so
        // the field paints FIRST and anything the switcher published would win
        // last-write-wins on the way to the root. Rows are 40 tall: the field
        // owns `y ∈ [0, 40)`, the switcher `y ∈ [40, 80)`.
        let key = Rc::new(Cell::new(1u32));
        let mut app = {
            let key = key.clone();
            move |_: &mut ()| {
                column()
                    .child(PersistentField {
                        size: Size::new(100.0, 40.0),
                    })
                    .child(pattern_switcher(
                        key.get(),
                        FadeThrough,
                        leaf_any(100.0, 40.0),
                    ))
            }
        };
        let mut root: RenderRoot<(), FlexView<()>> = RenderRoot::new();
        let mut state = ();
        root.rebuild(&mut app, &mut state);
        root.layout(Size::new(100.0, 100.0));
        root.paint(&mut RecordingScene::default(), FrameTime::ZERO);

        // Tap inside the field's row — never the switcher's, which would blur the
        // field on the way in (blur-on-outside-tap) and hide the defect.
        root.event(&mut state, &down(5.0, 5.0));
        assert!(
            root.is_focus_active(),
            "the sibling field owns the focus session"
        );
        assert_eq!(
            root.ime_state().map(|s| s.editing.text),
            Some("query".to_string()),
            "…and the shell-facing surface is the field's"
        );
        let generation = root.focus_ime_generation();

        // The switcher's identity changes. Its own child never held focus, so
        // there is no session here to end.
        key.set(2);
        root.rebuild(&mut app, &mut state);
        root.layout(Size::new(100.0, 100.0));
        root.paint(&mut RecordingScene::default(), FrameTime::ZERO);

        assert!(
            root.is_focus_active(),
            "an identity change in an unfocused switcher must not release the \
             sibling field's session"
        );
        let ime = root
            .ime_state()
            .expect("the identity change dropped the sibling field's IME surface entirely");
        assert!(ime.active, "the field's surface was left inactive");
        assert_eq!(
            ime.editing.text, "query",
            "the field's surface was replaced with the switcher's cleared one"
        );
        assert_eq!(
            root.focus_ime_generation(),
            generation,
            "an identity change in an unfocused switcher is not a focus/IME edge"
        );
    }

    // --- Exiting torn down at the switch, its pod retained (painting) until
    //     progress 1.0, then dropped — never torn down a second time. ---

    #[test]
    fn exiting_child_is_torn_down_at_the_switch_and_dropped_after_settle() {
        let torn = Rc::new(Cell::new(0u32));
        let teardowns = Rc::new(Cell::new(0u32));
        let short = Timing::Duration(Duration::from_millis(100), Curve::Linear);
        let v1: PatternSwitcherView<(), _> =
            pattern_switcher(1u32, FadeThrough, counting_recorder(&torn, &teardowns)).timing(short);
        let mut w = build(&v1);
        let size = w.layout(&mut LayoutCtx::new(), &loose());

        // Switch identity -> transition begins. The outgoing subtree is torn
        // down on this very rebuild; its pod is retained (not dropped).
        let v2: PatternSwitcherView<(), _> =
            pattern_switcher(2u32, FadeThrough, leaf_any(10.0, 10.0)).timing(short);
        let mut counter = 0u64;
        v2.rebuild(&v1, &mut w, &mut BuildCtx::new(&mut counter));
        assert!(w.exiting.is_some());
        assert_eq!(teardowns.get(), 1, "torn down at the switch, exactly once");
        assert_eq!(
            torn.get(),
            0,
            "its pod is not dropped while the transition runs"
        );

        // First paint creates + seeds the driver (still mid-flight).
        w.paint(
            &mut PaintCtx::new(Point::ZERO, size),
            &mut RecordingScene::default(),
        );
        assert!(w.exiting.is_some(), "retained during the transition");
        assert_eq!(torn.get(), 0);
        assert!(!w.settled);

        // Drive the retained driver to rest directly (PaintCtx::set_frame_time is
        // crate-private to frust-core, mirroring the animated.rs tests).
        w.driver
            .as_mut()
            .expect("driver created on first paint")
            .advance(ft_ms(10_000.0));

        // The next paint observes the settled driver and flags finalize.
        w.paint(
            &mut PaintCtx::new(Point::ZERO, size),
            &mut RecordingScene::default(),
        );
        assert!(w.settled, "paint flags settle once the driver reaches rest");
        assert!(
            w.exiting.is_some(),
            "still retained until the finalize rebuild"
        );
        assert_eq!(torn.get(), 0);

        // The finalize rebuild (same identity, key 2) drops the exiting pod —
        // a plain drop, no second teardown.
        let v3: PatternSwitcherView<(), _> =
            pattern_switcher(2u32, FadeThrough, leaf_any(10.0, 10.0)).timing(short);
        v3.rebuild(&v2, &mut w, &mut BuildCtx::new(&mut counter));
        assert!(w.exiting.is_none(), "exiting dropped after settle");
        assert_eq!(
            torn.get(),
            1,
            "exiting dropped exactly once, after progress 1.0"
        );
        assert_eq!(
            teardowns.get(),
            1,
            "the settle drop is not a second teardown"
        );
        assert!(!w.settled);
        assert!(w.driver.is_none());

        // And the switcher's own teardown touches nothing already finished.
        v3.teardown(&mut w, &mut BuildCtx::new(&mut counter));
        assert_eq!((teardowns.get(), torn.get()), (1, 1));
    }

    // --- A navigator under the outgoing child leaves the tree AT the switch:
    //     unmounted and claiming no back press on that very rebuild, while its
    //     frozen pod keeps painting until settle. ---

    #[test]
    fn a_navigator_in_the_outgoing_child_unmounts_on_the_switch_but_still_paints() {
        use crate::test_support::leaf;
        use crate::{NavigatorController, navigator};

        let ctrl: NavigatorController<()> = NavigatorController::new();
        let short = Timing::Duration(Duration::from_millis(100), Curve::Linear);
        let section = |key: u32| -> PatternSwitcherView<(), FadeThrough> {
            let child = if key == 1 {
                any(navigator(&ctrl, || leaf(10.0, 10.0)))
            } else {
                leaf_any(10.0, 10.0)
            };
            pattern_switcher(key, FadeThrough, child).timing(short)
        };
        let mut counter = 0u64;
        let v1 = section(1);
        let mut w = build(&v1);
        assert!(ctrl.is_mounted());

        // Depth 2 through a same-key rebuild: the navigator claims back.
        ctrl.push(|| leaf(40.0, 40.0));
        let v2 = section(1);
        v2.rebuild(&v1, &mut w, &mut BuildCtx::new(&mut counter));
        assert_eq!(ctrl.depth(), 2);
        assert!(
            ctrl.back_interest(),
            "a mounted depth-2 navigator claims back"
        );

        // Switch the key: the very same rebuild unmounts it and silences it.
        let v3 = section(2);
        v3.rebuild(&v2, &mut w, &mut BuildCtx::new(&mut counter));
        assert!(!ctrl.is_mounted(), "torn down at the switch, not at settle");
        assert!(
            !ctrl.back_interest(),
            "a torn-down navigator claims nothing, with no re-wire in between"
        );

        // ...while its frozen pod keeps painting its top page (40x40) until
        // settle. FadeThrough at p=0: the exiting child is fully opaque.
        let size = w.layout(&mut LayoutCtx::new(), &loose());
        let mut scene = RecordingScene::default();
        w.paint(&mut PaintCtx::new(Point::ZERO, size), &mut scene);
        assert!(
            scene.rects.iter().any(|(_, s)| *s == Size::new(40.0, 40.0)),
            "the torn-down navigator's top page still paints: {:?}",
            scene.rects
        );

        // Settle and finalize: dropped, and still unmounted (no double count).
        w.driver
            .as_mut()
            .expect("driver created on first paint")
            .advance(ft_ms(10_000.0));
        w.paint(
            &mut PaintCtx::new(Point::ZERO, size),
            &mut RecordingScene::default(),
        );
        assert!(w.settled);
        let v4 = section(2);
        v4.rebuild(&v3, &mut w, &mut BuildCtx::new(&mut counter));
        assert!(w.exiting.is_none());
        assert!(!ctrl.is_mounted());
        assert!(!ctrl.back_interest());
    }

    // --- A Component in the outgoing child is torn down (its owner disposed)
    //     exactly once across the freeze, the settle drop and the switcher's
    //     own teardown. Its child view's `View::teardown` only runs from the
    //     component's teardown (never from its `Drop`), so its count is the
    //     component's teardown count; `State` drops with the widget. ---

    struct ProbeComp {
        teardowns: Rc<Cell<u32>>,
        state_drops: Rc<Cell<u32>>,
    }
    struct ProbeState {
        drops: Rc<Cell<u32>>,
    }
    impl Drop for ProbeState {
        fn drop(&mut self) {
            self.drops.set(self.drops.get() + 1);
        }
    }
    impl frust_core::Component for ProbeComp {
        type State = ProbeState;
        fn init(&self) -> ProbeState {
            ProbeState {
                drops: self.state_drops.clone(),
            }
        }
        fn build(&self, _state: &mut ProbeState) -> impl View<ProbeState> {
            TeardownLeaf {
                teardowns: self.teardowns.clone(),
            }
        }
    }
    /// A leaf over any state that counts its `View::teardown`s.
    struct TeardownLeaf {
        teardowns: Rc<Cell<u32>>,
    }
    impl<S: 'static> View<S> for TeardownLeaf {
        type Element = crate::test_support::LeafWidget;
        fn build(&self, ctx: &mut BuildCtx<'_>) -> Self::Element {
            View::<()>::build(&crate::test_support::leaf(30.0, 30.0), ctx)
        }
        fn rebuild(
            &self,
            _prev: &Self,
            _element: &mut Self::Element,
            _ctx: &mut BuildCtx<'_>,
        ) -> ChangeFlags {
            ChangeFlags::NONE
        }
        fn teardown(&self, _element: &mut Self::Element, _ctx: &mut BuildCtx<'_>) {
            self.teardowns.set(self.teardowns.get() + 1);
        }
    }

    #[test]
    fn a_component_in_the_outgoing_child_is_torn_down_exactly_once() {
        let teardowns = Rc::new(Cell::new(0u32));
        let state_drops = Rc::new(Cell::new(0u32));
        let short = Timing::Duration(Duration::from_millis(100), Curve::Linear);
        let comp = || {
            any(frust_core::component(ProbeComp {
                teardowns: teardowns.clone(),
                state_drops: state_drops.clone(),
            }))
        };
        let mut counter = 0u64;

        // (1) Freeze -> settle drop -> switcher teardown.
        let v1: PatternSwitcherView<(), _> =
            pattern_switcher(1u32, FadeThrough, comp()).timing(short);
        let mut w = build(&v1);
        let size = w.layout(&mut LayoutCtx::new(), &loose());
        let v2: PatternSwitcherView<(), _> =
            pattern_switcher(2u32, FadeThrough, leaf_any(10.0, 10.0)).timing(short);
        v2.rebuild(&v1, &mut w, &mut BuildCtx::new(&mut counter));
        assert_eq!(
            teardowns.get(),
            1,
            "the component is torn down at the freeze"
        );
        assert_eq!(
            state_drops.get(),
            0,
            "its widget (and state) is still painting"
        );

        // A torn-down component still paints its pod (pass-through).
        let mut scene = RecordingScene::default();
        w.layout(&mut LayoutCtx::new(), &loose());
        w.paint(&mut PaintCtx::new(Point::ZERO, size), &mut scene);
        assert!(
            scene.rects.iter().any(|(_, s)| *s == Size::new(30.0, 30.0)),
            "the disposed component's subtree still paints: {:?}",
            scene.rects
        );

        w.driver
            .as_mut()
            .expect("driver created on first paint")
            .advance(ft_ms(10_000.0));
        w.paint(
            &mut PaintCtx::new(Point::ZERO, size),
            &mut RecordingScene::default(),
        );
        let v3: PatternSwitcherView<(), _> =
            pattern_switcher(2u32, FadeThrough, leaf_any(10.0, 10.0)).timing(short);
        v3.rebuild(&v2, &mut w, &mut BuildCtx::new(&mut counter));
        assert!(w.exiting.is_none());
        assert_eq!(state_drops.get(), 1, "dropped once at settle");
        assert_eq!(
            teardowns.get(),
            1,
            "the settle drop is not a second teardown"
        );
        v3.teardown(&mut w, &mut BuildCtx::new(&mut counter));
        assert_eq!((teardowns.get(), state_drops.get()), (1, 1));

        // (2) Freeze -> switcher teardown mid-transition (the exiting pod is
        //     still retained when the switcher itself leaves the tree).
        teardowns.set(0);
        state_drops.set(0);
        let v1: PatternSwitcherView<(), _> =
            pattern_switcher(1u32, FadeThrough, comp()).timing(short);
        let mut w = build(&v1);
        let v2: PatternSwitcherView<(), _> =
            pattern_switcher(2u32, FadeThrough, leaf_any(10.0, 10.0)).timing(short);
        v2.rebuild(&v1, &mut w, &mut BuildCtx::new(&mut counter));
        assert_eq!((teardowns.get(), state_drops.get()), (1, 0));
        v2.teardown(&mut w, &mut BuildCtx::new(&mut counter));
        assert!(
            w.exiting.is_none(),
            "the switcher's teardown drops the exiting pod"
        );
        assert_eq!(
            (teardowns.get(), state_drops.get()),
            (1, 1),
            "torn down once at the freeze, dropped once by the switcher's teardown"
        );
    }

    // --- Supersede mid-transition (A -> B -> C before settle): each outgoing
    //     child is torn down exactly once, at its own freeze. ---

    #[test]
    fn superseding_switches_tear_each_outgoing_child_down_exactly_once() {
        let counters = || (Rc::new(Cell::new(0u32)), Rc::new(Cell::new(0u32)));
        let (a_drop, a_td) = counters();
        let (b_drop, b_td) = counters();
        let (c_drop, c_td) = counters();
        let mut counter = 0u64;

        let va: PatternSwitcherView<(), _> =
            pattern_switcher(1u32, FadeThrough, counting_recorder(&a_drop, &a_td));
        let mut w = build(&va);
        let vb: PatternSwitcherView<(), _> =
            pattern_switcher(2u32, FadeThrough, counting_recorder(&b_drop, &b_td));
        vb.rebuild(&va, &mut w, &mut BuildCtx::new(&mut counter));
        assert_eq!(
            (a_td.get(), a_drop.get()),
            (1, 0),
            "A frozen: torn down, kept"
        );
        assert_eq!((b_td.get(), b_drop.get()), (0, 0), "B is live");

        // C supersedes before A's exit settles: A's pod is dropped (no second
        // teardown), B is frozen and torn down.
        let vc: PatternSwitcherView<(), _> =
            pattern_switcher(3u32, FadeThrough, counting_recorder(&c_drop, &c_td));
        vc.rebuild(&vb, &mut w, &mut BuildCtx::new(&mut counter));
        assert_eq!(
            (a_td.get(), a_drop.get()),
            (1, 1),
            "A superseded: dropped only"
        );
        assert_eq!(
            (b_td.get(), b_drop.get()),
            (1, 0),
            "B frozen: torn down, kept"
        );
        assert_eq!((c_td.get(), c_drop.get()), (0, 0), "C is live");

        // The switcher's own teardown: C (live) is torn down through its view,
        // B (frozen) is only dropped.
        vc.teardown(&mut w, &mut BuildCtx::new(&mut counter));
        assert_eq!((a_td.get(), a_drop.get()), (1, 1));
        assert_eq!((b_td.get(), b_drop.get()), (1, 1), "B dropped, not re-torn");
        assert_eq!(
            c_td.get(),
            1,
            "the live child is torn down by the switcher's teardown"
        );
        drop(w);
        assert_eq!(
            (a_td.get(), b_td.get(), c_td.get()),
            (1, 1, 1),
            "each child torn down exactly once"
        );
        assert_eq!((a_drop.get(), b_drop.get(), c_drop.get()), (1, 1, 1));
    }

    // --- Same-key rebuilds reconcile in place: no transition, no teardown. ---

    #[test]
    fn same_key_rebuilds_reconcile_in_place_with_no_teardown() {
        let torn = Rc::new(Cell::new(0u32));
        let teardowns = Rc::new(Cell::new(0u32));
        let mut counter = 0u64;
        let make = || -> PatternSwitcherView<(), FadeThrough> {
            pattern_switcher(7u32, FadeThrough, counting_recorder(&torn, &teardowns))
        };
        let mut prev = make();
        let mut w = build(&prev);
        for _ in 0..3 {
            let next = make();
            next.rebuild(&prev, &mut w, &mut BuildCtx::new(&mut counter));
            prev = next;
        }
        assert!(w.exiting.is_none(), "no transition staged");
        assert_eq!(
            (teardowns.get(), torn.get()),
            (0, 0),
            "the live child was reconciled in place: never torn down, never dropped"
        );
    }

    // --- reduce_motion collapses to a fast crossfade ---

    #[test]
    fn reduce_motion_collapses_to_fast_crossfade() {
        let theme = reduced_motion_theme();
        // Configure a *directional* pattern (SharedAxis::X slides the incoming
        // child by 30dp) so the collapse to a non-directional crossfade is
        // observable in the child's pod origin.
        let v1: PatternSwitcherView<(), _> =
            pattern_switcher(1u32, SharedAxis::X, leaf_any(10.0, 10.0));
        let mut w = build(&v1);
        let size = w.layout(&mut LayoutCtx::new(), &loose());

        let v2: PatternSwitcherView<(), _> =
            pattern_switcher(2u32, SharedAxis::X, leaf_any(10.0, 10.0));
        let mut counter = 0u64;
        v2.rebuild(&v1, &mut w, &mut BuildCtx::new(&mut counter));

        let mut pctx = PaintCtx::new(Point::ZERO, size).with_theme(&theme);
        w.paint(&mut pctx, &mut RecordingScene::default());

        assert!(
            w.reduce_motion,
            "reduce_motion must be resolved from the threaded theme"
        );
        // FadeThrough collapse: the incoming child never slides (dx stays 0),
        // unlike the configured SharedAxis::X (which offsets it by 30dp at p=0).
        assert_eq!(
            w.child.origin(),
            Point::ZERO,
            "reduce_motion collapses to a non-directional crossfade (no slide)"
        );
    }

    #[test]
    fn without_reduce_motion_the_configured_directional_pattern_slides() {
        // The contrast case for the reduce_motion test above: an untheme'd (no
        // reduce_motion) SharedAxis::X switch DOES offset the incoming child.
        let v1: PatternSwitcherView<(), _> =
            pattern_switcher(1u32, SharedAxis::X, leaf_any(10.0, 10.0));
        let mut w = build(&v1);
        let size = w.layout(&mut LayoutCtx::new(), &loose());

        let v2: PatternSwitcherView<(), _> =
            pattern_switcher(2u32, SharedAxis::X, leaf_any(10.0, 10.0));
        let mut counter = 0u64;
        v2.rebuild(&v1, &mut w, &mut BuildCtx::new(&mut counter));

        w.paint(
            &mut PaintCtx::new(Point::ZERO, size),
            &mut RecordingScene::default(),
        );
        assert!(!w.reduce_motion);
        // At the seed frame (p=0) SharedAxis::X offsets the incoming child by the
        // full 30dp slide.
        assert_eq!(w.child.origin().x, 30.0);
    }

    // --- No-transition steady state paints the child once, plainly ---

    #[test]
    fn steady_state_paints_the_single_child_with_no_layer_or_transform() {
        let v: PatternSwitcherView<(), _> =
            pattern_switcher(1u32, FadeThrough, leaf_any(10.0, 10.0));
        let mut w = build(&v);
        let size = w.layout(&mut LayoutCtx::new(), &loose());

        let mut scene = RecordingScene::default();
        w.paint(&mut PaintCtx::new(Point::ZERO, size), &mut scene);
        assert_eq!(scene.rects.len(), 1, "the single child paints its fill");
        assert!(
            scene.layers.is_empty(),
            "no crossfade layer at steady state"
        );
        assert!(
            scene.transforms.is_empty(),
            "no scale transform at steady state"
        );
    }

    // --- Discard: a staged child at alpha 0 paints into a DiscardScene sink,
    //     recording no ops and no zero-alpha layer (mirrors nav::navigator's
    //     paint_page_layer discard branch). ---

    #[test]
    fn alpha_zero_staged_child_records_no_ops_and_no_zero_alpha_layer() {
        let leaf = leaf_any(10.0, 10.0);
        let mut counter = 0u64;
        let mut pod = crate::authoring::build_child(&leaf, &mut BuildCtx::new(&mut counter));
        let size = pod.layout_child(&mut LayoutCtx::new(), &loose());
        pod.set_origin(Point::ZERO);

        let mut scene = RecordingScene::default();
        let layer = PatternLayer {
            dx: 0.0,
            dy: 0.0,
            alpha: 0.0,
            scale: 1.0,
        };
        paint_staged_child(
            &mut pod,
            &mut RetainedBoundary::new(),
            &mut PaintCtx::new(Point::ZERO, size),
            &mut scene,
            layer,
        );

        assert!(scene.rects.is_empty(), "an alpha-0 child records no fill");
        assert!(
            scene.layers.is_empty(),
            "no zero-alpha push_layer is recorded either"
        );
    }

    // --- Retained boundaries: a staged child at a slide/fade step paints
    //     through its own boundary — a recording bracket on the seed frame
    //     (the exiting child still at rest), the retained page once it is
    //     resident — and a scale step paints inline. Mirrors nav::navigator's
    //     paint_page_layer. ---

    /// A ledger reporting `keys` resident as 10x10 pages at scale 1 — the
    /// extent and scale a `leaf_any(10.0, 10.0)` child's boundary asks for
    /// under a recorder with no transform.
    fn resident(keys: &[RetainedKey]) -> RetainedLedger {
        RetainedLedger::from_entries(1, keys.iter().map(|k| (k.get(), (10, 10), 1.0)))
    }

    /// Switch `v1`'s widget to a second key with the same pattern, returning
    /// the widget, its size, and the key the child held before the switch.
    fn switched<P: TransitionPattern + Clone + 'static>(
        pattern: P,
    ) -> (PatternSwitcherWidget<P>, Size, RetainedKey) {
        let timing = Timing::Duration(Duration::from_millis(100), Curve::Linear);
        let v1: PatternSwitcherView<(), _> =
            pattern_switcher(1u32, pattern.clone(), leaf_any(10.0, 10.0)).timing(timing);
        let mut w = build(&v1);
        let size = w.layout(&mut LayoutCtx::new(), &loose());
        let live_key = w.child_boundary.key();
        let v2: PatternSwitcherView<(), _> =
            pattern_switcher(2u32, pattern, leaf_any(10.0, 10.0)).timing(timing);
        let mut counter = 0u64;
        v2.rebuild(&v1, &mut w, &mut BuildCtx::new(&mut counter));
        w.layout(&mut LayoutCtx::new(), &loose());
        (w, size, live_key)
    }

    #[test]
    fn the_seed_frame_records_the_exiting_child_under_the_key_it_held_while_live() {
        let (mut w, size, live_key) = switched(SharedAxis::X);
        assert_eq!(
            w.exiting_boundary.key(),
            live_key,
            "the frozen pod keeps the boundary it painted through while live"
        );
        assert_ne!(
            w.child_boundary.key(),
            live_key,
            "the fresh child takes the other key"
        );

        let ledger = RetainedLedger::empty();
        let mut scene = RetainedRecordingScene::default();
        w.paint(
            &mut PaintCtx::for_test(Point::ZERO, size, ft_ms(0.0)).with_retained_ledger(&ledger),
            &mut scene,
        );
        // p = 0: the exiting child sits at rest (dx 0, alpha 1); the incoming
        // one is at alpha 0 (discarded).
        assert_eq!(
            scene.retained_pushes,
            vec![(live_key.get(), Point::ZERO, size, 1.0, 1.0)],
            "one recording bracket, keyed by the exiting child's own key, at scale 1"
        );
        assert_eq!(scene.retained_pops, 1, "the bracket is balanced");
        assert!(scene.draws.is_empty(), "nothing is resident yet");
    }

    #[test]
    fn a_clean_resident_exiting_child_composites_its_page_as_it_fades() {
        let (mut w, size, live_key) = switched(FadeScale);
        let empty = RetainedLedger::empty();
        w.paint(
            &mut PaintCtx::for_test(Point::ZERO, size, ft_ms(0.0)).with_retained_ledger(&empty),
            &mut RetainedRecordingScene::default(),
        );

        // 15ms into the 100ms linear duration: progress 0.15, inside
        // FadeScale's simultaneous-fade window — both children visible.
        let ledger = resident(&[live_key]);
        let mut scene = RetainedRecordingScene::default();
        w.paint(
            &mut PaintCtx::for_test(Point::ZERO, size, ft_ms(15.0)).with_retained_ledger(&ledger),
            &mut scene,
        );
        assert_eq!(
            scene.draws.len(),
            1,
            "the exiting page is drawn: {:?}",
            scene.draws
        );
        let (key, origin, draw_size, alpha, scale) = scene.draws[0];
        assert_eq!(
            (key, origin, draw_size, scale),
            (live_key.get(), Point::ZERO, size, 1.0)
        );
        assert!(
            alpha > 0.0 && alpha < 1.0,
            "at the fade's own alpha (was {alpha})"
        );
        assert_eq!(
            scene.rects.len(),
            1,
            "only the incoming child paints a body; the exiting one is composited"
        );
        assert!(
            scene.retained_pushes.is_empty(),
            "the incoming child's scale step is never bracketed: {:?}",
            scene.retained_pushes
        );
        assert_eq!(
            scene.transform_pushes, 1,
            "the incoming child's scale step paints inline under a push_transform"
        );
    }

    #[test]
    fn without_a_ledger_staged_children_paint_with_no_bracket() {
        let (mut w, size, _) = switched(FadeScale);
        w.paint(
            &mut PaintCtx::for_test(Point::ZERO, size, ft_ms(0.0)),
            &mut RetainedRecordingScene::default(),
        );
        let mut scene = RetainedRecordingScene::default();
        w.paint(
            &mut PaintCtx::for_test(Point::ZERO, size, ft_ms(15.0)),
            &mut scene,
        );
        assert!(scene.retained_pushes.is_empty() && scene.draws.is_empty());
        assert_eq!(scene.rects.len(), 2, "both children paint their bodies");
        assert_eq!(scene.layers.len(), 2, "each under its own fade layer");
    }

    #[test]
    fn a_slid_child_is_never_recorded_while_it_overhangs_the_switcher() {
        // SharedAxis::X slides children by 30dp. Past the split (p = 0.5) the
        // incoming child sits at dx = 15: partly outside the switcher's rect,
        // where a renderer would refuse to retain it, so it paints directly.
        let (mut w, size, _) = switched(SharedAxis::X);
        let ledger = RetainedLedger::empty();
        w.paint(
            &mut PaintCtx::for_test(Point::ZERO, size, ft_ms(0.0)).with_retained_ledger(&ledger),
            &mut RetainedRecordingScene::default(),
        );
        let mut scene = RetainedRecordingScene::default();
        w.paint(
            &mut PaintCtx::for_test(Point::ZERO, size, ft_ms(50.0)).with_retained_ledger(&ledger),
            &mut scene,
        );
        assert!(
            scene.retained_pushes.is_empty(),
            "no bracket: {:?}",
            scene.retained_pushes
        );
        assert_eq!(
            scene.rects,
            vec![(Point::new(15.0, 0.0), size)],
            "the incoming child paints at its slid origin"
        );
    }

    // --- The key pair is reserved once, at construction, and outlives every
    //     switch this widget instance stages. ---

    fn key_pair<P: TransitionPattern + Clone + 'static>(w: &PatternSwitcherWidget<P>) -> [u64; 2] {
        let mut keys = [w.child_boundary.key().get(), w.exiting_boundary.key().get()];
        keys.sort_unstable();
        keys
    }

    #[test]
    fn the_key_pair_is_stable_across_multiple_switches_on_the_same_widget() {
        let v1: PatternSwitcherView<(), _> =
            pattern_switcher(1u32, FadeThrough, leaf_any(10.0, 10.0));
        let mut w = build(&v1);
        let pair = key_pair(&w);
        assert_eq!(pair[1], pair[0] + 1, "a reserved consecutive pair");
        let mut counter = 0u64;

        let v2: PatternSwitcherView<(), _> =
            pattern_switcher(2u32, FadeThrough, leaf_any(10.0, 10.0));
        v2.rebuild(&v1, &mut w, &mut BuildCtx::new(&mut counter));
        assert_eq!(
            key_pair(&w),
            pair,
            "a switch does not reassign the key pair"
        );

        let v3: PatternSwitcherView<(), _> =
            pattern_switcher(3u32, FadeThrough, leaf_any(10.0, 10.0));
        v3.rebuild(&v2, &mut w, &mut BuildCtx::new(&mut counter));
        assert_eq!(
            key_pair(&w),
            pair,
            "a second switch on the same widget still keeps the same key pair"
        );
    }

    // --- Two switcher instances never alias each other's cache slot. ---

    #[test]
    fn two_switcher_instances_get_disjoint_key_pairs() {
        let v: PatternSwitcherView<(), _> =
            pattern_switcher(1u32, FadeThrough, leaf_any(10.0, 10.0));
        let w1 = build(&v);
        let w2 = build(&v);
        let (a, b) = (key_pair(&w1), key_pair(&w2));
        assert!(
            a.iter().all(|k| !b.contains(k)),
            "two switcher instances never share a key: {a:?} vs {b:?}"
        );
    }
}