frust-glyph 0.5.2

Glyph design-system catalog for Frust: a terminal-native, dark-first, monospace-led widget set with bundled Space Mono and IBM Plex Mono fonts.
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
//! Glyph toast + host/queue: a status-dot +
//! message bubble ([`Toast`]), and [`ToastHost`] — the retained overlay
//! widget that plays a queue of toast requests one at a time with authored
//! enter/hold/exit motion and a 2.4s auto-dismiss.
//!
//! # Toast (the leaf)
//!
//! [`ToastView`]/[`ToastWidget`]: a status dot + message row painted on the
//! Glyph "overlay" surface role (`colors.surface_container_highest` — the
//! same `bg-overlay` token [`super::progress`]'s track uses; the Glyph source
//! doesn't name toast explicitly, but it *is* an overlay surface, so this
//! reuses the role rather than inventing a new one), `shape.medium` corner
//! radius (Glyph's canonical `--radius-md` = 10px), and the Glyph toast
//! elevation recipe
//! (`elevation.level4.shadow(brightness)` — exactly `0 12px 32px` dark /
//! `rgba(...,.12)` light, the cited toast shadow). The dot
//! color follows [`ToastVariant`]: `Plain` (default) is the accent
//! (`colors.primary`); `Info`/`Success`/`Warning` resolve `StatusPalette`
//! (Glyph's success/warning/info extension); `Error` resolves
//! `colors.error` (a first-class `ColorScheme` role). Message color is
//! `colors.on_surface` — the same label-color simplification
//! `material::chips` documents (not the more precise
//! `on_surface_container_highest`, which `TextView` has no themed role for
//! yet). The message's family is the live theme's `bodyMedium` type-scale
//! role (IBM Plex Mono under Glyph's own scale), resolved by the `Text` child
//! at layout via `.themed_family(..)`, so a theme swap repaints it; unthemed,
//! it keeps `Text`'s own system family.
//!
//! # ToastHost + queue policy
//!
//! [`ToastHostView`] takes a `Vec<String>` FIFO snapshot (the app's own
//! growing request log — see [`show`]) every rebuild; [`ToastHostWidget`]
//! retains a `next_index` cursor plus at most one [`ActiveToast`] — **v1
//! policy: exactly one visible toast at a time, queued FIFO**, never
//! stacked. `rebuild` is where all queue bookkeeping happens (building/
//! tearing down the active [`ChildPod`] needs a [`frust::authoring::BuildCtx`],
//! unavailable from `layout`/`paint`): a `Done` active toast is torn down and
//! `next_index` advances; if nothing is active and a next request exists, it
//! starts fresh. The host never mutates the *view-supplied* queue itself
//! (the controlled-component idiom `docs/CODE_STANDARDS.md` names) — it only
//! reads a fresh snapshot each rebuild and clamps its own cursor to it.
//!
//! **Known v1 limitation:** since the queue is the app's own ever-growing
//! `Vec`, a very long-running session accumulates every message ever shown,
//! and the app cannot safely trim it from the outside. The host's cursor and
//! whether a toast is active are retained state the app cannot observe, and
//! both matter: while a toast plays, `next_index` still points AT its entry
//! and only advances past it when it finishes (in `maybe_advance_queue`,
//! after `rebuild`'s clamp), so cutting the vec to a length at or below that
//! index — clearing it included — makes the post-finish advance land past
//! the new end, and the next message pushed there is skipped, never shown.
//! Draining from the front shifts every pending entry under the cursor and
//! skips or loses them. Only removing entries strictly after the one being
//! shown is harmless (it cancels pending toasts), and the app cannot tell
//! which one that is. Treat the vec as append-only and bound growth at the
//! producers instead (rate-limit what can be triggered repeatedly), as
//! `examples/native-widgets-demo` does; a later revision may expose a
//! consumed count so an app can trim what the host is provably done with.
//!
//! # Anchoring (framework-side positioning)
//!
//! [`ToastHostWidget::layout`] fills the incoming max constraints (a
//! [`frust::Stack`] loosens its children, so the host spans the whole stack)
//! rather than sizing to the active toast's own content, and positions the
//! toast internally per [`ToastAnchor`] (`.anchor()` on [`ToastHostView`],
//! default [`ToastAnchor::BottomCenter`]) — apps no longer wrap the host in
//! their own `Align`. Margins are [`EDGE_MARGIN`] (10px) from the anchored
//! edges, additionally widened by [`frust::authoring::WindowInsets::padding`] on
//! those same edges (`ctx.window_insets()`, **not** `view_insets` — IME
//! avoidance stays out of scope for v1) so a bottom toast clears gesture-nav
//! insets with no app-side `SafeArea`. The host itself stays
//! **event-transparent**: it never overrides `Widget::event`, so the
//! default no-op (`EventResult::Ignored`) lets every pointer event — inside
//! or outside the toast's own (smaller) rect — pass through to whatever the
//! host overlays. Enter/exit motion follows the anchored edge: bottom
//! anchors rise from below (a positive slide offset settling to zero);
//! top anchors drop from above (the pre-existing negative-offset motion) —
//! see [`ToastAnchor::is_top`].
//!
//! # Timeline
//!
//! Enter: 220ms (`MotionScheme::durations.base`) with the Glyph spatial
//! easing (`Cubic(0.34, 1.35, 0.64, 1.0)` — an authored overshoot); a
//! vertical slide from [`ENTER_OFFSET_FRACTION`] (140%) of the toast's own
//! height above its resting position, plus a fade. Hold: exactly
//! [`HOLD_DURATION`] (2.4s — the Glyph source's authored
//! auto-dismiss value), advanced via **`FrameTime` differencing, never
//! `Instant::now()`** (`docs/CODE_STANDARDS.md`'s No-`Instant::now()` rule).
//! Exit: 150ms (`durations.fast`) with the Glyph exit easing
//! (`Cubic(0.4, 0.0, 1.0, 1.0)`), fading/sliding back out. `reduce_motion`
//! collapses both enter and exit to a single fast (120ms) linear crossfade
//! (no slide) — the Details' "toast becomes fast crossfade" rule, mirroring
//! `nav::transition::resolve_spec`'s reduce-motion collapse.
//!
//! All three durations/easings are **exact source values** (see
//! `MotionScheme::glyph`'s doc comment), not approximations — only
//! [`ENTER_OFFSET_FRACTION`] (the slide distance) is this widget's own choice.

use std::time::Duration;

use frust::authoring::Role;
use frust::authoring::{
    AnyView, BoxConstraints, BuildCtx, ChangeFlags, ChildPod, LayoutCtx, PaintCtx, PaintScene,
    SemanticsCtx, ThemeTextType, View, Widget, WindowEdgeInsets, any,
};
use frust::{Curve, FrameTime};
use frust::{StatusPalette, Theme};
use kurbo::{Affine, Point, Size};
use peniko::Color;

use frust::Timing;
use frust::{TransitionDriver, make_driver};

// ---------------------------------------------------------------------
// Toast (the leaf)
// ---------------------------------------------------------------------

/// A toast's status-dot color category. See the [module docs](self).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ToastVariant {
    /// The plain accent dot (default) — no particular status.
    #[default]
    Plain,
    Info,
    Success,
    Warning,
    Error,
}

/// The row height floor, in logical px (a one-line toast never shrinks below
/// this). An original, hand-picked value.
const MIN_HEIGHT: f64 = 44.0;
/// Horizontal padding around the content row. An original, hand-picked value.
const PAD_X: f64 = 14.0;
/// Vertical padding above/below the content when the message wraps taller
/// than [`MIN_HEIGHT`] would otherwise need. An original, hand-picked value.
const PAD_Y: f64 = 10.0;
/// Gap between the status dot and the message text. An original, hand-picked value.
const DOT_GAP: f64 = 10.0;
/// Status-dot diameter. This widget's own choice.
const DOT_DIAMETER: f64 = 8.0;

/// Unthemed corner-radius fallback — Glyph's canonical `--radius-md` (10px).
const FALLBACK_RADIUS: f64 = 10.0;
/// Unthemed surface fallback — Glyph dark's `bg-overlay` (`#272d3d`), the
/// same role [`super::progress`]'s track uses.
const FALLBACK_SURFACE: Color = Color::from_rgb8(0x27, 0x2d, 0x3d);
/// Unthemed dot fallbacks, one per [`ToastVariant`] — Glyph dark's amber
/// accent / cyan info / success / warning / error tokens.
const FALLBACK_PLAIN: Color = Color::from_rgb8(0xff, 0xb6, 0x27);
const FALLBACK_INFO: Color = Color::from_rgb8(0x5e, 0xc8, 0xd8);
const FALLBACK_SUCCESS: Color = Color::from_rgb8(0x5f, 0xd8, 0x8f);
const FALLBACK_WARNING: Color = Color::from_rgb8(0xf5, 0xc8, 0x60);
const FALLBACK_ERROR: Color = Color::from_rgb8(0xff, 0x6b, 0x6b);
/// Unthemed shadow fallbacks — Glyph dark's exact toast recipe (`0 12px 32px
/// rgba(0,0,0,.4)`).
const FALLBACK_SHADOW_Y: f64 = 12.0;
const FALLBACK_SHADOW_BLUR: f64 = 32.0;
const FALLBACK_SHADOW_ALPHA: f32 = 0.40;

/// Return `color` with its alpha channel replaced by `alpha` (mirrors the
/// per-module helper of the same shape used across `frust-widgets`).
fn with_alpha(color: Color, alpha: f32) -> Color {
    let c = color.components;
    Color::new([c[0], c[1], c[2], alpha])
}

/// A declarative Glyph toast. See the [module docs](self).
pub struct ToastView {
    message: String,
    variant: ToastVariant,
}

/// Create a toast with the given message (default [`ToastVariant::Plain`]).
pub fn toast(message: impl Into<String>) -> ToastView {
    ToastView {
        message: message.into(),
        variant: ToastVariant::Plain,
    }
}

/// PascalCase alias for [`toast`], matching the widget-fn vocabulary
/// (`Button`/`Image`/…).
#[allow(non_snake_case)]
pub fn Toast(message: impl Into<String>) -> ToastView {
    toast(message)
}

impl ToastView {
    /// Set the status-dot [`ToastVariant`] (default [`ToastVariant::Plain`]).
    pub fn variant(mut self, variant: ToastVariant) -> Self {
        self.variant = variant;
        self
    }
}

/// Build the type-erased message-label view, shared by build/rebuild/
/// teardown so it stays consistent (mirrors `material::chips`' analogous
/// `assist_label_view` helper). Its family comes from the theme's
/// `bodyMedium` role.
fn message_view<State: 'static>(message: String) -> AnyView<State> {
    any::<State, _>(frust::text(message).themed_family(ThemeTextType::BodyMedium))
}

impl<State: 'static> View<State> for ToastView {
    type Element = ToastWidget;

    fn build(&self, ctx: &mut BuildCtx<'_>) -> ToastWidget {
        ToastWidget {
            message: frust::authoring::build_child::<State>(
                &message_view::<State>(self.message.clone()),
                ctx,
            ),
            message_text: self.message.clone(),
            variant: self.variant,
        }
    }

    fn rebuild(
        &self,
        prev: &Self,
        element: &mut ToastWidget,
        ctx: &mut BuildCtx<'_>,
    ) -> ChangeFlags {
        let mut flags = ChangeFlags::NONE;
        if prev.message != self.message {
            element.message_text = self.message.clone();
            let prev_view = message_view::<State>(prev.message.clone());
            let next_view = message_view::<State>(self.message.clone());
            flags |=
                frust::authoring::rebuild_child(&prev_view, &next_view, &mut element.message, ctx);
        }
        if prev.variant != self.variant {
            element.variant = self.variant;
            flags |= ChangeFlags::PAINT;
        }
        flags
    }

    fn teardown(&self, element: &mut ToastWidget, ctx: &mut BuildCtx<'_>) {
        let view = message_view::<State>(self.message.clone());
        frust::authoring::teardown_child(&view, &mut element.message, ctx);
    }
}

/// The retained widget for a [`ToastView`]. See the [module docs](self).
pub struct ToastWidget {
    message: ChildPod,
    message_text: String,
    variant: ToastVariant,
}

impl ToastWidget {
    /// The status-dot color for `variant`: `Plain`/`Error` resolve directly
    /// from `ColorScheme`; `Info`/`Success`/`Warning` resolve the themed
    /// [`StatusPalette`] extension (falling back to `colors.primary` if a
    /// theme carries none — every shipping baseline attaches one, so this is
    /// only reachable for a hand-built `Theme`).
    fn resolve_dot_color(theme: Option<&Theme>, variant: ToastVariant) -> Color {
        match theme {
            Some(t) => match variant {
                ToastVariant::Plain => t.scheme().primary,
                ToastVariant::Error => t.scheme().error,
                ToastVariant::Info | ToastVariant::Success | ToastVariant::Warning => t
                    .extension::<StatusPalette>()
                    .map(|p| {
                        let c = p.colors(t.brightness);
                        match variant {
                            ToastVariant::Info => c.info,
                            ToastVariant::Success => c.success,
                            ToastVariant::Warning => c.warning,
                            _ => unreachable!(),
                        }
                    })
                    .unwrap_or(t.scheme().primary),
            },
            None => match variant {
                ToastVariant::Plain => FALLBACK_PLAIN,
                ToastVariant::Info => FALLBACK_INFO,
                ToastVariant::Success => FALLBACK_SUCCESS,
                ToastVariant::Warning => FALLBACK_WARNING,
                ToastVariant::Error => FALLBACK_ERROR,
            },
        }
    }

    /// The surface fill: themed `colors.surface_container_highest`, or the
    /// unthemed [`FALLBACK_SURFACE`]. The message row's own color comes from
    /// `TextView`'s default `ThemeTextColor::OnSurface` role (see the
    /// [module docs](self)) — not resolved here.
    fn resolve_surface_color(theme: Option<&Theme>) -> Color {
        match theme {
            Some(t) => t.scheme().surface_container_highest,
            None => FALLBACK_SURFACE,
        }
    }

    /// The `(y_offset, blur_std_dev, color)` shadow triple: themed
    /// `elevation.level4.shadow(brightness)` (Glyph's exact toast recipe), or
    /// the unthemed [`FALLBACK_SHADOW_Y`]/[`FALLBACK_SHADOW_BLUR`]/black-at-
    /// [`FALLBACK_SHADOW_ALPHA`].
    fn resolve_shadow(theme: Option<&Theme>) -> (f64, f64, Color) {
        match theme {
            Some(t) => {
                let shadow = t.elevation.level4.shadow(t.brightness);
                (
                    shadow.y_offset,
                    shadow.blur_std_dev,
                    with_alpha(t.scheme().shadow, shadow.color_alpha),
                )
            }
            None => (
                FALLBACK_SHADOW_Y,
                FALLBACK_SHADOW_BLUR,
                with_alpha(Color::from_rgb8(0, 0, 0), FALLBACK_SHADOW_ALPHA),
            ),
        }
    }
}

impl Widget for ToastWidget {
    fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
        let inner_max = Size::new(f64::INFINITY, f64::INFINITY);
        let text_size = self
            .message
            .layout_child(ctx, &BoxConstraints::loose(inner_max));
        let content_h = text_size.height.max(DOT_DIAMETER);
        let height = MIN_HEIGHT.max(content_h + PAD_Y * 2.0);
        self.message.set_origin(Point::new(
            PAD_X + DOT_DIAMETER + DOT_GAP,
            (height - text_size.height) / 2.0,
        ));
        let width = PAD_X * 2.0 + DOT_DIAMETER + DOT_GAP + text_size.width;
        bc.constrain(Size::new(width, height))
    }

    fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
        let theme = Theme::from_paint_ctx(ctx);
        let surface = Self::resolve_surface_color(theme);
        let radius = theme.map(|t| t.shape.medium).unwrap_or(FALLBACK_RADIUS);
        let (shadow_y, shadow_blur, shadow_color) = Self::resolve_shadow(theme);
        let size = ctx.size();
        let origin = ctx.origin();

        scene.draw_shadow(
            Point::new(origin.x, origin.y + shadow_y),
            size,
            radius,
            shadow_blur,
            shadow_color,
        );
        scene.fill_rounded_rect(origin, size, radius, surface);

        let dot_color = Self::resolve_dot_color(theme, self.variant);
        let dot_cy = origin.y + size.height / 2.0;
        let dot_cx = origin.x + PAD_X + DOT_DIAMETER / 2.0;
        scene.fill_rounded_rect(
            Point::new(dot_cx - DOT_DIAMETER / 2.0, dot_cy - DOT_DIAMETER / 2.0),
            Size::new(DOT_DIAMETER, DOT_DIAMETER),
            DOT_DIAMETER / 2.0,
            dot_color,
        );

        self.message.paint_child(ctx, scene);
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        ctx.push_node(Role::Status, |node| {
            node.set_label(self.message_text.as_str());
        });
    }

    frust::authoring::visit_children!(message);
}

// ---------------------------------------------------------------------
// ToastHost + queue
// ---------------------------------------------------------------------

/// Push `message` onto a toast request queue (FIFO) — pair with
/// [`toast_host`]'s queue snapshot (see the [module docs](self)). A plain,
/// uncomplicated `push` — the app owns the `Vec<String>` (e.g. a
/// `Component::State` field).
pub fn show(queue: &mut Vec<String>, message: impl Into<String>) {
    queue.push(message.into());
}

/// Enter duration (`durations.base`, exact Glyph source value — see the
/// [module docs](self)).
const ENTER_DURATION: Duration = Duration::from_millis(220);
/// Enter easing (Glyph's `spatial` cubic-bezier, exact source value).
const ENTER_CURVE: Curve = Curve::Cubic(0.34, 1.35, 0.64, 1.0);
/// Exit duration (`durations.fast`, exact Glyph source value).
const EXIT_DURATION: Duration = Duration::from_millis(150);
/// Exit easing (Glyph's `exit` cubic-bezier, exact source value).
const EXIT_CURVE: Curve = Curve::Cubic(0.4, 0.0, 1.0, 1.0);
/// Hold duration: exactly 2.4s (the Glyph source's authored
/// auto-dismiss value).
const HOLD_DURATION: Duration = Duration::from_millis(2400);
/// `reduce_motion`'s collapsed crossfade duration (mirrors
/// `nav::transition::REDUCE_MOTION_DURATION`).
const REDUCE_MOTION_DURATION: Duration = Duration::from_millis(120);
/// The enter slide's starting offset above the resting position, as a
/// fraction of the toast's own height ("from -140%").
/// An original, hand-picked value.
const ENTER_OFFSET_FRACTION: f64 = 1.4;

/// The `(enter, exit)` [`Timing`]s for the current `reduce_motion` state:
/// the authored spatial/exit durations+curves, or both collapsed to
/// [`REDUCE_MOTION_DURATION`] linear (the Details' "toast becomes fast
/// crossfade" rule).
fn resolve_timings(reduce_motion: bool) -> (Timing, Timing) {
    if reduce_motion {
        let t = Timing::Duration(REDUCE_MOTION_DURATION, Curve::Linear);
        (t, t)
    } else {
        (
            Timing::Duration(ENTER_DURATION, ENTER_CURVE),
            Timing::Duration(EXIT_DURATION, EXIT_CURVE),
        )
    }
}

/// [`ActiveToast`]'s lifecycle phase.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ToastPhase {
    Enter,
    Hold,
    Exit,
    /// Fully exited; a no-op phase until the next `rebuild` tears it down
    /// and starts the next queued request (see the [module docs](self)).
    Done,
}

/// A currently-playing toast: its content pod plus timeline state.
struct ActiveToast {
    message: String,
    child: ChildPod,
    phase: ToastPhase,
    /// The active enter/exit progress driver — lazily built the first time
    /// [`ToastHostWidget::advance`] sees this phase, since `rebuild` (where
    /// the toast is created) has no theme to resolve a [`Timing`] from (only
    /// `LayoutCtx`/`PaintCtx` carry one).
    driver: Option<TransitionDriver>,
    /// Elapsed hold time, accumulated via `FrameTime` differencing (never
    /// `Instant::now()` — `docs/CODE_STANDARDS.md`).
    hold_elapsed: Duration,
    last_time: Option<FrameTime>,
}

impl frust::authoring::VisitPods for ActiveToast {
    fn visit_pods(&self, visitor: &mut dyn FnMut(&ChildPod)) {
        visitor(&self.child);
    }
}

/// Where [`ToastHostWidget`] positions the active toast within the host's
/// (now full-bleed) bounds. See the [module docs](self)'s Anchoring section.
///
/// Default [`ToastAnchor::BottomCenter`] — the framework's v1 opinionated
/// default, matching most platform toast conventions (Android's `Toast`,
/// Material Snackbar).
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum ToastAnchor {
    TopLeft,
    TopCenter,
    TopRight,
    BottomLeft,
    #[default]
    BottomCenter,
    BottomRight,
}

impl ToastAnchor {
    /// Whether `self` anchors to the top edge (`TopLeft`/`TopCenter`/
    /// `TopRight`) rather than the bottom — the axis the enter/exit slide
    /// direction and vertical margin both key off (see the [module
    /// docs](self)'s Anchoring section).
    pub fn is_top(self) -> bool {
        matches!(
            self,
            ToastAnchor::TopLeft | ToastAnchor::TopCenter | ToastAnchor::TopRight
        )
    }
}

/// Margin from the anchored edge(s), in logical px — matches the glyph
/// catalog's earlier top margin (`lib.rs`'s `EdgeInsets { top: 10.0,
/// .. }` wrapper this host-side anchoring supersedes). An original,
/// hand-picked value, additionally widened by [`frust::authoring::WindowInsets::padding`] on
/// the anchored edges (see the [module docs](self)'s Anchoring section).
const EDGE_MARGIN: f64 = 10.0;

/// Resolve the active toast's origin within the host's `host_size`, per
/// `anchor`, [`EDGE_MARGIN`], and the window's safe-area `insets` on the
/// anchored edges — additive with the margin (not `max`), so e.g. a
/// bottom-anchored toast's rest position sits `EDGE_MARGIN + insets.bottom`
/// above the host's bottom edge.
fn anchor_origin(
    anchor: ToastAnchor,
    host_size: Size,
    toast_size: Size,
    insets: WindowEdgeInsets,
) -> Point {
    let x = match anchor {
        ToastAnchor::TopLeft | ToastAnchor::BottomLeft => EDGE_MARGIN + insets.left,
        ToastAnchor::TopCenter | ToastAnchor::BottomCenter => {
            (host_size.width - toast_size.width) / 2.0
        }
        ToastAnchor::TopRight | ToastAnchor::BottomRight => {
            host_size.width - EDGE_MARGIN - insets.right - toast_size.width
        }
    };
    let y = if anchor.is_top() {
        EDGE_MARGIN + insets.top
    } else {
        host_size.height - EDGE_MARGIN - insets.bottom - toast_size.height
    };
    Point::new(x, y)
}

/// A declarative toast-request queue snapshot. See the [module docs](self).
pub struct ToastHostView {
    pending: Vec<String>,
    anchor: ToastAnchor,
}

/// Create a toast host reading `pending` (the app's FIFO request log — see
/// [`show`]) as this rebuild's snapshot, anchored [`ToastAnchor::BottomCenter`]
/// by default — see [`ToastHostView::anchor`].
pub fn toast_host(pending: impl Into<Vec<String>>) -> ToastHostView {
    ToastHostView {
        pending: pending.into(),
        anchor: ToastAnchor::default(),
    }
}

impl ToastHostView {
    /// Set the host's [`ToastAnchor`] (default [`ToastAnchor::BottomCenter`]).
    pub fn anchor(mut self, anchor: ToastAnchor) -> Self {
        self.anchor = anchor;
        self
    }
}

/// PascalCase alias for [`toast_host`], matching the widget-fn vocabulary
/// (`Button`/`Image`/…).
#[allow(non_snake_case)]
pub fn ToastHost(pending: impl Into<Vec<String>>) -> ToastHostView {
    toast_host(pending)
}

impl<State: 'static> View<State> for ToastHostView {
    type Element = ToastHostWidget;

    fn build(&self, ctx: &mut BuildCtx<'_>) -> ToastHostWidget {
        let mut widget = ToastHostWidget {
            queue: self.pending.clone(),
            next_index: 0,
            active: None,
            anchor: self.anchor,
        };
        let _ = widget.maybe_advance_queue::<State>(ctx);
        widget
    }

    fn rebuild(
        &self,
        prev: &Self,
        element: &mut ToastHostWidget,
        ctx: &mut BuildCtx<'_>,
    ) -> ChangeFlags {
        element.queue = self.pending.clone();
        element.next_index = element.next_index.min(element.queue.len());
        let anchor_changed = prev.anchor != self.anchor;
        element.anchor = self.anchor;
        let structural_change = element.maybe_advance_queue::<State>(ctx);
        // The active child's own paint-driven animation covers redraw needs
        // when nothing structural happened, so this reports plain PAINT in
        // that case — cheap, and correct (never under-reports). Either an
        // anchor swap (repositions the toast) or a structural queue change
        // (a new child pod was built or the active one torn down — a fresh/
        // absent pod has never been laid out, so it MUST be relaid-out this
        // frame, not just repainted; see the module's diagnosis) additionally
        // forces LAYOUT (the host's own layout resolves the anchored origin,
        // not paint).
        if anchor_changed || structural_change {
            ChangeFlags::LAYOUT | ChangeFlags::PAINT
        } else {
            ChangeFlags::PAINT
        }
    }

    fn teardown(&self, element: &mut ToastHostWidget, ctx: &mut BuildCtx<'_>) {
        if let Some(active) = element.active.take() {
            let view = any::<State, _>(toast(active.message));
            let mut pod = active.child;
            frust::authoring::teardown_child(&view, &mut pod, ctx);
        }
    }
}

/// The retained widget for a [`ToastHostView`]. See the [module docs](self).
pub struct ToastHostWidget {
    /// The last-seen full request queue (a growing FIFO log — see the
    /// [module docs](self)'s Known v1 limitation).
    queue: Vec<String>,
    /// Index of the next not-yet-started request in `queue`.
    next_index: usize,
    active: Option<ActiveToast>,
    /// Where the active toast is positioned within the (full-bleed) host —
    /// see the [module docs](self)'s Anchoring section.
    anchor: ToastAnchor,
}

impl ToastHostWidget {
    /// If the current `active` toast is [`ToastPhase::Done`], tear it down
    /// and advance `next_index`; then, if nothing is active and a next
    /// request exists, start it. Building/tearing down a [`ChildPod`] needs
    /// a [`BuildCtx`], so this only ever runs from `build`/`rebuild` — see
    /// the [module docs](self).
    ///
    /// Returns whether the active toast was **structurally** changed — a new
    /// child pod was built and/or the previous one torn down — as opposed to
    /// the common case where the existing pod just keeps playing. A caller
    /// (`rebuild`) MUST fold a `true` return into `ChangeFlags::LAYOUT`: a
    /// freshly built pod has never been laid out, so `Widget::layout` MUST
    /// run this frame, not just `paint` (a structural child change is a
    /// layout-affecting event per the widget contract, not a paint-only one
    /// — the mobile layout-skip gate honors under-reported flags literally,
    /// see the module's diagnosis doc comment).
    fn maybe_advance_queue<State: 'static>(&mut self, ctx: &mut BuildCtx<'_>) -> bool {
        let mut structural_change = false;
        if matches!(
            self.active.as_ref().map(|a| a.phase),
            Some(ToastPhase::Done)
        ) {
            let active = self.active.take().expect("checked Some above");
            let view = any::<State, _>(toast(active.message));
            let mut pod = active.child;
            frust::authoring::teardown_child(&view, &mut pod, ctx);
            self.next_index += 1;
            structural_change = true;
        }
        if self.active.is_none()
            && let Some(message) = self.queue.get(self.next_index).cloned()
        {
            let child = frust::authoring::build_child::<State>(
                &any::<State, _>(toast(message.clone())),
                ctx,
            );
            self.active = Some(ActiveToast {
                message,
                child,
                phase: ToastPhase::Enter,
                driver: None,
                hold_elapsed: Duration::ZERO,
                last_time: None,
            });
            structural_change = true;
        }
        structural_change
    }

    /// Advance the active toast's phase machine to frame time `now`,
    /// returning the shown-progress to paint at (`0.0` hidden, `1.0` fully
    /// shown — transiently `> 1.0` mid-enter under the spatial easing's
    /// overshoot), or `None` if nothing is active. Mutates `self.active`'s
    /// phase/driver/hold_elapsed in place.
    ///
    /// Factored out of `paint` so the full enter→hold→exit timeline is
    /// drivable with synthetic [`FrameTime`]s in a unit test — a bare
    /// `PaintCtx` can't be constructed at an arbitrary frame time outside
    /// `frust-core` (mirrors `LoadingIndicatorWidget::step`'s rationale).
    fn advance(&mut self, now: FrameTime, enter: Timing, exit: Timing) -> Option<f64> {
        let active = self.active.as_mut()?;
        let shown = match active.phase {
            ToastPhase::Enter => {
                let adv = active
                    .driver
                    .get_or_insert_with(|| make_driver(enter).0)
                    .advance(now);
                if adv.done {
                    active.phase = ToastPhase::Hold;
                    active.driver = None;
                    active.last_time = Some(now);
                }
                adv.value
            }
            ToastPhase::Hold => {
                if let Some(last) = active.last_time {
                    active.hold_elapsed += now.saturating_sub(last);
                }
                active.last_time = Some(now);
                if active.hold_elapsed >= HOLD_DURATION {
                    active.phase = ToastPhase::Exit;
                    active.driver = None;
                }
                1.0
            }
            ToastPhase::Exit => {
                let adv = active
                    .driver
                    .get_or_insert_with(|| make_driver(exit).0)
                    .advance(now);
                if adv.done {
                    active.phase = ToastPhase::Done;
                }
                1.0 - adv.value.clamp(0.0, 1.0)
            }
            ToastPhase::Done => 0.0,
        };
        Some(shown)
    }
}

impl Widget for ToastHostWidget {
    fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
        // Lay out the active toast (if any) at its own natural size first —
        // needed both to size an unbounded host axis (below) and to position
        // it per anchor. `bc.loosen()` mirrors the old direct pass-through
        // (this host's incoming `bc` is already loose — `Stack` loosens its
        // children — but loosening explicitly keeps the toast's own sizing
        // independent of the host's now-larger, full-bleed `bc`).
        let toast_size = match &mut self.active {
            Some(active) if !matches!(active.phase, ToastPhase::Done) => {
                Some(active.child.layout_child(ctx, &bc.loosen()))
            }
            _ => None,
        };

        // Full-bleed: fill each bounded axis (the common case — Stack hands
        // down the surrounding page's finite size) so the host spans the
        // whole overlay region; shrink-wrap an unbounded axis to the active
        // toast's own size instead (Align's Flutter-parity per-axis rule —
        // `align.rs`'s module docs), or to zero while idle.
        let natural = toast_size.unwrap_or(Size::ZERO);
        let width = if bc.max().width.is_finite() {
            bc.max().width
        } else {
            natural.width
        };
        let height = if bc.max().height.is_finite() {
            bc.max().height
        } else {
            natural.height
        };
        let size = bc.constrain(Size::new(width, height));

        if let (Some(active), Some(toast_size)) = (&mut self.active, toast_size) {
            let insets = ctx.window_insets().padding();
            let origin = anchor_origin(self.anchor, size, toast_size, insets);
            active.child.set_origin(origin);
        }

        size
    }

    fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
        let theme = Theme::from_paint_ctx(ctx);
        let reduce_motion = theme.map(|t| t.motion.reduce_motion).unwrap_or(false);
        let (enter, exit) = resolve_timings(reduce_motion);
        let now = ctx.frame_time();
        let host_origin = ctx.origin();
        // Bottom anchors rise from below (a positive slide offset settling to
        // zero); top anchors keep the pre-existing drop-from-above motion
        // (negative offset) — see the [module docs](self)'s Anchoring section.
        let sign = if self.anchor.is_top() { -1.0 } else { 1.0 };

        if let Some(shown) = self.advance(now, enter, exit) {
            let phase = self.active.as_ref().map(|a| a.phase);
            let done = matches!(phase, Some(ToastPhase::Done));
            if !done && let Some(active) = &mut self.active {
                // The toast's own (anchored) rect, not the host's full-bleed
                // bounds — the layer/transform below only ever cover the
                // toast itself, keeping the rest of the (event-transparent)
                // host untouched.
                let toast_origin = host_origin + active.child.origin().to_vec2();
                let toast_size = active.child.size();
                let dy = (1.0 - shown) * sign * (ENTER_OFFSET_FRACTION * toast_size.height);
                let alpha = shown.clamp(0.0, 1.0) as f32;
                scene.push_transform(Affine::translate((0.0, dy)));
                scene.push_layer(toast_origin, toast_size, alpha);
                active.child.paint_child(ctx, scene);
                scene.pop_layer();
                scene.pop_transform();
            }
            // Kept active (even once `Done`) until the next `rebuild` tears it
            // down — one more frame ensures that rebuild actually runs (see
            // the [module docs](self)). Enter/Exit are genuine transitions
            // (a user-visible endpoint driven by `TransitionDriver`) and
            // request the unpaced class every vsync, like the one-frame
            // tear-down poke past `Done`; Hold's only need is elapsed-time
            // bookkeeping toward `HOLD_DURATION`, so it paces instead — the
            // mobile frame gate throttles it to `cosmetic_loop_rate`
            // (`docs/CODE_STANDARDS.md`'s perpetual-decorative-loop rule; a
            // fixed-length hold isn't perpetual, but the same
            // paint-doesn't-need-full-rate reasoning applies since nothing
            // visible changes frame-to-frame during it).
            if matches!(phase, Some(ToastPhase::Hold)) {
                ctx.request_frame_paced();
            } else {
                ctx.request_frame();
            }
        }
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        if let Some(active) = &self.active
            && !matches!(active.phase, ToastPhase::Done)
        {
            active.child.semantics_child(ctx);
        }
    }

    frust::authoring::visit_children!(active);
}

#[cfg(test)]
mod tests {
    use super::*;
    use frust::authoring::BuildCtx;

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

    fn build_host(pending: Vec<String>) -> ToastHostWidget {
        let view: ToastHostView = toast_host(pending);
        let mut counter = 0u64;
        <ToastHostView as View<()>>::build(&view, &mut BuildCtx::new(&mut counter))
    }

    // -- Toast leaf -----------------------------------------------------

    #[derive(Default)]
    struct RecordingScene {
        rrects: Vec<(Point, Size, f64, Color)>,
        shadows: Vec<(Point, Size, f64, f64, Color)>,
        transforms: Vec<Affine>,
        transform_pops: u32,
        layers: Vec<(Point, Size, f32)>,
        layer_pops: u32,
    }

    impl PaintScene for RecordingScene {
        fn fill_rect(&mut self, _o: Point, _s: Size, _c: Color) {}
        fn draw_text(&mut self, _o: Point, _t: &str) {}
        fn fill_rounded_rect(&mut self, o: Point, s: Size, radius: f64, color: Color) {
            self.rrects.push((o, s, radius, color));
        }
        fn draw_shadow(&mut self, o: Point, s: Size, radius: f64, std_dev: f64, color: Color) {
            self.shadows.push((o, s, radius, std_dev, color));
        }
        fn push_transform(&mut self, transform: Affine) {
            self.transforms.push(transform);
        }
        fn pop_transform(&mut self) {
            self.transform_pops += 1;
        }
        fn push_layer(&mut self, origin: Point, size: Size, alpha: f32) {
            self.layers.push((origin, size, alpha));
        }
        fn pop_layer(&mut self) {
            self.layer_pops += 1;
        }
    }

    fn build_toast(message: &str) -> ToastWidget {
        let view: ToastView = toast(message);
        let mut counter = 0u64;
        <ToastView as View<()>>::build(&view, &mut BuildCtx::new(&mut counter))
    }

    #[test]
    fn toast_paints_shadow_surface_dot_and_message() {
        use frust::authoring::LayoutCtx;
        use frust::authoring::text::TextContext;
        use std::any::Any;

        let mut w = build_toast("Saved");
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        let size = w.layout(&mut lctx, &BoxConstraints::loose(Size::new(400.0, 200.0)));
        let mut ctx = PaintCtx::new(Point::ZERO, size);
        let mut scene = RecordingScene::default();
        w.paint(&mut ctx, &mut scene);
        assert_eq!(scene.shadows.len(), 1);
        assert_eq!(scene.rrects.len(), 2, "surface rect + dot rect");
        assert_eq!(scene.rrects[0].3, FALLBACK_SURFACE);
    }

    #[test]
    fn variant_selects_the_dot_color_unthemed() {
        for (variant, expected) in [
            (ToastVariant::Plain, FALLBACK_PLAIN),
            (ToastVariant::Info, FALLBACK_INFO),
            (ToastVariant::Success, FALLBACK_SUCCESS),
            (ToastVariant::Warning, FALLBACK_WARNING),
            (ToastVariant::Error, FALLBACK_ERROR),
        ] {
            assert_eq!(ToastWidget::resolve_dot_color(None, variant), expected);
        }
    }

    #[test]
    fn glyph_tokens_resolve_dark_and_light() {
        let dark = crate::baseline();
        let light = dark.clone().with_brightness(frust::Brightness::Light);
        assert_eq!(
            ToastWidget::resolve_surface_color(Some(&dark)),
            dark.scheme().surface_container_highest
        );
        assert_eq!(
            ToastWidget::resolve_surface_color(Some(&light)),
            light.scheme().surface_container_highest
        );
        assert_ne!(
            dark.scheme().surface_container_highest,
            light.scheme().surface_container_highest
        );
        // Status-based variants resolve StatusPalette per brightness.
        let dark_success = ToastWidget::resolve_dot_color(Some(&dark), ToastVariant::Success);
        let light_success = ToastWidget::resolve_dot_color(Some(&light), ToastVariant::Success);
        assert_eq!(
            dark_success,
            dark.extension::<StatusPalette>().unwrap().dark.success
        );
        assert_eq!(
            light_success,
            light.extension::<StatusPalette>().unwrap().light.success
        );
    }

    // -- ToastHost: queue policy (v1: single visible, FIFO) --------------

    #[test]
    fn only_one_toast_is_active_at_a_time_and_starts_the_first_request() {
        let host = build_host(vec!["first".to_string(), "second".to_string()]);
        let active = host
            .active
            .as_ref()
            .expect("first request starts immediately");
        assert_eq!(active.message, "first");
        assert_eq!(active.phase, ToastPhase::Enter);
        assert_eq!(host.next_index, 0, "not yet advanced past the active item");
    }

    #[test]
    fn finishing_a_toast_starts_the_next_queued_one_on_rebuild() {
        let mut host = build_host(vec!["first".to_string(), "second".to_string()]);
        let (enter, exit) = resolve_timings(false);

        // Drive fully through enter -> hold -> exit -> Done.
        let mut t = 0.0;
        loop {
            host.advance(ft_ms(t), enter, exit);
            if matches!(
                host.active.as_ref().map(|a| a.phase),
                Some(ToastPhase::Done)
            ) {
                break;
            }
            t += 50.0;
            assert!(t < 10_000.0, "timeline never reached Done");
        }

        let view: ToastHostView = toast_host(vec!["first".to_string(), "second".to_string()]);
        let mut counter = 0u64;
        <ToastHostView as View<()>>::rebuild(
            &view,
            &view,
            &mut host,
            &mut BuildCtx::new(&mut counter),
        );

        assert_eq!(host.next_index, 1, "advanced past the finished first toast");
        let active = host.active.as_ref().expect("the second request starts");
        assert_eq!(active.message, "second");
        assert_eq!(active.phase, ToastPhase::Enter);
    }

    // -- ToastHost: rebuild flags (a structural
    // queue change (start or teardown of the active pod) MUST report LAYOUT,
    // or a layout-skip shell (Android) leaves a fresh/torn-down child pod
    // unlaid-out — see the module's diagnosis doc comment) -----------------

    #[test]
    fn rebuild_reports_layout_when_a_pushed_toast_starts() {
        let mut host = build_host(vec![]);
        assert!(host.active.is_none(), "nothing queued yet");

        let prev_view: ToastHostView = toast_host(vec![]);
        let next_view: ToastHostView = toast_host(vec!["hello".to_string()]);
        let mut counter = 0u64;
        let flags = <ToastHostView as View<()>>::rebuild(
            &next_view,
            &prev_view,
            &mut host,
            &mut BuildCtx::new(&mut counter),
        );

        assert!(host.active.is_some(), "the pushed toast starts immediately");
        assert!(
            flags.needs_layout(),
            "a newly-started toast's child pod has never been laid out — \
             the rebuild that builds it MUST report LAYOUT, or a \
             layout-skip shell (Android) leaves it at Size::ZERO for its \
             whole lifecycle"
        );
    }

    #[test]
    fn honoring_rebuild_flags_after_a_push_always_lays_out_the_new_child() {
        // Mirrors the Android-shaped sequence: a shell that trusts the
        // returned ChangeFlags and only calls `layout` when they say to. If
        // `rebuild` under-reports (PAINT-only), a shell honoring that
        // literally paints a never-laid-out (Size::ZERO) child — this test
        // drives exactly that shell contract and confirms the toast layer
        // paints nonzero.
        let mut host = build_host(vec![]);
        let prev_view: ToastHostView = toast_host(vec![]);
        let next_view: ToastHostView = toast_host(vec!["hello".to_string()]);
        let mut counter = 0u64;
        let flags = <ToastHostView as View<()>>::rebuild(
            &next_view,
            &prev_view,
            &mut host,
            &mut BuildCtx::new(&mut counter),
        );

        // The shell contract under test: only relayout when flags say so.
        if flags.needs_layout() {
            layout_host(&mut host, &BoxConstraints::tight(Size::new(400.0, 800.0)));
        }

        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(400.0, 800.0));
        let mut scene = RecordingScene::default();
        host.paint(&mut ctx, &mut scene);

        assert_eq!(scene.layers.len(), 1, "the active toast paints a layer");
        let (_, layer_size, _) = scene.layers[0];
        assert!(
            layer_size.width > 0.0 && layer_size.height > 0.0,
            "the toast layer must be nonzero — a zero size means the shell \
             skipped layout on a flags contract it correctly honored, i.e. \
             the bug this task fixes: {layer_size:?}"
        );
    }

    #[test]
    fn rebuild_reports_layout_when_a_finished_toast_tears_down() {
        let mut host = build_host(vec!["first".to_string(), "second".to_string()]);
        let (enter, exit) = resolve_timings(false);

        // Drive fully through enter -> hold -> exit -> Done.
        let mut t = 0.0;
        loop {
            host.advance(ft_ms(t), enter, exit);
            if matches!(
                host.active.as_ref().map(|a| a.phase),
                Some(ToastPhase::Done)
            ) {
                break;
            }
            t += 50.0;
            assert!(t < 10_000.0, "timeline never reached Done");
        }

        let view: ToastHostView = toast_host(vec!["first".to_string(), "second".to_string()]);
        let mut counter = 0u64;
        let flags = <ToastHostView as View<()>>::rebuild(
            &view,
            &view,
            &mut host,
            &mut BuildCtx::new(&mut counter),
        );

        assert!(
            flags.needs_layout(),
            "tearing down the finished toast and starting the next is also \
             a structural change and must report LAYOUT"
        );
    }

    #[test]
    fn idle_host_with_no_pending_requests_requests_no_frame() {
        let mut host = build_host(vec![]);
        assert!(host.active.is_none());
        let mut ctx = PaintCtx::new(Point::ZERO, Size::ZERO);
        let mut scene = RecordingScene::default();
        host.paint(&mut ctx, &mut scene);
        assert!(!ctx.needs_frame());
    }

    // -- ToastHost: timeline (enter -> hold 2.4s -> exit), fake frame times --

    #[test]
    fn timeline_progresses_enter_then_hold_then_exit_then_done() {
        let mut host = build_host(vec!["hello".to_string()]);
        let (enter, exit) = resolve_timings(false);

        // Seed the clock; still Enter, shown starts at 0.
        let shown0 = host.advance(ft_ms(0.0), enter, exit).unwrap();
        assert!(shown0.abs() < 1e-6);
        assert_eq!(host.active.as_ref().unwrap().phase, ToastPhase::Enter);

        // Past the 220ms enter duration: settles into Hold at shown == 1.0.
        let shown_settled = host.advance(ft_ms(300.0), enter, exit).unwrap();
        assert!((shown_settled - 1.0).abs() < 1e-6);
        assert_eq!(host.active.as_ref().unwrap().phase, ToastPhase::Hold);

        // Advance through most of the 2.4s hold: still Hold.
        host.advance(ft_ms(300.0 + 2000.0), enter, exit);
        assert_eq!(host.active.as_ref().unwrap().phase, ToastPhase::Hold);

        // Past the full 2.4s hold: flips to Exit (this call only flips the
        // phase; the exit driver itself is created and seeded on the *next*
        // call, mirroring the enter driver's own seed-then-settle shape
        // above).
        host.advance(ft_ms(300.0 + 2500.0), enter, exit);
        assert_eq!(host.active.as_ref().unwrap().phase, ToastPhase::Exit);

        // Seed the exit driver's clock.
        let shown_exit_seed = host
            .advance(ft_ms(300.0 + 2500.0 + 10.0), enter, exit)
            .unwrap();
        assert!(
            (shown_exit_seed - 1.0).abs() < 1e-6,
            "exit starts fully shown"
        );
        assert_eq!(host.active.as_ref().unwrap().phase, ToastPhase::Exit);

        // Past the 150ms exit duration: settles into Done, shown == 0.
        let shown_done = host
            .advance(ft_ms(300.0 + 2500.0 + 10.0 + 300.0), enter, exit)
            .unwrap();
        assert!(shown_done.abs() < 1e-6);
        assert_eq!(host.active.as_ref().unwrap().phase, ToastPhase::Done);
    }

    #[test]
    fn reduce_motion_uses_the_fast_linear_crossfade_timing() {
        let (enter, exit) = resolve_timings(true);
        assert_eq!(
            enter,
            Timing::Duration(REDUCE_MOTION_DURATION, Curve::Linear)
        );
        assert_eq!(
            exit,
            Timing::Duration(REDUCE_MOTION_DURATION, Curve::Linear)
        );
    }

    #[test]
    fn paint_at_enter_start_emits_translated_faded_layer() {
        let mut host = build_host(vec!["hi".to_string()]);
        {
            use frust::authoring::LayoutCtx;
            use frust::authoring::text::TextContext;
            use std::any::Any;
            let mut tcx = TextContext::new();
            let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
            host.layout(&mut lctx, &BoxConstraints::loose(Size::new(300.0, 100.0)));
        }
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(200.0, 50.0));
        let mut scene = RecordingScene::default();
        host.paint(&mut ctx, &mut scene);
        assert_eq!(scene.transforms.len(), 1);
        assert_eq!(scene.transform_pops, 1);
        assert_eq!(scene.layers.len(), 1);
        assert_eq!(scene.layer_pops, 1);
        // At the very start of Enter (FrameTime::ZERO seeds the clock), shown
        // is 0: fully faded and offset fully above the resting position.
        assert_eq!(scene.layers[0].2, 0.0);
        assert!(ctx.needs_frame());
    }

    #[test]
    fn hold_phase_paces_frame_requests_but_enter_and_exit_do_not() {
        let mut host = build_host(vec!["hi".to_string()]);
        {
            use frust::authoring::LayoutCtx;
            use frust::authoring::text::TextContext;
            use std::any::Any;
            let mut tcx = TextContext::new();
            let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
            host.layout(&mut lctx, &BoxConstraints::loose(Size::new(300.0, 100.0)));
        }

        // Enter (the freshly-built default phase): a genuine transition,
        // unpaced.
        assert_eq!(host.active.as_ref().unwrap().phase, ToastPhase::Enter);
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(300.0, 100.0));
        let mut scene = RecordingScene::default();
        host.paint(&mut ctx, &mut scene);
        assert_eq!(host.active.as_ref().unwrap().phase, ToastPhase::Enter);
        assert!(
            !ctx.needs_frame_paced_only(),
            "Enter is a genuine transition and must run unpaced"
        );

        // Force into Hold — mirrors the file's other tests' direct phase
        // manipulation via `advance`/field access (same-file `tests`
        // submodule has private-field access); elapsed-time bookkeeping only,
        // so it must pace.
        host.active.as_mut().unwrap().phase = ToastPhase::Hold;
        host.active.as_mut().unwrap().last_time = None;
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(300.0, 100.0));
        let mut scene = RecordingScene::default();
        host.paint(&mut ctx, &mut scene);
        assert_eq!(host.active.as_ref().unwrap().phase, ToastPhase::Hold);
        assert!(
            ctx.needs_frame_paced_only(),
            "Hold's only need is elapsed-time bookkeeping toward \
             HOLD_DURATION — it must pace to the mobile frame gate's \
             cosmetic-loop rate"
        );

        // Force into Exit: a genuine transition again, unpaced.
        host.active.as_mut().unwrap().phase = ToastPhase::Exit;
        host.active.as_mut().unwrap().driver = None;
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(300.0, 100.0));
        let mut scene = RecordingScene::default();
        host.paint(&mut ctx, &mut scene);
        assert_eq!(host.active.as_ref().unwrap().phase, ToastPhase::Exit);
        assert!(
            !ctx.needs_frame_paced_only(),
            "Exit is a genuine transition and must run unpaced"
        );
    }

    // -- ToastHost: anchoring (framework-side positioning) -------------------

    /// Lay `host` out under `bc` with a fresh (empty) `TextContext` — every
    /// active toast contains a `Text` child needing one threaded (mirrors
    /// `paint_at_enter_start_emits_translated_faded_layer`'s inline setup).
    fn layout_host(host: &mut ToastHostWidget, bc: &BoxConstraints) -> Size {
        use frust::authoring::LayoutCtx;
        use frust::authoring::text::TextContext;
        use std::any::Any;
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        host.layout(&mut lctx, bc)
    }

    #[test]
    fn default_anchor_is_bottom_center() {
        assert_eq!(ToastAnchor::default(), ToastAnchor::BottomCenter);
    }

    #[test]
    fn default_anchor_positions_bottom_center_with_margin_no_insets() {
        let mut host = build_host(vec!["hi".to_string()]);
        let size = layout_host(&mut host, &BoxConstraints::tight(Size::new(400.0, 800.0)));
        assert_eq!(size, Size::new(400.0, 800.0), "host fills the full bc");

        let active = host.active.as_ref().expect("toast starts immediately");
        let toast_size = active.child.size();
        let origin = active.child.origin();

        let center_x = origin.x + toast_size.width / 2.0;
        assert!(
            (center_x - 200.0).abs() < 1e-6,
            "toast rect centers horizontally: {center_x}"
        );
        let bottom_edge = origin.y + toast_size.height;
        assert!(
            (bottom_edge - (800.0 - EDGE_MARGIN)).abs() < 1e-6,
            "toast rect's bottom edge sits EDGE_MARGIN above the host bottom: {bottom_edge}"
        );
    }

    #[test]
    fn default_anchor_bottom_margin_additionally_respects_the_bottom_inset() {
        use frust::authoring::text::TextContext;
        use frust::authoring::{WindowEdgeInsets, WindowInsets};
        use frust_core::RenderRoot;

        fn logic(_: &mut ()) -> ToastHostView {
            toast_host(vec!["hi".to_string()])
        }
        let mut root: RenderRoot<(), ToastHostView> = RenderRoot::new();
        let mut state = ();
        root.rebuild(&mut logic, &mut state);
        root.set_insets(WindowInsets::new(
            WindowEdgeInsets::new(0.0, 0.0, 0.0, 34.0),
            WindowEdgeInsets::ZERO,
        ));
        let mut tcx = TextContext::new();
        let size = root.layout_with_text(Size::new(400.0, 800.0), &mut tcx);
        assert_eq!(size, Size::new(400.0, 800.0));

        let id = root.root_id().expect("root built");
        let widget = (root.tree().pod(id).expect("root pod").widget() as &dyn std::any::Any)
            .downcast_ref::<ToastHostWidget>()
            .expect("root is a ToastHostWidget");
        let active = widget.active.as_ref().expect("toast starts immediately");
        let toast_size = active.child.size();
        let origin = active.child.origin();
        let bottom_edge = origin.y + toast_size.height;
        assert!(
            (bottom_edge - (800.0 - EDGE_MARGIN - 34.0)).abs() < 1e-6,
            "the 34px bottom inset widens the margin additively: {bottom_edge}"
        );
    }

    #[test]
    fn all_six_anchors_position_correctly() {
        for anchor in [
            ToastAnchor::TopLeft,
            ToastAnchor::TopCenter,
            ToastAnchor::TopRight,
            ToastAnchor::BottomLeft,
            ToastAnchor::BottomCenter,
            ToastAnchor::BottomRight,
        ] {
            let view: ToastHostView = toast_host(vec!["hi".to_string()]).anchor(anchor);
            let mut counter = 0u64;
            let mut host =
                <ToastHostView as View<()>>::build(&view, &mut BuildCtx::new(&mut counter));
            let size = layout_host(&mut host, &BoxConstraints::tight(Size::new(400.0, 800.0)));
            assert_eq!(size, Size::new(400.0, 800.0));

            let active = host.active.as_ref().expect("toast starts immediately");
            let toast_size = active.child.size();
            let origin = active.child.origin();

            let expected_x = match anchor {
                ToastAnchor::TopLeft | ToastAnchor::BottomLeft => EDGE_MARGIN,
                ToastAnchor::TopCenter | ToastAnchor::BottomCenter => {
                    (400.0 - toast_size.width) / 2.0
                }
                ToastAnchor::TopRight | ToastAnchor::BottomRight => {
                    400.0 - EDGE_MARGIN - toast_size.width
                }
            };
            let expected_y = if anchor.is_top() {
                EDGE_MARGIN
            } else {
                800.0 - EDGE_MARGIN - toast_size.height
            };
            assert!(
                (origin.x - expected_x).abs() < 1e-6,
                "{anchor:?}: x = {}, expected {expected_x}",
                origin.x
            );
            assert!(
                (origin.y - expected_y).abs() < 1e-6,
                "{anchor:?}: y = {}, expected {expected_y}",
                origin.y
            );
        }
    }

    #[test]
    fn host_never_swallows_events_inside_or_outside_the_toast_rect() {
        use frust::authoring::{
            EventCtx, EventResult, InputEvent, PointerButton, PointerEvent, PointerPhase,
        };
        use std::any::Any;

        // `ToastHostWidget` never overrides `Widget::event`, so it always
        // falls through to the default no-op — verified explicitly here so a
        // future accidental override (e.g. adding tap-to-dismiss) trips this
        // test rather than silently starting to swallow taps.
        let mut host = build_host(vec!["hi".to_string()]);
        let mut state = ();
        let state_any: &mut dyn Any = &mut state;
        let mut ectx = EventCtx::new(state_any, Point::ZERO, Size::new(400.0, 800.0));

        let ev = InputEvent::Pointer(PointerEvent {
            phase: PointerPhase::Down,
            position: Point::new(5.0, 5.0),
            button: PointerButton::Primary,
        });
        assert_eq!(host.event(&mut ectx, &ev), EventResult::Ignored);
    }

    // -- ToastHost: VisitPods regression (RenderRoot::inspect) ---------------

    #[test]
    fn inspect_surfaces_the_active_toast_only_while_one_is_playing() {
        // Regression coverage for the hand-written `ActiveToast` `VisitPods`
        // impl (ported from crates/frust-widgets/tests/visit_children.rs,
        // which covered this shape before the design-system extraction). If
        // `ActiveToast::visit_pods` ever stopped forwarding to its `child`
        // field, a playing host's node list below would collapse to just
        // `["ToastHostWidget"]` — indistinguishable from the idle host, and
        // silently invisible to `WidgetTree::inspect`/devtools even though
        // the toast is actually on screen.
        use frust::authoring::text::TextContext;
        use frust_core::{InspectNode, RenderRoot};
        use std::any::Any;

        fn short_names(nodes: &[InspectNode]) -> Vec<&str> {
            nodes
                .iter()
                .map(|n| {
                    let bare = n.type_name.split('<').next().unwrap_or(n.type_name);
                    bare.rsplit("::").next().unwrap_or(bare)
                })
                .collect()
        }

        fn idle_logic(_: &mut ()) -> ToastHostView {
            toast_host(Vec::<String>::new())
        }
        let mut idle_root: RenderRoot<(), ToastHostView> = RenderRoot::new();
        let mut state = ();
        idle_root.rebuild(&mut idle_logic, &mut state);
        let mut idle_tcx = TextContext::new();
        idle_root.layout_with_text(Size::new(400.0, 400.0), &mut idle_tcx as &mut dyn Any);
        assert_eq!(short_names(&idle_root.inspect()), vec!["ToastHostWidget"]);

        fn playing_logic(_: &mut ()) -> ToastHostView {
            toast_host(vec!["hello".to_string()])
        }
        let mut playing_root: RenderRoot<(), ToastHostView> = RenderRoot::new();
        playing_root.rebuild(&mut playing_logic, &mut state);
        let mut playing_tcx = TextContext::new();
        playing_root.layout_with_text(Size::new(400.0, 400.0), &mut playing_tcx as &mut dyn Any);
        assert_eq!(
            short_names(&playing_root.inspect()),
            vec!["ToastHostWidget", "ToastWidget", "TextWidget"],
            "the active toast (and its own child) hang under the host"
        );
    }

    #[test]
    fn enter_offset_sign_flips_between_top_and_bottom_anchors() {
        fn early_enter_dy(anchor: ToastAnchor) -> f64 {
            let view: ToastHostView = toast_host(vec!["hi".to_string()]).anchor(anchor);
            let mut counter = 0u64;
            let mut host =
                <ToastHostView as View<()>>::build(&view, &mut BuildCtx::new(&mut counter));
            layout_host(&mut host, &BoxConstraints::tight(Size::new(400.0, 800.0)));

            let mut ctx = PaintCtx::new(Point::ZERO, Size::new(400.0, 800.0));
            let mut scene = RecordingScene::default();
            host.paint(&mut ctx, &mut scene);
            scene.transforms[0].translation().y
        }

        // At the very start of Enter (shown == 0), the slide offset is at its
        // full magnitude — sign alone tells top from bottom.
        let bottom_dy = early_enter_dy(ToastAnchor::BottomCenter);
        let top_dy = early_enter_dy(ToastAnchor::TopCenter);
        assert!(
            bottom_dy > 0.0,
            "a bottom anchor rises from below (positive dy): {bottom_dy}"
        );
        assert!(
            top_dy < 0.0,
            "a top anchor drops from above (negative dy): {top_dy}"
        );
    }

    // ---- Typeface: the message's family follows its type-scale role -------

    #[cfg(feature = "bundled-fonts")]
    fn saved(_: &mut ()) -> ToastView {
        toast("Saved")
    }

    #[cfg(feature = "bundled-fonts")]
    #[test]
    fn the_message_paints_in_its_role_face_under_the_glyph_theme() {
        // Before the message opted into a type-scale role it painted `Text`'s
        // system family here — `Face::Other` — beside the catalog's own
        // IBM Plex Mono.
        use crate::badge::typeface_probe::{Face, painted_faces};
        let faces = painted_faces(saved, crate::baseline(), Size::new(400.0, 200.0));
        assert_eq!(faces, [Face::PlexMono]);
    }

    #[cfg(feature = "bundled-fonts")]
    #[test]
    fn the_message_follows_a_live_theme_family_swap() {
        use crate::badge::typeface_probe::{Face, faces_across_a_live_swap};
        let (before, after) = faces_across_a_live_swap(saved, Size::new(400.0, 200.0));
        assert_eq!(before, [Face::PlexMono]);
        assert_eq!(after, [Face::SpaceMono]);
    }
}