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
//! [`badge`]/[`BadgeView`]: a small, lowercase, pill-shaped status indicator —
//! "connected"/"degraded"/"offline"/"read-only"/"v0.44.1" in the Glyph
//! design system's `.badge*` rules (retrieved 2026-07-21) — with six
//! semantic variants and an optional leading dot.
//!
//! # Color resolution (documented three-tier precedence)
//!
//! Not every variant has all three tiers, since `ColorScheme` (the M3
//! baseline) carries no `success`/`warning` roles at all (see
//! `frust_theme::extensions`' module docs):
//!
//! - **Success/Warning** resolve `theme.extension::<StatusPalette>()` first
//!   (`Theme::neutral` and every design system's baseline — this crate's
//!   [`crate::baseline`] included — attach one), falling back to this
//!   module's literal Glyph-dark constants only in the defensive case where
//!   an app cleared the extension.
//! - **Error** resolves directly from `ColorScheme::error`/`error_container` —
//!   M3's baseline *does* carry an error role, so no extension is needed.
//! - **Neutral** resolves `surface_container_high`/`on_surface_variant` (the
//!   Glyph token module's own `bg-raised`/`fg-muted` mapping, see
//!   [`crate::tokens::color`]) plus an `outline` border.
//! - **Accent** has no `ColorScheme` container role for a *faint* wash —
//!   `primary_container` is the opaque bright-fill role (used for filled
//!   buttons), not a translucent one — so this variant paints a true alpha
//!   wash over `primary` instead (`ACCENT_WASH_ALPHA` matches the source's
//!   `--amber-faint` alpha, `0.12`, exactly), unlike the pre-flattened
//!   Success/Warning/Error containers which assume a `surface`-level
//!   backdrop (see [`crate::tokens::color`]'s "Alpha pre-flattening").
//!
//! With no theme threaded at all, every variant falls back to a literal Glyph
//! **dark** constant (this module's `BADGE_*` consts) — never a panic.
//!
//! # Text color and why this widget doesn't nest a `Text` child
//!
//! [`frust::TextView`] resolves its themed color from a fixed
//! four-variant `ThemeTextColor` role (`OnSurface`/`OnPrimary`/
//! `OnSurfaceVariant`/`OnPrimaryContainer`) chosen at `View::build`/`rebuild`
//! time — but `BuildCtx` (unlike `LayoutCtx`/`PaintCtx`) carries no theme, so a
//! nested `Text` view could never resolve an arbitrary per-variant color
//! (success green, warning amber, …) that isn't one of those four roles.
//! Rather than widen `TextView`'s internal role enum (a change scoped
//! beyond this module), `BadgeWidget` shapes
//! and paints its own label glyph run directly via `frust_text`, mirroring
//! `crate::text::TextWidget`'s own shape (lazy shape-on-layout, glyph-run
//! paint) but resolving color from the variant/theme itself.
//!
//! Per the crate's layout-time-baked-color contract
//! (`docs/CODE_STANDARDS.md`'s Theming conventions), the resolved color feeds
//! into the cached [`TextStyle`] compared at each layout pass, so a theme
//! swap (which forces `ChangeFlags::LAYOUT` — see
//! `docs/ARCHITECTURE.md`'s Theme delivery) always re-shapes with the new
//! color.
//!
//! # Typeface
//!
//! The label's family is read at layout from the live theme's `labelSmall`
//! type-scale role — IBM Plex Mono under Glyph's own scale, the face it has
//! always painted — falling back to Glyph's IBM Plex Mono stack unthemed.
//! Size, weight and tracking stay this module's own constants. The family is
//! part of the cached [`TextStyle`] too, so a theme swap (or a type scale an
//! app rewrites) reshapes the label in the new face, exactly like the color.
//! Every other self-shaping Glyph widget follows the same rule.

use frust::authoring::Role;
use frust::authoring::text::{
    FontFamily, FontWeight, GenericSlot, TextContext, TextLayout, TextStyle,
};
use frust::authoring::{
    BoxConstraints, BuildCtx, ChangeFlags, LayoutCtx, PaintCtx, PaintScene, SemanticsCtx, View,
    Widget,
};
use frust::{ShapeScale, StatusPalette, Theme};
use kurbo::{Point, Rect, RoundedRect, Shape, Size, Vec2};
use peniko::{Brush, Color};

/// Corner-rounding tolerance for the neutral-variant hairline border (matches
/// the crate's other `RoundedRect::to_path` call sites, e.g.
/// `crate::cupertino::tabbar`'s `PATH_TOLERANCE`).
const PATH_TOLERANCE: f64 = 0.1;

/// Horizontal padding, in logical px (`.badge{padding:4px 9px}`).
const BADGE_PAD_X: f64 = 9.0;
/// Vertical padding, in logical px.
const BADGE_PAD_Y: f64 = 4.0;
/// Gap between the leading dot and the label, in logical px
/// (`.badge{gap:6px}`).
const BADGE_GAP: f64 = 6.0;
/// Leading-dot diameter, in logical px (`.badge-dot{width:5px;height:5px}`).
const BADGE_DOT_SIZE: f64 = 5.0;
/// Label font size, in logical px (`.badge{font-size:10.5px}`).
const BADGE_FONT_SIZE: f32 = 10.5;
/// Label letter-spacing, in logical px (`.badge{letter-spacing:0.03em}` ==
/// `0.03 * 10.5`).
const BADGE_LETTER_SPACING: f32 = BADGE_FONT_SIZE * 0.03;
/// Border width, in logical px (`.badge{border:1px solid transparent}` —
/// neutral and warning variants supply non-transparent `border-color`).
const BADGE_BORDER_WIDTH: f64 = 1.0;
/// Border alpha for warning and info variants (following alert.rs's
/// `ALERT_BORDER_ALPHA` precedent).
const BADGE_BORDER_ALPHA: f32 = 0.3;
/// The Accent variant's wash alpha (`--amber-faint` == `rgba(255,182,39,0.12)`,
/// both Glyph brightnesses — see the module docs).
const BADGE_ACCENT_WASH_ALPHA: f32 = 0.12;

// ---- Unthemed fallback constants (Glyph **dark** values; see module docs) --

const BADGE_SUCCESS_FG: Color = Color::from_rgb8(0x5f, 0xd8, 0x8f);
const BADGE_SUCCESS_BG: Color = Color::from_rgb8(0x1f, 0x31, 0x30);
const BADGE_WARNING_FG: Color = Color::from_rgb8(0xf5, 0xc8, 0x60);
const BADGE_WARNING_BG: Color = Color::from_rgb8(0x31, 0x2f, 0x2a);
const BADGE_WARNING_BORDER: Color = Color::from_rgb8(0xf5, 0xc8, 0x60);
const BADGE_ERROR_FG: Color = Color::from_rgb8(0xff, 0x6b, 0x6b);
const BADGE_ERROR_BG: Color = Color::from_rgb8(0x32, 0x24, 0x2c);
const BADGE_INFO_FG: Color = Color::from_rgb8(0x5e, 0xc8, 0xd8);
const BADGE_INFO_BG: Color = Color::from_rgb8(0x20, 0x32, 0x3c);
const BADGE_NEUTRAL_FG: Color = Color::from_rgb8(0xa3, 0x9c, 0x88);
const BADGE_NEUTRAL_BG: Color = Color::from_rgb8(0x1e, 0x23, 0x30);
const BADGE_NEUTRAL_BORDER: Color = Color::from_rgb8(0x3e, 0x3f, 0x44);
const BADGE_ACCENT_FG: Color = Color::from_rgb8(0xff, 0xb6, 0x27);

/// Return `color` with its alpha channel replaced by `alpha` (mirrors
/// `crate::cupertino::button`'s helper of the same shape).
fn with_alpha(color: Color, alpha: f32) -> Color {
    let c = color.components;
    Color::new([c[0], c[1], c[2], alpha])
}

/// Which semantic variant a [`BadgeView`] renders as — see the module docs
/// for the color-resolution precedence per variant.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BadgeVariant {
    /// A faint success-hued wash (e.g. "connected"/"live").
    Success,
    /// A faint warning-hued wash (e.g. "degraded").
    Warning,
    /// A faint error-hued wash (e.g. "offline"/"stopped").
    Error,
    /// A faint info-hued wash (cyan, e.g. "active"/"processing").
    Info,
    /// A neutral raised-surface wash with a hairline border (e.g.
    /// "read-only"/"idle").
    Neutral,
    /// The Glyph accent (amber) as a faint wash (e.g. a version tag).
    Accent,
}

/// A declarative status badge. See the [module docs](self).
pub struct BadgeView {
    label: String,
    variant: BadgeVariant,
    dot: bool,
}

/// Create a badge labelled `label` (rendered lowercase, per the source's
/// `text-transform:lowercase`) in the given semantic `variant`.
pub fn badge(label: impl Into<String>, variant: BadgeVariant) -> BadgeView {
    BadgeView {
        label: label.into(),
        variant,
        dot: false,
    }
}

impl BadgeView {
    /// Show (or hide) the leading status dot, colored to match the label.
    pub fn dot(mut self, dot: bool) -> Self {
        self.dot = dot;
        self
    }
}

/// A minimal retained text run: shapes lazily during layout and paints via
/// glyph runs. A self-contained mirror of `crate::text::TextWidget`'s cache
/// shape (see the module docs for why `Badge`/`Tag`/`Alert` don't nest a
/// `Text` child).
struct GlyphLabel {
    content: String,
    layout: Option<TextLayout>,
    laid_out_style: Option<TextStyle>,
    laid_out_max_width: Option<f32>,
}

impl GlyphLabel {
    fn new(content: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            layout: None,
            laid_out_style: None,
            laid_out_max_width: None,
        }
    }

    /// Replace the content, invalidating the cached shaped layout if it
    /// actually changed.
    fn set_content(&mut self, content: impl Into<String>) {
        let content = content.into();
        if self.content != content {
            self.content = content;
            self.layout = None;
        }
    }

    /// Shape (or reuse the cached shape of) this run at `style`/`max_width`,
    /// returning its size. Re-shapes whenever either input differs from the
    /// last pass — including a color-only `style` change (the layout-time-baked
    /// color contract, see the module docs).
    fn layout(&mut self, ctx: &mut LayoutCtx, style: &TextStyle, max_width: Option<f32>) -> Size {
        if let Some(cached) = &self.layout
            && self.laid_out_max_width == max_width
            && self.laid_out_style.as_ref() == Some(style)
        {
            return cached.size();
        }
        let text_ctx = ctx.text_context::<TextContext>();
        let laid = text_ctx.layout(&self.content, style, max_width);
        let size = laid.size();
        self.layout = Some(laid);
        self.laid_out_style = Some(style.clone());
        self.laid_out_max_width = max_width;
        size
    }

    /// Emit this run's glyphs at absolute `origin`. A no-op before the first
    /// [`GlyphLabel::layout`] call.
    fn paint(&self, origin: Point, scene: &mut dyn PaintScene) {
        if let Some(layout) = &self.layout {
            for run in layout.to_scene_runs(origin) {
                scene.draw_glyph_run(run);
            }
        }
    }
}

/// The retained widget for a [`BadgeView`].
pub struct BadgeWidget {
    label: GlyphLabel,
    label_text: String,
    label_size: Size,
    variant: BadgeVariant,
    dot: bool,
}

impl<State: 'static> View<State> for BadgeView {
    type Element = BadgeWidget;

    fn build(&self, _ctx: &mut BuildCtx<'_>) -> BadgeWidget {
        BadgeWidget {
            label: GlyphLabel::new(self.label.to_lowercase()),
            label_text: self.label.clone(),
            label_size: Size::ZERO,
            variant: self.variant,
            dot: self.dot,
        }
    }

    fn rebuild(
        &self,
        prev: &Self,
        element: &mut BadgeWidget,
        _ctx: &mut BuildCtx<'_>,
    ) -> ChangeFlags {
        let mut flags = ChangeFlags::NONE;
        if prev.label != self.label {
            element.label.set_content(self.label.to_lowercase());
            element.label_text = self.label.clone();
            flags |= ChangeFlags::LAYOUT | ChangeFlags::PAINT;
        }
        if prev.variant != self.variant {
            element.variant = self.variant;
            flags |= ChangeFlags::LAYOUT | ChangeFlags::PAINT;
        }
        if prev.dot != self.dot {
            element.dot = self.dot;
            flags |= ChangeFlags::LAYOUT | ChangeFlags::PAINT;
        }
        flags
    }
}

/// Glyph's UI face stack (IBM Plex Mono, then the generic monospace): the
/// label's unthemed family.
fn ui_face() -> FontFamily {
    FontFamily::stack_with_generic(["IBM Plex Mono"], GenericSlot::Monospace)
}

/// The label's style: weight, size and tracking are Glyph-authored
/// constants; the family is the theme's `labelSmall` role, or [`ui_face`]
/// unthemed (see the module docs' Typeface section); `color` varies per
/// variant.
fn badge_label_style(theme: Option<&Theme>, color: Color) -> TextStyle {
    TextStyle {
        family: theme.map_or_else(ui_face, |t| t.type_scale.label_small.family.clone()),
        weight: FontWeight::MEDIUM,
        letter_spacing: BADGE_LETTER_SPACING,
        ..TextStyle::new(BADGE_FONT_SIZE, color)
    }
}

/// Resolve `(background, foreground, border)` for `variant` — see the module
/// docs for the full precedence.
fn resolve_badge_colors(
    theme: Option<&Theme>,
    variant: BadgeVariant,
) -> (Color, Color, Option<Color>) {
    let Some(theme) = theme else {
        return unthemed_badge_colors(variant);
    };
    let scheme = theme.scheme();
    match variant {
        BadgeVariant::Success => match theme.extension::<StatusPalette>() {
            Some(status) => {
                let c = status.colors(theme.brightness);
                (c.success_container, c.success, None)
            }
            None => (BADGE_SUCCESS_BG, BADGE_SUCCESS_FG, None),
        },
        BadgeVariant::Warning => match theme.extension::<StatusPalette>() {
            Some(status) => {
                let c = status.colors(theme.brightness);
                (
                    c.warning_container,
                    c.warning,
                    Some(with_alpha(c.warning, BADGE_BORDER_ALPHA)),
                )
            }
            None => (
                BADGE_WARNING_BG,
                BADGE_WARNING_FG,
                Some(BADGE_WARNING_BORDER),
            ),
        },
        BadgeVariant::Error => (scheme.error_container, scheme.error, None),
        BadgeVariant::Info => match theme.extension::<StatusPalette>() {
            Some(status) => {
                let c = status.colors(theme.brightness);
                (
                    c.info_container,
                    c.info,
                    Some(with_alpha(c.info, BADGE_BORDER_ALPHA)),
                )
            }
            None => (BADGE_INFO_BG, BADGE_INFO_FG, Some(BADGE_INFO_FG)),
        },
        BadgeVariant::Neutral => (
            scheme.surface_container_high,
            scheme.on_surface_variant,
            Some(scheme.outline),
        ),
        BadgeVariant::Accent => (
            with_alpha(scheme.primary, BADGE_ACCENT_WASH_ALPHA),
            scheme.primary,
            None,
        ),
    }
}

fn unthemed_badge_colors(variant: BadgeVariant) -> (Color, Color, Option<Color>) {
    match variant {
        BadgeVariant::Success => (BADGE_SUCCESS_BG, BADGE_SUCCESS_FG, None),
        BadgeVariant::Warning => (
            BADGE_WARNING_BG,
            BADGE_WARNING_FG,
            Some(BADGE_WARNING_BORDER),
        ),
        BadgeVariant::Error => (BADGE_ERROR_BG, BADGE_ERROR_FG, None),
        BadgeVariant::Info => (BADGE_INFO_BG, BADGE_INFO_FG, Some(BADGE_INFO_FG)),
        BadgeVariant::Neutral => (
            BADGE_NEUTRAL_BG,
            BADGE_NEUTRAL_FG,
            Some(BADGE_NEUTRAL_BORDER),
        ),
        BadgeVariant::Accent => (
            with_alpha(BADGE_ACCENT_FG, BADGE_ACCENT_WASH_ALPHA),
            BADGE_ACCENT_FG,
            None,
        ),
    }
}

/// The pill radius: themed `shape.full` resolved against the box (always a
/// true pill, since `full` is infinite in every baseline). Unthemed: half the
/// box height exactly, the same pill shape without a theme to resolve.
fn resolve_badge_radius(theme: Option<&Theme>, size: Size) -> f64 {
    match theme {
        Some(theme) => ShapeScale::resolve(theme.shape.full, size.width, size.height),
        None => size.height / 2.0,
    }
}

impl Widget for BadgeWidget {
    fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
        let theme = Theme::from_layout_ctx(ctx);
        let (_, fg, _) = resolve_badge_colors(theme, self.variant);
        let style = badge_label_style(theme, fg);
        let label_size = self.label.layout(ctx, &style, None);
        self.label_size = label_size;

        let dot_extra = if self.dot {
            BADGE_DOT_SIZE + BADGE_GAP
        } else {
            0.0
        };
        let width = BADGE_PAD_X * 2.0 + dot_extra + label_size.width;
        let content_height = if self.dot {
            label_size.height.max(BADGE_DOT_SIZE)
        } else {
            label_size.height
        };
        let height = content_height + BADGE_PAD_Y * 2.0;
        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 (bg, fg, border) = resolve_badge_colors(theme, self.variant);
        let radius = resolve_badge_radius(theme, ctx.size());
        scene.fill_rounded_rect(ctx.origin(), ctx.size(), radius, bg);
        if let Some(border_color) = border {
            let rr =
                RoundedRect::from_rect(Rect::from_origin_size(Point::ORIGIN, ctx.size()), radius);
            let path = rr.to_path(PATH_TOLERANCE);
            scene.stroke_path(
                ctx.origin(),
                &path,
                BADGE_BORDER_WIDTH,
                &Brush::Solid(border_color),
            );
        }

        let mut x = BADGE_PAD_X;
        if self.dot {
            let y = (ctx.size().height - BADGE_DOT_SIZE) / 2.0;
            scene.fill_rounded_rect(
                ctx.origin() + Vec2::new(x, y),
                Size::new(BADGE_DOT_SIZE, BADGE_DOT_SIZE),
                BADGE_DOT_SIZE / 2.0,
                fg,
            );
            x += BADGE_DOT_SIZE + BADGE_GAP;
        }
        let label_y = (ctx.size().height - self.label_size.height) / 2.0;
        self.label
            .paint(ctx.origin() + Vec2::new(x, label_y), scene);
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        // A live status indicator: `Role::Status` (not `Label`), carrying the
        // original (non-lowercased) label text so a screen reader announces
        // natural casing.
        ctx.push_node(Role::Status, |node| {
            node.set_label(self.label_text.as_str());
        });
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use frust::Brightness;
    use std::any::Any;

    /// Records fills/borders/glyph-run brushes, mirroring
    /// `crate::material::chips`'s `RRectRecorder` plus a glyph-run capture.
    #[derive(Default)]
    struct Recorder {
        rrects: Vec<(Point, Size, f64, Color)>,
        strokes: Vec<Color>,
        glyph_colors: Vec<Color>,
    }

    impl PaintScene for Recorder {
        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 stroke_path(&mut self, _o: Point, _path: &kurbo::BezPath, _width: f64, brush: &Brush) {
            if let Brush::Solid(c) = brush {
                self.strokes.push(*c);
            }
        }
        fn draw_glyph_run(&mut self, run: frust::authoring::scene::GlyphRun) {
            if let Brush::Solid(c) = run.brush {
                self.glyph_colors.push(c);
            }
        }
    }

    fn build_widget(variant: BadgeVariant, dot: bool) -> BadgeWidget {
        let view = badge("Connected", variant).dot(dot);
        let mut counter = 0u64;
        View::<()>::build(&view, &mut BuildCtx::new(&mut counter))
    }

    // `badge()` doesn't need a turbofish in practice (state is inferred from
    // the `View<State>` call site), but the test harness builds it directly.
    fn badge_helper(label: &str, variant: BadgeVariant) -> BadgeView {
        badge(label, variant)
    }

    fn layout_and_paint(widget: &mut BadgeWidget, theme: Option<&Theme>) -> Recorder {
        let mut tcx = TextContext::new();
        let mut lctx = match theme {
            Some(t) => {
                LayoutCtx::with_resources(Some(&mut tcx as &mut dyn Any), Some(t as &dyn Any))
            }
            None => LayoutCtx::with_text_context(&mut tcx as &mut dyn Any),
        };
        let size = widget.layout(&mut lctx, &BoxConstraints::loose(Size::new(400.0, 100.0)));
        let mut rec = Recorder::default();
        let mut pctx = match theme {
            Some(t) => PaintCtx::new(Point::ZERO, size).with_theme(t),
            None => PaintCtx::new(Point::ZERO, size),
        };
        widget.paint(&mut pctx, &mut rec);
        rec
    }

    #[test]
    fn unthemed_success_uses_fallback_constants() {
        let _ = badge_helper("x", BadgeVariant::Success); // exercise the fn form too
        let mut w = build_widget(BadgeVariant::Success, false);
        let rec = layout_and_paint(&mut w, None);
        assert_eq!(rec.rrects[0].3, BADGE_SUCCESS_BG);
        assert_eq!(rec.glyph_colors[0], BADGE_SUCCESS_FG);
    }

    #[test]
    fn unthemed_warning_has_a_border() {
        let mut w = build_widget(BadgeVariant::Warning, false);
        let rec = layout_and_paint(&mut w, None);
        assert_eq!(rec.rrects[0].3, BADGE_WARNING_BG);
        assert_eq!(rec.glyph_colors[0], BADGE_WARNING_FG);
        assert_eq!(rec.strokes[0], BADGE_WARNING_BORDER);
    }

    #[test]
    fn unthemed_info_uses_fallback_constants() {
        let mut w = build_widget(BadgeVariant::Info, false);
        let rec = layout_and_paint(&mut w, None);
        assert_eq!(rec.rrects[0].3, BADGE_INFO_BG);
        assert_eq!(rec.glyph_colors[0], BADGE_INFO_FG);
        assert_eq!(rec.strokes[0], BADGE_INFO_FG);
    }

    #[test]
    fn unthemed_neutral_has_a_border() {
        let mut w = build_widget(BadgeVariant::Neutral, false);
        let rec = layout_and_paint(&mut w, None);
        assert_eq!(rec.rrects[0].3, BADGE_NEUTRAL_BG);
        assert_eq!(rec.strokes[0], BADGE_NEUTRAL_BORDER);
    }

    #[test]
    fn unthemed_accent_is_a_true_alpha_wash() {
        let mut w = build_widget(BadgeVariant::Accent, false);
        let rec = layout_and_paint(&mut w, None);
        assert_eq!(
            rec.rrects[0].3,
            with_alpha(BADGE_ACCENT_FG, BADGE_ACCENT_WASH_ALPHA)
        );
        assert_eq!(rec.glyph_colors[0], BADGE_ACCENT_FG);
    }

    #[test]
    fn glyph_dark_theme_resolves_success_from_status_palette() {
        let theme = crate::baseline();
        let mut w = build_widget(BadgeVariant::Success, false);
        let rec = layout_and_paint(&mut w, Some(&theme));
        let status = theme.extension::<StatusPalette>().unwrap();
        let colors = status.colors(Brightness::Dark);
        assert_eq!(rec.rrects[0].3, colors.success_container);
        assert_eq!(rec.glyph_colors[0], colors.success);
    }

    #[test]
    fn glyph_light_theme_resolves_warning_from_status_palette() {
        let theme = crate::baseline().with_brightness(Brightness::Light);
        let mut w = build_widget(BadgeVariant::Warning, false);
        let rec = layout_and_paint(&mut w, Some(&theme));
        let status = theme.extension::<StatusPalette>().unwrap();
        let colors = status.colors(Brightness::Light);
        assert_eq!(rec.rrects[0].3, colors.warning_container);
        assert_eq!(rec.glyph_colors[0], colors.warning);
        assert_eq!(
            rec.strokes[0],
            with_alpha(colors.warning, BADGE_BORDER_ALPHA)
        );
    }

    #[test]
    fn glyph_dark_theme_resolves_info_from_status_palette() {
        let theme = crate::baseline();
        let mut w = build_widget(BadgeVariant::Info, false);
        let rec = layout_and_paint(&mut w, Some(&theme));
        let status = theme.extension::<StatusPalette>().unwrap();
        let colors = status.colors(Brightness::Dark);
        assert_eq!(rec.rrects[0].3, colors.info_container);
        assert_eq!(rec.glyph_colors[0], colors.info);
        assert_eq!(rec.strokes[0], with_alpha(colors.info, BADGE_BORDER_ALPHA));
    }

    #[test]
    fn glyph_light_theme_resolves_info_from_status_palette() {
        let theme = crate::baseline().with_brightness(Brightness::Light);
        let mut w = build_widget(BadgeVariant::Info, false);
        let rec = layout_and_paint(&mut w, Some(&theme));
        let status = theme.extension::<StatusPalette>().unwrap();
        let colors = status.colors(Brightness::Light);
        assert_eq!(rec.rrects[0].3, colors.info_container);
        assert_eq!(rec.glyph_colors[0], colors.info);
        assert_eq!(rec.strokes[0], with_alpha(colors.info, BADGE_BORDER_ALPHA));
    }

    #[test]
    fn glyph_theme_resolves_error_from_color_scheme_directly() {
        let theme = crate::baseline();
        let mut w = build_widget(BadgeVariant::Error, false);
        let rec = layout_and_paint(&mut w, Some(&theme));
        assert_eq!(rec.rrects[0].3, theme.scheme().error_container);
        assert_eq!(rec.glyph_colors[0], theme.scheme().error);
    }

    #[test]
    fn glyph_theme_resolves_radius_as_a_pill() {
        let theme = crate::baseline();
        let mut w = build_widget(BadgeVariant::Success, false);
        let rec = layout_and_paint(&mut w, Some(&theme));
        let (_, size, radius, _) = rec.rrects[0];
        assert_eq!(radius, size.height / 2.0);
    }

    #[test]
    fn all_variants_resolved_colors_are_pinned() {
        // This test prevents silent restyling of shipped badge variants.
        // If you need to change a variant's appearance, update these assertions
        // and document the change in the commit message.
        let theme = crate::baseline();

        // Success: no border
        let mut w = build_widget(BadgeVariant::Success, false);
        let rec = layout_and_paint(&mut w, Some(&theme));
        let status = theme.extension::<StatusPalette>().unwrap();
        let sc = status.colors(Brightness::Dark);
        assert_eq!(rec.rrects[0].3, sc.success_container);
        assert_eq!(rec.glyph_colors[0], sc.success);
        assert_eq!(rec.strokes.len(), 0, "Success should have no border");

        // Warning: has border
        let mut w = build_widget(BadgeVariant::Warning, false);
        let rec = layout_and_paint(&mut w, Some(&theme));
        assert_eq!(rec.rrects[0].3, sc.warning_container);
        assert_eq!(rec.glyph_colors[0], sc.warning);
        assert_eq!(
            rec.strokes[0],
            with_alpha(sc.warning, BADGE_BORDER_ALPHA),
            "Warning should have alpha-blended border"
        );

        // Error: no border
        let mut w = build_widget(BadgeVariant::Error, false);
        let rec = layout_and_paint(&mut w, Some(&theme));
        assert_eq!(rec.rrects[0].3, theme.scheme().error_container);
        assert_eq!(rec.glyph_colors[0], theme.scheme().error);
        assert_eq!(rec.strokes.len(), 0, "Error should have no border");

        // Neutral: has border
        let mut w = build_widget(BadgeVariant::Neutral, false);
        let rec = layout_and_paint(&mut w, Some(&theme));
        assert_eq!(rec.rrects[0].3, theme.scheme().surface_container_high);
        assert_eq!(rec.glyph_colors[0], theme.scheme().on_surface_variant);
        assert_eq!(
            rec.strokes[0],
            theme.scheme().outline,
            "Neutral should have outline border"
        );

        // Accent: no border, alpha-washed background
        let mut w = build_widget(BadgeVariant::Accent, false);
        let rec = layout_and_paint(&mut w, Some(&theme));
        assert_eq!(
            rec.rrects[0].3,
            with_alpha(theme.scheme().primary, BADGE_ACCENT_WASH_ALPHA)
        );
        assert_eq!(rec.glyph_colors[0], theme.scheme().primary);
        assert_eq!(rec.strokes.len(), 0, "Accent should have no border");
    }

    #[test]
    fn dot_widens_the_badge_and_paints_a_dot_colored_like_the_label() {
        let mut plain = build_widget(BadgeVariant::Success, false);
        let mut dotted = build_widget(BadgeVariant::Success, true);
        let rec_plain = layout_and_paint(&mut plain, None);
        let rec_dotted = layout_and_paint(&mut dotted, None);
        assert!(rec_dotted.rrects[0].1.width > rec_plain.rrects[0].1.width);
        // rrects[0] is the pill background; rrects[1] is the dot.
        assert_eq!(rec_dotted.rrects.len(), 2);
        assert_eq!(rec_dotted.rrects[1].3, BADGE_SUCCESS_FG);
    }

    #[test]
    fn label_is_rendered_lowercase() {
        let w = build_widget(BadgeVariant::Neutral, false);
        // Not directly observable via the recorder (glyph runs carry shaped
        // glyphs, not the source string), but the retained content is:
        assert_eq!(w.label.content, "connected");
        assert_eq!(w.label_text, "Connected");
    }

    #[test]
    fn semantics_reports_status_role_and_original_casing() {
        fn logic(_s: &mut ()) -> BadgeView {
            badge("Connected", BadgeVariant::Success)
        }
        let mut root: frust_core::RenderRoot<(), BadgeView> = frust_core::RenderRoot::new();
        let mut state = ();
        root.rebuild(&mut logic, &mut state);
        let mut tcx = TextContext::new();
        root.layout_with_text(Size::new(200.0, 200.0), &mut tcx as &mut dyn Any);
        let update = root.semantics();
        let (_, node) = update
            .nodes
            .iter()
            .find(|(_, n)| n.role() == Role::Status)
            .expect("badge contributes a Role::Status node");
        assert_eq!(node.label(), Some("Connected"));
    }

    // ---- Typeface: the label's family follows the live theme ----------------

    #[cfg(feature = "bundled-fonts")]
    #[test]
    fn the_label_paints_in_its_role_face_under_the_glyph_theme() {
        use super::typeface_probe::{Face, painted_faces};
        let faces = painted_faces(
            |_: &mut ()| badge("online", BadgeVariant::Success),
            crate::baseline(),
            Size::new(200.0, 60.0),
        );
        assert_eq!(faces, [Face::PlexMono]);
    }

    #[cfg(feature = "bundled-fonts")]
    #[test]
    fn the_label_follows_a_live_theme_family_swap() {
        use super::typeface_probe::{Face, faces_across_a_live_swap};
        let (before, after) = faces_across_a_live_swap(
            |_: &mut ()| badge("online", BadgeVariant::Success),
            Size::new(200.0, 60.0),
        );
        assert_eq!(before, [Face::PlexMono]);
        assert_eq!(after, [Face::SpaceMono]);
    }
}

/// A render-time typeface probe for the catalog's own text runs: paints a
/// view through a real `RenderRoot` with every bundled Glyph face registered
/// and reports, per painted glyph run in paint order, which bundled family
/// that run's font bytes belong to.
///
/// Registering a face proves nothing about what paints — a run that never
/// asks for the theme's family paints whatever it hardcodes right beside a
/// registered face — so the tests built on this assert on the runs.
///
/// Glyph's scale carries two families: Space Mono in every display/headline
/// role, IBM Plex Mono in every title/body/label role. A swap test therefore
/// pushes [`inverted_glyph_theme`] (the same scale with those two families
/// traded) into the live root: a run that takes its family from its role
/// flips face, and a run with a fixed family stays where it was.
///
/// The first probe in a process also paints a control: a plain `text(..)`
/// (the `SystemUi` request) must paint in neither bundled family, or an
/// identity assertion could pass on a host that resolves the system face to
/// one of them.
#[cfg(all(test, feature = "bundled-fonts"))]
pub(crate) mod typeface_probe {
    use std::any::Any;
    use std::sync::{Once, OnceLock};

    use frust::Theme;
    use frust::authoring::scene::GlyphRun;
    use frust::authoring::text::{FontFamily, GenericSlot, TextContext};
    use frust::authoring::{PaintScene, View};
    use frust_core::{FrameTime, RenderRoot};
    use kurbo::{Point, Size};
    use peniko::Color;

    /// The bundled family a painted glyph run shaped in.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub(crate) enum Face {
        /// A Space Mono face: Glyph's display/headline family.
        SpaceMono,
        /// An IBM Plex Mono face: Glyph's title/body/label family.
        PlexMono,
        /// Any other face (a system or fallback font).
        Other,
    }

    /// Every bundled face's bytes, with the family its own `name` table
    /// registers under. Registering is process-wide (`TextContext`'s app-font
    /// record), so each face is registered once and every `TextContext` built
    /// afterwards resolves it.
    fn bundled_faces() -> &'static [(&'static [u8], Face)] {
        static FACES: OnceLock<Vec<(&'static [u8], Face)>> = OnceLock::new();
        FACES.get_or_init(|| {
            let mut tcx = TextContext::new();
            crate::font_data()
                .iter()
                .map(|&bytes| {
                    let families = tcx
                        .register_fonts(bytes.to_vec())
                        .expect("a bundled Glyph face registers");
                    let face = match families.first().map(|family| family.name.as_str()) {
                        Some("Space Mono") => Face::SpaceMono,
                        Some("IBM Plex Mono") => Face::PlexMono,
                        other => panic!("unexpected bundled family {other:?}"),
                    };
                    (bytes, face)
                })
                .collect()
        })
    }

    /// Records, per painted glyph run, the bundled family its bytes belong to.
    pub(crate) struct FaceRecorder {
        /// One entry per `draw_glyph_run` call, in paint order.
        pub(crate) faces: Vec<Face>,
    }

    impl FaceRecorder {
        pub(crate) fn new() -> Self {
            Self { faces: Vec::new() }
        }
    }

    impl PaintScene for FaceRecorder {
        fn fill_rect(&mut self, _o: Point, _s: Size, _c: Color) {}
        fn draw_text(&mut self, _o: Point, _t: &str) {}
        fn draw_glyph_run(&mut self, run: GlyphRun) {
            let bytes = run.font.font().data.as_ref();
            let face = bundled_faces()
                .iter()
                .find(|(face_bytes, _)| *face_bytes == bytes)
                .map_or(Face::Other, |(_, face)| *face);
            self.faces.push(face);
        }
    }

    /// A fresh text context that resolves every bundled Glyph face by name.
    fn registered_context() -> TextContext {
        bundled_faces();
        TextContext::new()
    }

    /// A text context that resolves every bundled Glyph face by name, for a
    /// test driving a widget directly. Runs the control first (see the
    /// [module docs](self)).
    pub(crate) fn text_context() -> TextContext {
        assert_control();
        registered_context()
    }

    /// Glyph's baseline with its two families traded: every display/headline
    /// role names IBM Plex Mono, every title/body/label role Space Mono.
    pub(crate) fn inverted_glyph_theme() -> Theme {
        let space = FontFamily::stack_with_generic(["Space Mono"], GenericSlot::Monospace);
        let plex = FontFamily::stack_with_generic(["IBM Plex Mono"], GenericSlot::Monospace);
        let mut theme = crate::baseline();
        macro_rules! set_family {
            ($family:ident => $($role:ident),+ $(,)?) => {
                $( theme.type_scale.$role.family = $family.clone(); )+
            };
        }
        set_family!(plex =>
            display_large, display_medium, display_small,
            headline_large, headline_medium, headline_small,
            display_large_emphasized, display_medium_emphasized, display_small_emphasized,
            headline_large_emphasized, headline_medium_emphasized, headline_small_emphasized,
        );
        set_family!(space =>
            title_large, title_medium, title_small,
            body_large, body_medium, body_small,
            label_large, label_medium, label_small,
            title_large_emphasized, title_medium_emphasized, title_small_emphasized,
            body_large_emphasized, body_medium_emphasized, body_small_emphasized,
            label_large_emphasized, label_medium_emphasized, label_small_emphasized,
        );
        theme
    }

    /// The simulated frame interval a settling paint pass advances by.
    const FRAME_NS: u64 = 16_000_000;
    /// How long a paint pass lets an enter animation run before it reports
    /// the frame it has, settled or not.
    const SETTLE_NS: u64 = 5_000_000_000;

    /// Lays `root` out in `window` against `tcx`, then paints frames from
    /// `*now` on — re-laying out whenever a paint asks — until the tree stops
    /// asking for frames, so a component that animates in (a menu's item
    /// stagger, a dialog's enter) is measured at rest. Returns the last
    /// frame's run faces and leaves `*now` at that frame.
    fn paint_pass<V: View<()>>(
        root: &mut RenderRoot<(), V>,
        window: Size,
        tcx: &mut TextContext,
        now: &mut u64,
    ) -> Vec<Face> {
        root.layout_with_text(window, tcx as &mut dyn Any);
        let deadline = *now + SETTLE_NS;
        loop {
            let mut recorder = FaceRecorder::new();
            let outcome = root.paint(&mut recorder, FrameTime::from_nanos(*now));
            if !(outcome.needs_frame || outcome.needs_layout) || *now >= deadline {
                return recorder.faces;
            }
            if outcome.needs_layout {
                root.layout_with_text(window, tcx as &mut dyn Any);
            }
            *now += FRAME_NS;
        }
    }

    /// Panics unless a plain `text(..)` paints in neither bundled family
    /// (see the [module docs](self)). Runs once per process.
    fn assert_control() {
        static CONTROL: Once = Once::new();
        CONTROL.call_once(|| {
            let mut root: RenderRoot<(), _> = RenderRoot::new();
            root.set_theme(Box::new(crate::baseline()));
            root.rebuild(&mut |_: &mut ()| frust::text("Hello"), &mut ());
            let faces = paint_pass(
                &mut root,
                Size::new(200.0, 60.0),
                &mut registered_context(),
                &mut 0,
            );
            assert!(
                faces.iter().all(|face| *face == Face::Other),
                "control: a plain text() that never asks for a Glyph family painted {faces:?} \
                 — on this host an un-opted run is indistinguishable from a bundled face, \
                 so the typeface assertions would prove nothing"
            );
        });
    }

    /// Paints `logic`'s view under `theme` in `window`, settled (see
    /// `paint_pass`), and returns each painted run's face, in paint order.
    pub(crate) fn painted_faces<V: View<()>>(
        mut logic: impl FnMut(&mut ()) -> V,
        theme: Theme,
        window: Size,
    ) -> Vec<Face> {
        let mut tcx = text_context();
        let mut root: RenderRoot<(), V> = RenderRoot::new();
        root.set_theme(Box::new(theme));
        root.rebuild(&mut logic, &mut ());
        paint_pass(&mut root, window, &mut tcx, &mut 0)
    }

    /// Paints `logic`'s view under Glyph's own baseline, then pushes
    /// [`inverted_glyph_theme`] into the same live root — no rebuild, the way
    /// a shell delivers a theme change — and paints it again, each pass
    /// settled (see `paint_pass`). Returns both passes' faces, in paint order.
    pub(crate) fn faces_across_a_live_swap<V: View<()>>(
        mut logic: impl FnMut(&mut ()) -> V,
        window: Size,
    ) -> (Vec<Face>, Vec<Face>) {
        let mut tcx = text_context();
        let mut root: RenderRoot<(), V> = RenderRoot::new();
        root.set_theme(Box::new(crate::baseline()));
        root.rebuild(&mut logic, &mut ());
        let mut now = 0;
        let before = paint_pass(&mut root, window, &mut tcx, &mut now);
        root.set_theme(Box::new(inverted_glyph_theme()));
        let after = paint_pass(&mut root, window, &mut tcx, &mut now);
        (before, after)
    }
}