frust-widgets 0.6.3

Baseline widget set for Frust: text, buttons, images, flex, stack and scroll containers, and the authoring helpers for custom widgets.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
//! The `Slider` interactive widget: a horizontal track with a thumb
//! that reports a `0.0..=1.0` value as it is dragged.
//!
//! [`slider`] produces a [`SliderView`] carrying the current `value` and an
//! `on_change` closure. A `Down` on the track captures the pointer and reports
//! the value at that x-position; each captured `Move` reports the updated value
//! (continuous drag); `Up`/`Cancel` release. Like [`crate::Checkbox`] it is not
//! its own source of truth — it fires `on_change` and the next rebuild feeds the
//! new value back in. Horizontal only for v1.
//!
//! A slider is a Tab stop; while focused, a bare Left/Down arrow requests the value `0.05`
//! lower, Right/Up `0.05` higher, Home `0.0` and End `1.0` (auto-repeat included). A primary
//! mouse press also takes focus, so the next Tab continues from here; a touch tap never claims it.
//!
//! # Design-language branch
//!
//! `paint` reads [`Theme::design_language`] and re-skins the knob only when it
//! is [`DesignLanguage::Cupertino`] — groove/fill geometry, colors, event
//! handling, and the entire `Material3`/unthemed path are **untouched**: a
//! Material-tagged or unthemed paint runs the exact same sequence as before
//! this branch was added (same `fill_rounded_rect` call count/order/values),
//! so Material rendering stays byte-identical. The kit's mined data
//! (`kit-colors-type-metrics.json`) has **no `Sliders` size record at all**
//! (only shadow recipes for the knob in `glass-recipes.json`, with no
//! width/height fields). Per the same evidence rule this repo applies to any
//! unsourced platform metric,
//! [`CUPERTINO_THUMB`] is therefore **community-approximate**, not kit-cited
//! (see its doc comment); the groove thickness ([`TRACK_H`]) is shared with
//! the Material path unchanged, since there is no evidence either way to
//! diverge it. The knob's reflective treatment (drop shadow + specular
//! gradient) reads the theme's own `glass.control` tier (buttons/toggles/
//! sliders — the "control" glass tier covers interactive controls generally,
//! see `frust-theme/src/glass.rs`'s module docs), so the recipe is whatever
//! the active design system authored, never a value named here. iOS 26.2's
//! "Liquid Glass
//! slider" claims (a user-facing OS tint-adjustment control) are **not**
//! what this branch re-skins — this is Frust's `Slider` widget, a different
//! control; this widget ships a visual re-skin only, no behavior changes.

use std::rc::Rc;

use frust_core::accesskit::Role;
use frust_core::{
    BoxConstraints, BuildCtx, ChangeFlags, EventCtx, EventResult, InputEvent, Key, KeyEvent,
    LayoutCtx, Modifiers, NamedKey, PaintCtx, PaintScene, PointerPhase, SemanticsCtx, View, Widget,
};
use frust_theme::{DesignLanguage, GlassMaterial, GlassScale, Theme};
use kurbo::{Point, Size};
use peniko::{Brush, Color, Gradient};

use crate::authoring::presses;
use crate::shortcuts::press_claims_focus;

/// How far one arrow key moves a focused slider: twenty steps across the track.
const KEY_STEP: f64 = 0.05;
/// Slider control height, in logical px.
const HEIGHT: f64 = 24.0;
/// Default track width when the incoming constraints are unbounded.
const DEFAULT_WIDTH: f64 = 200.0;
/// Track (groove) thickness, in logical px. Shared by both design-language
/// paths (see the module docs' Design-language branch section — no kit or
/// community evidence to diverge it for Cupertino).
const TRACK_H: f64 = 4.0;
/// Thumb diameter, in logical px — the Material path only (see [`THUMB_FILL`]
/// for its color; [`CUPERTINO_THUMB`] is the Cupertino-branch equivalent).
const THUMB: f64 = 18.0;
/// Cupertino knob diameter, in logical px.
///
/// **Community-approximate**, not kit-cited: the kit's mined data has no
/// `Sliders` size record at all (see the module docs) — 28pt is the
/// widely-cited default `UISlider` thumb diameter community reimplementations
/// converge on, distinctly larger than the Material path's 18pt (M3's own
/// slider spec).
const CUPERTINO_THUMB: f64 = 28.0;
/// The Cupertino knob's fill — plain white, mirroring
/// [`crate::cupertino::switch`]'s knob and `UISlider`'s stock white-circle
/// thumb (its `minimumTrackTintColor`/active-fill carries the tint instead;
/// see [`resolve_colors`]'s `fill`, reused unchanged for the active track on
/// both design-language paths).
const CUPERTINO_THUMB_FILL: Color = Color::from_rgb8(0xFF, 0xFF, 0xFF);
/// Peak alpha of the Cupertino knob's specular-highlight gradient at its
/// center — see [`crate::cupertino::switch`]'s constant of the same name and
/// role (this module mirrors that treatment exactly).
const SPECULAR_PEAK_SCALE: f32 = 1.8;
/// Unfilled (inactive) track color (unthemed fallback; a theme resolves this
/// from `colors.surface_container_highest`, per the M3 slider spec).
const TRACK: Color = Color::from_rgb8(0xD1, 0xD5, 0xDB);
/// Filled (active) track color (unthemed fallback; a theme resolves this from
/// `colors.primary`).
const FILL: Color = Color::from_rgb8(0x3B, 0x82, 0xF6);
/// Thumb color (unthemed fallback; a theme resolves this from `colors.primary`).
const THUMB_FILL: Color = Color::from_rgb8(0x1D, 0x4E, 0xD8);

/// The resolved slider paint colors: `(inactive_track, active_track, thumb)`.
/// Themed per the Material 3 slider spec: the inactive track is
/// `surface_container_highest`, the active track and thumb are `primary`.
/// Unthemed: the [`TRACK`]/[`FILL`]/[`THUMB_FILL`] constants exactly, so a
/// pre-theme app renders unchanged.
fn resolve_colors(theme: Option<&Theme>) -> (Color, Color, Color) {
    match theme {
        Some(theme) => {
            let scheme = theme.scheme();
            (
                scheme.surface_container_highest,
                scheme.primary,
                scheme.primary,
            )
        }
        None => (TRACK, FILL, THUMB_FILL),
    }
}

/// `true` when `theme` is tagged [`DesignLanguage::Cupertino`] — the sole
/// gate on the Cupertino knob branch (see the module docs). An unthemed paint
/// (`None`) and a `Material3`-tagged one both return `false`, running the
/// Material path unchanged.
fn is_cupertino(theme: Option<&Theme>) -> bool {
    theme.map(|t| t.design_language) == Some(DesignLanguage::Cupertino)
}

/// The `control` glass tier (buttons/toggles/sliders) the Cupertino knob's
/// shadow/highlight reads: `theme.glass.control`.
///
/// The unthemed arm is **unreachable by construction** — the sole call site
/// sits inside the `is_cupertino(theme)` guard in `paint`, and
/// `is_cupertino(None)` is `false`, so `theme` is always `Some` here. It
/// therefore resolves to the language-free [`GlassScale::opaque_material`]
/// tier rather than naming a design language's glass recipe: a fallback no
/// paint pass can observe must not pin this baseline widget to a catalog's
/// token table.
fn resolve_control_glass(theme: Option<&Theme>) -> GlassMaterial {
    theme
        .map(|t| t.glass.control.clone())
        .unwrap_or_else(|| GlassScale::opaque_material().control)
}

/// 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 view-held, typed change callback (erased on build).
type OnChange<State> = Rc<dyn Fn(&mut State, f64)>;

/// A declarative slider. See the [module docs](self).
pub struct SliderView<State: 'static> {
    value: f64,
    on_change: OnChange<State>,
}

/// Create a slider at `value` (clamped to `0.0..=1.0`) that fires
/// `on_change(state, new_value)` as it is dragged.
pub fn slider<State: 'static, F: Fn(&mut State, f64) + 'static>(
    value: f64,
    on_change: F,
) -> SliderView<State> {
    SliderView {
        value: value.clamp(0.0, 1.0),
        on_change: Rc::new(on_change),
    }
}

/// PascalCase alias for [`slider`].
#[allow(non_snake_case)]
pub fn Slider<State: 'static, F: Fn(&mut State, f64) + 'static>(
    value: f64,
    on_change: F,
) -> SliderView<State> {
    slider(value, on_change)
}

/// The retained widget for a [`SliderView`].
pub struct SliderWidget {
    value: f64,
    /// Armed by a `Down` (alongside `capture_pointer`), cleared on `Up`/`Cancel`.
    /// Gates `Move` so a hover `Move` (no prior press) never fires `on_change`;
    /// a `Down` still jumps to and reports the tapped value regardless.
    captured: bool,
    on_change: crate::authoring::ErasedArgCallback<f64>,
}

/// The value a bare navigation `key` asks for from `value`, or `None` for any other key.
fn value_from_key(key: &KeyEvent, value: f64) -> Option<f64> {
    if key.modifiers != Modifiers::default() {
        return None;
    }
    let Key::Named(named) = &key.key else {
        return None;
    };
    let next = match named {
        NamedKey::ArrowLeft | NamedKey::ArrowDown => value - KEY_STEP,
        NamedKey::ArrowRight | NamedKey::ArrowUp => value + KEY_STEP,
        NamedKey::Home => 0.0,
        NamedKey::End => 1.0,
        _ => return None,
    };
    Some(next.clamp(0.0, 1.0))
}

/// Map a widget-local x (in `0..=width`) to a `0.0..=1.0` value, clamped.
fn value_from_x(x: f64, width: f64) -> f64 {
    if width <= 0.0 {
        0.0
    } else {
        (x / width).clamp(0.0, 1.0)
    }
}

impl<State: 'static> View<State> for SliderView<State> {
    type Element = SliderWidget;

    fn build(&self, _ctx: &mut BuildCtx<'_>) -> SliderWidget {
        SliderWidget {
            value: self.value,
            captured: false,
            on_change: crate::authoring::erase_callback_arg(&self.on_change),
        }
    }

    fn rebuild(
        &self,
        prev: &Self,
        element: &mut SliderWidget,
        _ctx: &mut BuildCtx<'_>,
    ) -> ChangeFlags {
        element.on_change = crate::authoring::erase_callback_arg(&self.on_change);
        if prev.value != self.value {
            element.value = self.value;
            ChangeFlags::PAINT
        } else {
            ChangeFlags::NONE
        }
    }
}

impl Widget for SliderWidget {
    fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
        let width = if bc.max().width.is_finite() {
            bc.max().width
        } else {
            DEFAULT_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 (track, fill, thumb_fill) = resolve_colors(theme);
        let o = ctx.origin();
        let w = ctx.size().width;
        let mid_y = o.y + ctx.size().height / 2.0;
        // Groove.
        scene.fill_rounded_rect(
            Point::new(o.x, mid_y - TRACK_H / 2.0),
            Size::new(w, TRACK_H),
            TRACK_H / 2.0,
            track,
        );
        // Filled portion up to the thumb.
        let thumb_x = o.x + self.value.clamp(0.0, 1.0) * w;
        scene.fill_rounded_rect(
            Point::new(o.x, mid_y - TRACK_H / 2.0),
            Size::new((thumb_x - o.x).max(0.0), TRACK_H),
            TRACK_H / 2.0,
            fill,
        );

        if is_cupertino(theme) {
            // Cupertino re-skin: larger reflective knob — see
            // the module docs' Design-language branch section.
            let diam = CUPERTINO_THUMB;
            let thumb_origin = Point::new(thumb_x - diam / 2.0, mid_y - diam / 2.0);
            let thumb_size = Size::new(diam, diam);
            let glass_control = resolve_control_glass(theme);
            scene.draw_shadow(
                Point::new(
                    thumb_origin.x,
                    thumb_origin.y + glass_control.shadow.y_offset,
                ),
                thumb_size,
                diam / 2.0,
                glass_control.shadow.blur_std_dev,
                with_alpha(Color::BLACK, glass_control.shadow.color_alpha),
            );
            scene.fill_rounded_rect(thumb_origin, thumb_size, diam / 2.0, CUPERTINO_THUMB_FILL);
            let highlight_center = Point::new(thumb_x - diam * 0.18, mid_y - diam * 0.28);
            let peak_alpha = (glass_control.hairline_alpha * SPECULAR_PEAK_SCALE).min(1.0);
            let highlight = Gradient::new_radial(highlight_center, (diam * 0.65) as f32)
                .with_stops([
                    (0.0f32, with_alpha(CUPERTINO_THUMB_FILL, peak_alpha)),
                    (1.0f32, with_alpha(CUPERTINO_THUMB_FILL, 0.0)),
                ]);
            scene.fill_rounded_rect_brush(
                thumb_origin,
                thumb_size,
                diam / 2.0,
                &Brush::Gradient(highlight),
            );
        } else {
            // Material path (and unthemed): byte-identical to the pre-Cupertino
            // behavior — thumb (rounded-rect stand-in for a circle in v1).
            scene.fill_rounded_rect(
                Point::new(thumb_x - THUMB / 2.0, mid_y - THUMB / 2.0),
                Size::new(THUMB, THUMB),
                THUMB / 2.0,
                thumb_fill,
            );
        }
    }

    fn event(&mut self, ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
        if let InputEvent::Key(key) = event {
            let Some(v) = value_from_key(key, self.value).filter(|_| ctx.has_focus()) else {
                return EventResult::Ignored;
            };
            // An arrow at either end is still answered, so it never scrolls an ancestor.
            if v != self.value {
                (self.on_change)(ctx, v);
                ctx.request_redraw();
            }
            return EventResult::Handled;
        }
        let InputEvent::Pointer(p) = event else {
            return EventResult::Ignored;
        };
        match p.phase {
            PointerPhase::Down => {
                if !presses(p) {
                    return EventResult::Ignored;
                }
                if press_claims_focus(ctx) {
                    ctx.request_focus();
                }
                self.captured = true;
                ctx.capture_pointer();
                let v = value_from_x(p.position.x, ctx.size().width);
                (self.on_change)(ctx, v);
                ctx.request_redraw();
                EventResult::Handled
            }
            PointerPhase::Move => {
                // A hover `Move` (no prior press) never reports a value.
                if !self.captured {
                    return EventResult::Ignored;
                }
                let v = value_from_x(p.position.x, ctx.size().width);
                (self.on_change)(ctx, v);
                ctx.request_redraw();
                EventResult::Handled
            }
            PointerPhase::Up | PointerPhase::Cancel => {
                if !self.captured {
                    return EventResult::Ignored;
                }
                self.captured = false;
                ctx.request_redraw();
                EventResult::Handled
            }
        }
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        // A Slider node exposing its normalized `0.0..=1.0` value and range.
        ctx.push_node(Role::Slider, |node| {
            node.set_numeric_value(self.value);
            node.set_min_numeric_value(0.0);
            node.set_max_numeric_value(1.0);
        });
    }

    /// Always a Tab stop; a primary mouse press also takes focus (see the module docs).
    fn is_focusable(&self) -> bool {
        true
    }
}

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

    #[derive(Default)]
    struct Val {
        value: f64,
        changes: u32,
    }

    fn widget(value: f64) -> SliderWidget {
        let view = slider::<Val, _>(value, |s: &mut Val, v: f64| {
            s.value = v;
            s.changes += 1;
        });
        let mut counter = 0u64;
        View::<Val>::build(&view, &mut BuildCtx::new(&mut counter))
    }

    fn ev(phase: PointerPhase, x: f64) -> InputEvent {
        InputEvent::Pointer(frust_core::PointerEvent {
            phase,
            position: Point::new(x, 12.0),
            button: frust_core::PointerButton::Primary,
        })
    }

    /// The same event on the secondary (right) button.
    fn secondary_ev(phase: PointerPhase, x: f64) -> InputEvent {
        InputEvent::Pointer(frust_core::PointerEvent {
            phase,
            position: Point::new(x, 12.0),
            button: frust_core::PointerButton::Secondary,
        })
    }

    fn dispatch(w: &mut SliderWidget, state: &mut Val, event: &InputEvent) {
        let state_any: &mut dyn Any = state;
        let mut ctx = EventCtx::new(state_any, Point::ZERO, Size::new(200.0, HEIGHT));
        w.event(&mut ctx, event);
    }

    #[test]
    fn a_secondary_press_never_captures_or_reports_a_value() {
        let mut w = widget(0.0);
        let mut state = Val::default();
        dispatch(&mut w, &mut state, &secondary_ev(PointerPhase::Down, 50.0));
        assert!(!w.captured, "no capture opened");
        assert_eq!(state.changes, 0, "and no value reported");
        // A move after it is an ordinary uncaptured pass, not a drag.
        dispatch(&mut w, &mut state, &ev(PointerPhase::Move, 120.0));
        assert_eq!(state.changes, 0);

        // The primary press still reports.
        dispatch(&mut w, &mut state, &ev(PointerPhase::Down, 50.0));
        assert!(w.captured);
        assert_eq!(state.value, 0.25);
    }

    #[test]
    fn value_math_maps_position_to_fraction() {
        assert_eq!(value_from_x(0.0, 200.0), 0.0);
        assert_eq!(value_from_x(100.0, 200.0), 0.5);
        assert_eq!(value_from_x(200.0, 200.0), 1.0);
        // Clamps outside the track.
        assert_eq!(value_from_x(-40.0, 200.0), 0.0);
        assert_eq!(value_from_x(9000.0, 200.0), 1.0);
        // Degenerate zero-width track.
        assert_eq!(value_from_x(10.0, 0.0), 0.0);
    }

    #[test]
    fn down_reports_value_at_position() {
        let mut w = widget(0.0);
        let mut state = Val::default();
        dispatch(&mut w, &mut state, &ev(PointerPhase::Down, 50.0));
        assert_eq!(state.value, 0.25);
        assert_eq!(state.changes, 1);
    }

    #[test]
    fn drag_reports_continuously_and_clamps() {
        let mut w = widget(0.0);
        let mut state = Val::default();
        dispatch(&mut w, &mut state, &ev(PointerPhase::Down, 100.0));
        dispatch(&mut w, &mut state, &ev(PointerPhase::Move, 300.0)); // past the end
        assert_eq!(state.value, 1.0);
        dispatch(&mut w, &mut state, &ev(PointerPhase::Move, -20.0)); // before the start
        assert_eq!(state.value, 0.0);
        assert_eq!(state.changes, 3);
        // Up does not report a value.
        dispatch(&mut w, &mut state, &ev(PointerPhase::Up, 0.0));
        assert_eq!(state.changes, 3);
    }

    #[test]
    fn hover_move_without_down_is_ignored_noop() {
        let mut w = widget(0.3);
        let mut state = Val::default();
        let state_any: &mut dyn Any = &mut state;
        let mut ctx = EventCtx::new(state_any, Point::ZERO, Size::new(200.0, HEIGHT));
        let result = w.event(&mut ctx, &ev(PointerPhase::Move, 100.0));
        assert!(matches!(result, EventResult::Ignored));
        assert!(!ctx.needs_redraw(), "hover must not request a redraw");
        assert_eq!(state.changes, 0, "hover must not report a value");
    }

    #[test]
    fn cancel_clears_captured_state() {
        let mut w = widget(0.0);
        let mut state = Val::default();
        dispatch(&mut w, &mut state, &ev(PointerPhase::Down, 100.0));
        assert!(w.captured);
        dispatch(&mut w, &mut state, &ev(PointerPhase::Cancel, 100.0));
        assert!(!w.captured, "Cancel disarms the drag");
        // A follow-up hover Move must not report.
        let before = state.changes;
        dispatch(&mut w, &mut state, &ev(PointerPhase::Move, 40.0));
        assert_eq!(state.changes, before, "hover after Cancel does not report");
    }

    /// Records rounded-rect fill colors in paint order (track, fill, thumb).
    /// `shadows`/`brushes` separately record the Cupertino knob's reflective-
    /// treatment calls (`draw_shadow`/`fill_rounded_rect_brush`), which never
    /// fire on the Material path (see `material_and_unthemed_paint_have_no_reflective_treatment`).
    #[derive(Default)]
    struct TrackRecorder {
        rrects: Vec<Color>,
        shadows: Vec<(Point, Size, f64, f64, Color)>,
        brushes: Vec<(Point, Size, f64, Brush)>,
    }

    impl PaintScene for TrackRecorder {
        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, _r: f64, color: Color) {
            self.rrects.push(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 fill_rounded_rect_brush(&mut self, o: Point, s: Size, radius: f64, brush: &Brush) {
            self.brushes.push((o, s, radius, brush.clone()));
        }
    }

    fn paint_colors(value: f64, theme: Option<&Theme>) -> Vec<Color> {
        let mut w = widget(value);
        let mut rec = TrackRecorder::default();
        let mut ctx = match theme {
            Some(t) => PaintCtx::new(Point::ZERO, Size::new(200.0, HEIGHT)).with_theme(t),
            None => PaintCtx::new(Point::ZERO, Size::new(200.0, HEIGHT)),
        };
        w.paint(&mut ctx, &mut rec);
        rec.rrects
    }

    #[test]
    fn unthemed_paint_uses_fallback_constants() {
        assert_eq!(paint_colors(0.5, None), vec![TRACK, FILL, THUMB_FILL]);
    }

    #[test]
    fn themed_paint_resolves_the_scheme_s_slider_roles() {
        let theme = Theme::neutral();
        let scheme = theme.scheme();
        assert_eq!(
            paint_colors(0.5, Some(&theme)),
            vec![
                scheme.surface_container_highest,
                scheme.primary,
                scheme.primary
            ],
        );
    }

    #[test]
    fn non_cupertino_and_unthemed_paint_have_no_reflective_treatment() {
        // No draw_shadow/fill_rounded_rect_brush call leaks into the default
        // (or unthemed) path — only a `Cupertino`-tagged theme takes the
        // reflective branch.
        let mut unthemed = widget(0.5);
        let mut rec = TrackRecorder::default();
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(200.0, HEIGHT));
        unthemed.paint(&mut ctx, &mut rec);
        assert_eq!(rec.rrects.len(), 3, "track + fill + thumb, nothing else");
        assert!(rec.shadows.is_empty());
        assert!(rec.brushes.is_empty());

        let theme = Theme::neutral();
        assert_ne!(
            theme.design_language,
            DesignLanguage::Cupertino,
            "the default path under test must not be the Cupertino one"
        );
        let mut themed = widget(0.5);
        let mut rec = TrackRecorder::default();
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(200.0, HEIGHT)).with_theme(&theme);
        themed.paint(&mut ctx, &mut rec);
        assert_eq!(rec.rrects.len(), 3);
        assert!(rec.shadows.is_empty());
        assert!(rec.brushes.is_empty());
    }

    /// A `Cupertino`-tagged theme carrying a translucent `control` glass tier
    /// — the shape a Cupertino design system installs, built inline here
    /// because no design language ships in this crate. The shadow/hairline
    /// values are arbitrary-but-distinctive: the branch under test reads them
    /// straight off the theme, so what matters is that the assertions below
    /// track THESE numbers rather than a hardcoded recipe.
    fn cupertino_theme() -> Theme {
        Theme::builder(Theme::neutral())
            .design_language(DesignLanguage::Cupertino)
            .map_glass(|mut g| {
                g.control = GlassMaterial {
                    blur_radius_intent: 15.0,
                    fills_light: Vec::new(),
                    fills_dark: Vec::new(),
                    hairline_alpha: 0.3,
                    shadow: frust_theme::ShadowSpec {
                        y_offset: 2.0,
                        blur_std_dev: 4.0,
                        color_alpha: 0.12,
                    },
                };
                g
            })
            .build()
    }

    #[test]
    fn cupertino_themed_paint_uses_the_larger_reflective_knob() {
        let theme = cupertino_theme();
        assert_eq!(theme.design_language, DesignLanguage::Cupertino);
        let mut w = widget(0.5);
        let mut rec = TrackRecorder::default();
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(200.0, HEIGHT)).with_theme(&theme);
        w.paint(&mut ctx, &mut rec);

        // track + fill + knob base fill (white, unlike the Material path's
        // tinted `THUMB_FILL`).
        assert_eq!(rec.rrects.len(), 3);
        assert_eq!(rec.rrects[2], CUPERTINO_THUMB_FILL);

        assert_eq!(rec.shadows.len(), 1, "one drop shadow under the knob");
        let expected = theme.glass.control.shadow;
        assert_eq!(
            rec.shadows[0].2,
            CUPERTINO_THUMB / 2.0,
            "circular, knob radius"
        );
        assert_eq!(rec.shadows[0].3, expected.blur_std_dev);

        assert_eq!(rec.brushes.len(), 1, "one specular gradient highlight");
        assert_eq!(
            rec.brushes[0].2,
            CUPERTINO_THUMB / 2.0,
            "circular, knob radius"
        );
        match &rec.brushes[0].3 {
            Brush::Gradient(g) => assert_eq!(g.stops.len(), 2, "peak + fade-to-transparent"),
            _ => panic!("expected a gradient brush for the specular highlight"),
        }
    }

    #[test]
    fn rebuild_adopts_new_value_without_self_mutation() {
        let mut counter = 0u64;
        let prev = slider::<Val, _>(0.2, |_s, _v| {});
        let mut w = View::<Val>::build(&prev, &mut BuildCtx::new(&mut counter));
        assert_eq!(w.value, 0.2);
        let next = slider::<Val, _>(0.8, |_s, _v| {});
        View::<Val>::rebuild(&next, &prev, &mut w, &mut BuildCtx::new(&mut counter));
        assert_eq!(w.value, 0.8);
    }

    mod keyboard {
        use super::*;
        use frust_core::{DiscardScene, FrameTime, RenderRoot};

        fn key(named: NamedKey, repeat: bool) -> InputEvent {
            InputEvent::Key(KeyEvent {
                key: Key::Named(named),
                modifiers: Modifiers::default(),
                repeat,
            })
        }

        #[test]
        fn a_press_keeps_focus_so_the_next_tab_moves_to_the_next_stop() {
            let mut logic = |s: &mut Val| {
                crate::column()
                    .child(slider(0.5, |s: &mut Val, _| s.changes += 1))
                    .child(slider(s.value, |s: &mut Val, _| s.changes += 10))
            };
            let mut root: RenderRoot<Val, crate::FlexView<Val>> = RenderRoot::new();
            let mut state = Val {
                value: 0.5,
                changes: 0,
            };
            root.rebuild(&mut logic, &mut state);
            root.layout(Size::new(200.0, 100.0));
            root.paint(&mut DiscardScene, FrameTime::ZERO);
            root.event(&mut state, &ev(PointerPhase::Down, 50.0));
            root.event(&mut state, &ev(PointerPhase::Up, 50.0));
            assert_eq!(state.changes, 1);
            root.event(&mut state, &key(NamedKey::Tab, false));
            root.event(&mut state, &key(NamedKey::ArrowRight, false));
            assert_eq!(state.changes, 11, "Tab went to the second slider");
        }

        #[test]
        fn a_touch_tap_changes_the_value_without_claiming_focus() {
            let mut logic = |s: &mut Val| {
                crate::column().child(slider(s.value, |s: &mut Val, _| s.changes += 1))
            };
            let mut root: RenderRoot<Val, crate::FlexView<Val>> = RenderRoot::new();
            let mut state = Val {
                value: 0.5,
                changes: 0,
            };
            root.rebuild(&mut logic, &mut state);
            root.layout(Size::new(200.0, 100.0));
            root.paint(&mut DiscardScene, FrameTime::ZERO);
            for phase in [PointerPhase::Down, PointerPhase::Up] {
                let InputEvent::Pointer(event) = ev(phase, 50.0) else {
                    unreachable!()
                };
                let contact = InputEvent::PointerContact {
                    pointer_id: frust_core::event::PointerId::touch(0),
                    event,
                };
                root.event(&mut state, &contact);
            }
            assert_eq!(state.changes, 1);
            assert!(!root.is_focus_active(), "a tap leaves focus alone");
        }

        #[test]
        fn tab_focuses_the_slider_then_arrows_step_it() {
            assert!(widget(0.5).is_focusable());
            let mut logic = |s: &mut Val| {
                crate::column().child(slider(s.value, |s: &mut Val, v: f64| {
                    s.value = v;
                    s.changes += 1;
                }))
            };
            let mut root: RenderRoot<Val, crate::FlexView<Val>> = RenderRoot::new();
            let mut state = Val {
                value: 0.5,
                changes: 0,
            };
            let mut frame = |root: &mut RenderRoot<Val, _>, state: &mut Val| {
                root.rebuild(&mut logic, state);
                root.layout(Size::new(200.0, 100.0));
                root.paint(&mut DiscardScene, FrameTime::ZERO);
            };
            frame(&mut root, &mut state);
            root.event(&mut state, &key(NamedKey::ArrowRight, false));
            assert_eq!(state.changes, 0, "an unfocused slider takes no keys");

            root.event(&mut state, &key(NamedKey::Tab, false));
            assert!(root.is_focus_active());
            assert!(
                root.event(&mut state, &key(NamedKey::ArrowRight, false))
                    .handled
            );
            assert!((state.value - 0.55).abs() < 1e-9);
            frame(&mut root, &mut state);
            root.event(&mut state, &key(NamedKey::ArrowDown, true));
            assert!((state.value - 0.5).abs() < 1e-9, "auto-repeat steps too");
            frame(&mut root, &mut state);
            root.event(&mut state, &key(NamedKey::End, false));
            assert_eq!(state.value, 1.0);
            frame(&mut root, &mut state);
            let changes = state.changes;
            assert!(
                root.event(&mut state, &key(NamedKey::ArrowUp, false))
                    .handled
            );
            assert_eq!(
                state.changes, changes,
                "the end of the track reports nothing"
            );
            root.event(&mut state, &key(NamedKey::Home, false));
            assert_eq!(state.value, 0.0);
        }

        #[test]
        fn chorded_and_other_keys_are_not_navigation() {
            let shift = Modifiers {
                shift: true,
                ..Modifiers::default()
            };
            let chorded = KeyEvent {
                key: Key::Named(NamedKey::ArrowLeft),
                modifiers: shift,
                repeat: false,
            };
            assert_eq!(value_from_key(&chorded, 0.5), None);
            let enter = KeyEvent {
                key: Key::Named(NamedKey::Enter),
                modifiers: Modifiers::default(),
                repeat: false,
            };
            assert_eq!(value_from_key(&enter, 0.5), None);
            let left = KeyEvent {
                key: Key::Named(NamedKey::ArrowLeft),
                ..enter
            };
            assert_eq!(
                value_from_key(&left, 0.02),
                Some(0.0),
                "clamped at the start"
            );
        }
    }
}