taim 0.15.0-rc.2

Taim.rs: a GPU-native, fine-grained reactive GUI framework for Rust, for desktop, mobile and the web. By theaimartco.
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
//! The production component state matrix.
//!
//! `phase.md` Phase 11's component completion contract requires that
//! *every* component define and test its behavior across default, hover,
//! focus-visible, pressed, selected, disabled, loading, error,
//! high-contrast, RTL, large-text, and reduced-motion conditions, and
//! declare its semantics, navigation, touch target, focus ring, adaptive
//! layout, token-only styling, and readability without effects.
//!
//! Rather than 18 near-identical hand-written modules, this drives every
//! component through the whole matrix generically, so a component cannot
//! quietly skip part of the contract and a newly added one is covered the
//! moment it joins [`every_component`].

use taim_design::components::app_bar::{AppBar, AppBarKind};
use taim_design::components::bottom_sheet::{Anchor, BottomSheet};
use taim_design::components::button::{Button, ButtonKind};
use taim_design::components::card::Card;
use taim_design::components::dialog::Dialog;
use taim_design::components::icon_button::IconButton;
use taim_design::components::list_tile::{ListLines, ListTile};
use taim_design::components::menu::Menu;
use taim_design::components::navigation::{Navigation, NavigationMode};
use taim_design::components::notification::{Notification, Privacy};
use taim_design::components::progress::Progress;
use taim_design::components::selection::{Selection, SelectionKind};
use taim_design::components::slider::Slider;
use taim_design::components::text_field::TextField;
use taim_design::components::toast::Toast;
use taim_design::components::tooltip::{Tooltip, Trigger};
use taim_design::components::window_chrome::WindowChrome;
use taim_design::components::*;

use taim_design::icon::Icon;
use taim_design::state::Interaction;
use taim_design::theme::Theme;
use taim_design::tokens::{Contrast, Scheme};

use taim_core::Size;
use taim_core::semantics::{Actions, Role};

const EVERY_SCHEME: [Scheme; 3] = [Scheme::Light, Scheme::Dark, Scheme::HighContrast];

/// Every component in its ordinary, enabled configuration, paired with a
/// name for failure messages. Variants that change the contract
/// (disabled, static, secure) get their own cases below.
fn every_component() -> Vec<(&'static str, Box<dyn ComponentSpec>)> {
    vec![
        (
            "app_bar",
            Box::new(AppBar {
                kind: AppBarKind::Standard,
                navigation_action: true,
            }),
        ),
        (
            "bottom_sheet",
            Box::new(BottomSheet {
                expanded: 0.5,
                dismissible: true,
            }),
        ),
        (
            "button",
            Box::new(Button {
                kind: ButtonKind::Filled,
                loading: false,
                disabled: false,
            }),
        ),
        (
            "card",
            Box::new(Card {
                interactive: true,
                selected: false,
            }),
        ),
        (
            "dialog",
            Box::new(Dialog {
                dismissible: true,
                focus_trapped: true,
            }),
        ),
        (
            "icon_button",
            Box::new(IconButton {
                icon: Icon::new("close", 24, false),
                tooltip: Some("Close"),
                disabled: false,
            }),
        ),
        (
            "list_tile",
            Box::new(ListTile {
                lines: ListLines::Two,
                interactive: true,
            }),
        ),
        (
            "menu",
            Box::new(Menu {
                expanded: false,
                has_submenu: true,
            }),
        ),
        (
            "navigation",
            Box::new(Navigation {
                mode: NavigationMode::Rail,
                selected: false,
            }),
        ),
        (
            "notification",
            Box::new(Notification {
                privacy: Privacy::Public,
                actionable: true,
                group_count: 1,
            }),
        ),
        (
            "progress",
            Box::new(Progress {
                value: Some(0.4),
                circular: false,
            }),
        ),
        (
            "selection",
            Box::new(Selection {
                kind: SelectionKind::Checkbox,
                checked: false,
                disabled: false,
            }),
        ),
        (
            "slider",
            Box::new(Slider {
                value: 0.5,
                range: (0.0, 1.0),
                rtl: false,
                disabled: false,
            }),
        ),
        (
            "text_field",
            Box::new(TextField {
                secure: false,
                multiline: false,
                error: false,
                disabled: false,
            }),
        ),
        (
            "toast",
            Box::new(Toast {
                actionable: true,
                dismissible: true,
            }),
        ),
        (
            "tooltip",
            Box::new(Tooltip {
                focus_enabled: true,
                long_press_enabled: true,
            }),
        ),
        (
            "window_chrome",
            Box::new(WindowChrome {
                desktop: true,
                system_gestures_reserved: true,
            }),
        ),
        (
            "glass_card",
            Box::new(glass_card::GlassCard {
                interactive: true,
                selected: false,
                thickness_mm: 4.0,
                roughness: 0.15,
                transmission: 0.85,
                ior: 1.52,
            }),
        ),
        (
            "segmented_control",
            Box::new(segmented_control::SegmentedControl {
                segments: 3,
                selected_index: 0,
                interactive: true,
            }),
        ),
        (
            "gauge",
            Box::new(gauge::Gauge {
                value: 0.75,
                interactive: true,
            }),
        ),
        (
            "shimmer",
            Box::new(shimmer::Shimmer {
                active: true,
                phase: 0.25,
            }),
        ),
    ]
}

/// Every interaction the matrix sweeps, named for failure messages.
fn every_interaction() -> Vec<(&'static str, Interaction)> {
    vec![
        ("default", Interaction::default()),
        (
            "hover",
            Interaction {
                hovered: true,
                ..Interaction::default()
            },
        ),
        (
            "focus_visible",
            Interaction {
                focus_visible: true,
                ..Interaction::default()
            },
        ),
        (
            "pressed",
            Interaction {
                pressed: true,
                ..Interaction::default()
            },
        ),
        (
            "selected",
            Interaction {
                selected: true,
                ..Interaction::default()
            },
        ),
        (
            "disabled",
            Interaction {
                disabled: true,
                ..Interaction::default()
            },
        ),
        (
            "loading",
            Interaction {
                loading: true,
                ..Interaction::default()
            },
        ),
        (
            "error",
            Interaction {
                error: true,
                ..Interaction::default()
            },
        ),
    ]
}

// ---------------------------------------------------------------------
// The matrix: every component x every state x every theme
// ---------------------------------------------------------------------

#[test]
fn every_component_resolves_a_usable_appearance_in_every_state_and_theme() {
    for scheme in EVERY_SCHEME {
        let theme = Theme::new(scheme);

        for (name, component) in every_component() {
            for (state, interaction) in every_interaction() {
                let appearance = component.appearance(interaction, &theme);

                assert!(
                    (0.0..=1.0).contains(&appearance.overlay_alpha),
                    "{name}/{state}/{scheme:?}: overlay alpha {} out of range",
                    appearance.overlay_alpha
                );
                assert!(
                    appearance.foreground.a > 0.0,
                    "{name}/{state}/{scheme:?}: a fully transparent foreground is invisible"
                );
            }
        }
    }
}

#[test]
fn a_disabled_component_exposes_no_actions_and_reports_not_enabled() {
    // "Disabled" must be enforced in semantics, not merely painted: an
    // inert control still advertising ACTIVATE is a trap for assistive
    // technology.
    let disabled: Vec<(&str, Box<dyn ComponentSpec>)> = vec![
        (
            "button",
            Box::new(Button {
                kind: ButtonKind::Filled,
                loading: false,
                disabled: true,
            }),
        ),
        (
            "icon_button",
            Box::new(IconButton {
                icon: Icon::new("close", 24, false),
                tooltip: Some("Close"),
                disabled: true,
            }),
        ),
        (
            "selection",
            Box::new(Selection {
                kind: SelectionKind::Checkbox,
                checked: false,
                disabled: true,
            }),
        ),
        (
            "slider",
            Box::new(Slider {
                value: 0.5,
                range: (0.0, 1.0),
                rtl: false,
                disabled: true,
            }),
        ),
        (
            "text_field",
            Box::new(TextField {
                secure: false,
                multiline: false,
                error: false,
                disabled: true,
            }),
        ),
    ];

    let theme = Theme::default();

    for (name, component) in disabled {
        assert!(
            component.actions().is_empty(),
            "{name}: a disabled component must expose no actions"
        );
        assert!(
            !component.is_interactive(),
            "{name}: a disabled component must not report as interactive"
        );

        let appearance = component.appearance(
            Interaction {
                disabled: true,
                ..Interaction::default()
            },
            &theme,
        );
        assert!(
            !appearance.enabled,
            "{name}: appearance must report disabled"
        );
    }
}

#[test]
fn every_focusable_component_shows_a_focus_ring_only_when_focus_is_visible() {
    // A focusable control with no visible focus indicator is unusable by
    // keyboard. Non-negotiable in every theme.
    for scheme in EVERY_SCHEME {
        let theme = Theme::new(scheme);

        for (name, component) in every_component() {
            if !component.is_focusable() {
                continue;
            }

            let focused = component.appearance(
                Interaction {
                    focus_visible: true,
                    ..Interaction::default()
                },
                &theme,
            );

            let ring = focused.focus_ring.unwrap_or_else(|| {
                panic!("{name}/{scheme:?}: a focusable component must show a focus ring")
            });

            assert!(
                ring.width > 0.0,
                "{name}: a zero-width focus ring is invisible"
            );
            assert_eq!(
                ring.color,
                theme.colors().focus,
                "{name}: the focus ring must use the theme's focus token"
            );

            let unfocused = component.appearance(Interaction::default(), &theme);
            assert!(
                unfocused.focus_ring.is_none(),
                "{name}: a focus ring must only appear when focus is visible"
            );
        }
    }
}

#[test]
fn every_interactive_component_meets_the_minimum_touch_target() {
    for (name, component) in every_component() {
        if !component.is_interactive() {
            continue;
        }

        for density in Density::ALL {
            let size = component.min_size(density);

            // A container whose width is imposed by the window reports 0
            // and is exempt on that axis; its height must still qualify.
            if size.width > 0.0 {
                assert!(
                    size.width >= MIN_TOUCH_TARGET,
                    "{name}/{density:?}: width {} is below the {MIN_TOUCH_TARGET}px touch target",
                    size.width
                );
            }
            assert!(
                size.height >= MIN_TOUCH_TARGET,
                "{name}/{density:?}: height {} is below the {MIN_TOUCH_TARGET}px touch target",
                size.height
            );
        }
    }
}

#[test]
fn every_interactive_component_accepts_every_input_method() {
    // A pointer-only control excludes touch and keyboard users outright.
    for (name, component) in every_component() {
        if !component.is_interactive() {
            continue;
        }

        let inputs = component.input_methods();

        for required in [
            InputMethods::KEYBOARD,
            InputMethods::POINTER,
            InputMethods::TOUCH,
            InputMethods::GAMEPAD,
        ] {
            assert!(
                inputs.contains(required),
                "{name}: interactive components must accept {required:?}"
            );
        }
    }
}

#[test]
fn a_non_interactive_component_declares_no_inputs_and_takes_no_focus() {
    let inert: Vec<(&str, Box<dyn ComponentSpec>)> = vec![
        (
            "app_bar",
            Box::new(AppBar {
                kind: AppBarKind::Standard,
                navigation_action: true,
            }),
        ),
        (
            "progress",
            Box::new(Progress {
                value: None,
                circular: true,
            }),
        ),
        (
            "tooltip",
            Box::new(Tooltip {
                focus_enabled: true,
                long_press_enabled: true,
            }),
        ),
        (
            "window_chrome",
            Box::new(WindowChrome {
                desktop: false,
                system_gestures_reserved: true,
            }),
        ),
        (
            "card(static)",
            Box::new(Card {
                interactive: false,
                selected: false,
            }),
        ),
        (
            "list_tile(static)",
            Box::new(ListTile {
                lines: ListLines::One,
                interactive: false,
            }),
        ),
    ];

    for (name, component) in inert {
        assert!(
            !component.is_interactive(),
            "{name}: expected a non-interactive component"
        );
        assert!(
            component.input_methods().is_empty(),
            "{name}: a non-interactive component must declare no input methods"
        );
        assert!(
            !component.is_focusable(),
            "{name}: a non-interactive component must not be focusable"
        );
    }
}

#[test]
fn every_component_supports_rtl_large_text_and_reads_without_effects() {
    for (name, component) in every_component() {
        assert!(component.supports_rtl(), "{name}: must lay out mirrored");
        assert!(
            component.supports_large_text(),
            "{name}: must reflow for enlarged text"
        );
        assert!(
            component.readable_without_effects(),
            "{name}: must read with blur/shadow/noise disabled (Recovery tier)"
        );
    }
}

#[test]
fn every_component_declares_a_token_only_adaptive_layout() {
    use taim_design::tokens::Spacing;

    // "Theme tokens only -- no unexplained hard-coded spacing values":
    // every padding/gap must literally be a value from the scale.
    let scale = [
        Spacing::XS,
        Spacing::SM,
        Spacing::MD,
        Spacing::LG,
        Spacing::XL,
        Spacing::XXL,
    ];

    for (name, component) in every_component() {
        for viewport in ViewportClass::ALL {
            for density in Density::ALL {
                let layout = component.layout(viewport, density);

                assert!(
                    scale.contains(&layout.padding),
                    "{name}/{viewport:?}: padding {} is not a spacing token",
                    layout.padding
                );
                assert!(
                    scale.contains(&layout.gap),
                    "{name}/{viewport:?}: gap {} is not a spacing token",
                    layout.gap
                );
                assert_eq!(
                    layout.min_size,
                    component.min_size(density),
                    "{name}: layout min_size must agree with min_size()"
                );
            }
        }
    }
}

#[test]
fn a_component_only_claims_states_it_can_honor() {
    // Declaring DISABLED means actually going inert.
    let button = Button {
        kind: ButtonKind::Filled,
        loading: false,
        disabled: true,
    };
    assert!(button.supported_states().contains(StateSupport::DISABLED));
    assert!(button.actions().is_empty());

    // Declaring SELECTED means the appearance actually changes: a state
    // nobody can see is not a state.
    let theme = Theme::default();
    let selection = Selection {
        kind: SelectionKind::Checkbox,
        checked: true,
        disabled: false,
    };
    assert!(
        selection
            .supported_states()
            .contains(StateSupport::SELECTED)
    );

    let unselected = selection.appearance(Interaction::default(), &theme);
    let selected = selection.appearance(
        Interaction {
            selected: true,
            ..Interaction::default()
        },
        &theme,
    );
    assert_ne!(
        unselected.background, selected.background,
        "a component claiming SELECTED must look different when selected"
    );
}

#[test]
fn hover_and_press_produce_distinct_increasing_state_layers() {
    // The state layer is what makes a control feel alive; press must read
    // as stronger than hover, or the feedback is ambiguous.
    let theme = Theme::default();
    let button = Button::default();

    let rest = button.appearance(Interaction::default(), &theme);
    let hover = button.appearance(
        Interaction {
            hovered: true,
            ..Interaction::default()
        },
        &theme,
    );
    let pressed = button.appearance(
        Interaction {
            pressed: true,
            ..Interaction::default()
        },
        &theme,
    );

    assert!(rest.overlay_alpha < hover.overlay_alpha);
    assert!(hover.overlay_alpha < pressed.overlay_alpha);
}

// ---------------------------------------------------------------------
// Contrast: readability in every theme
// ---------------------------------------------------------------------

#[test]
fn every_components_foreground_is_readable_against_what_it_sits_on() {
    // The design system's central promise -- beauty from typography,
    // hierarchy, and colour -- is worthless if the text cannot be read.
    //
    // A component that paints its own fill is checked against that fill.
    // One that does not still has to be legible against the surface it
    // will actually sit on, so it is checked against the theme's surface
    // token rather than skipped -- otherwise this test would only cover
    // the three components that happen to draw a background.
    let mut checked = 0;

    for scheme in EVERY_SCHEME {
        let theme = Theme::new(scheme);

        for (name, component) in every_component() {
            for (state, interaction) in every_interaction() {
                let appearance = component.appearance(interaction, &theme);

                // A disabled control is deliberately dimmed by its state
                // layer; body contrast is not the right bar for it.
                if interaction.disabled {
                    continue;
                }

                let background = appearance.background.unwrap_or(theme.colors().surface);

                assert!(
                    Contrast::body_text(appearance.foreground, background),
                    "{name}/{state}/{scheme:?}: foreground fails body contrast against its \
                     background (ratio {:.2})",
                    Contrast::ratio(appearance.foreground, background)
                );
                checked += 1;
            }
        }
    }

    // Guard against a vacuous pass: if the skip rules ever swallow every
    // case, this test must fail rather than silently assert nothing.
    assert!(
        checked >= EVERY_SCHEME.len() * every_component().len(),
        "contrast sweep only checked {checked} cases -- it is not covering the matrix"
    );
}

#[test]
fn the_matrix_actually_covers_focusable_and_interactive_components() {
    // These sweeps skip components the rule does not apply to. If a
    // refactor ever made *everything* skippable, the sweeps above would
    // pass while checking nothing. Pin the coverage so that cannot happen
    // silently.
    let components = every_component();

    let focusable = components.iter().filter(|(_, c)| c.is_focusable()).count();
    let interactive = components
        .iter()
        .filter(|(_, c)| c.is_interactive())
        .count();

    assert!(
        focusable >= 8,
        "only {focusable} focusable components -- the focus-ring sweep has lost coverage"
    );
    assert!(
        interactive >= 10,
        "only {interactive} interactive components -- the touch-target and input sweeps have lost coverage"
    );
    assert!(
        components.len() >= 17,
        "the matrix is missing components: only {} registered",
        components.len()
    );
}

// ---------------------------------------------------------------------
// Component-specific contracts
// ---------------------------------------------------------------------

#[test]
fn a_secure_field_reports_the_secure_role_in_every_configuration() {
    for multiline in [false, true] {
        for error in [false, true] {
            for disabled in [false, true] {
                let field = TextField {
                    secure: true,
                    multiline,
                    error,
                    disabled,
                };
                assert_eq!(
                    field.role(),
                    Role::SecureField,
                    "a secure field must never downgrade to a plain TextField"
                );
            }
        }
    }
}

#[test]
fn a_modal_dialog_traps_focus_and_can_be_dismissed_from_every_input() {
    let dialog = Dialog {
        dismissible: true,
        focus_trapped: true,
    };

    assert!(dialog.actions().contains(Actions::DISMISS));
    assert!(dialog.traps_focus_correctly());
    assert_eq!(dialog.input_methods(), InputMethods::ALL);
}

#[test]
fn a_loading_button_stays_focusable_but_cannot_be_activated() {
    let loading = Button {
        kind: ButtonKind::Filled,
        loading: true,
        disabled: false,
    };

    assert!(
        loading.actions().contains(Actions::FOCUS),
        "a busy button must not eject a keyboard user"
    );
    assert!(
        !loading.actions().contains(Actions::ACTIVATE),
        "a busy button must not accept a second activation"
    );

    let appearance = loading.appearance(
        Interaction {
            loading: true,
            ..Interaction::default()
        },
        &Theme::default(),
    );
    assert!(appearance.busy);
}

#[test]
fn a_slider_mirrors_its_direction_in_rtl() {
    let ltr = Slider {
        value: 0.25,
        range: (0.0, 1.0),
        rtl: false,
        disabled: false,
    };
    let rtl = Slider { rtl: true, ..ltr };

    assert!((ltr.normalized() - 0.25).abs() < f32::EPSILON);
    assert!(
        (rtl.normalized() - 0.75).abs() < f32::EPSILON,
        "an RTL slider's maximum sits at the left"
    );
}

#[test]
fn a_slider_clamps_out_of_range_values_and_survives_a_degenerate_range() {
    let over = Slider {
        value: 99.0,
        range: (0.0, 1.0),
        rtl: false,
        disabled: false,
    };
    assert_eq!(over.normalized(), 1.0);

    let degenerate = Slider {
        value: 5.0,
        range: (3.0, 3.0),
        rtl: false,
        disabled: false,
    };
    assert_eq!(
        degenerate.normalized(),
        0.0,
        "a zero-width range must not divide by zero"
    );
}

#[test]
fn navigation_adapts_its_mode_to_the_viewport() {
    assert_eq!(
        Navigation::for_viewport(ViewportClass::Compact).mode,
        NavigationMode::Bar
    );
    assert_eq!(
        Navigation::for_viewport(ViewportClass::Medium).mode,
        NavigationMode::Rail
    );
    assert_eq!(
        Navigation::for_viewport(ViewportClass::Expanded).mode,
        NavigationMode::Sidebar
    );

    // Only a sidebar has room for a label beside the icon.
    assert!(Navigation::for_viewport(ViewportClass::Expanded).shows_label());
    assert!(!Navigation::for_viewport(ViewportClass::Compact).shows_label());
}

#[test]
fn a_bottom_sheet_snaps_to_the_nearest_anchor_and_never_dismisses_when_forbidden() {
    let dismissible = |expanded| BottomSheet {
        expanded,
        dismissible: true,
    };

    assert_eq!(dismissible(0.05).snap_target(), Anchor::Closed);
    assert_eq!(dismissible(0.45).snap_target(), Anchor::Half);
    assert_eq!(dismissible(0.95).snap_target(), Anchor::Full);

    // A non-dismissible sheet dragged to nearly closed must still settle
    // open -- a drag cannot dismiss what the caller said cannot be.
    let stubborn = BottomSheet {
        expanded: 0.0,
        dismissible: false,
    };
    assert_eq!(stubborn.snap_target(), Anchor::Half);
}

#[test]
fn notification_privacy_withholds_content_on_a_locked_screen() {
    assert!(Privacy::Public.shows_body(true));
    assert!(!Privacy::Sensitive.shows_body(true));
    assert!(Privacy::Sensitive.shows_title(true));
    assert!(!Privacy::Secret.shows_title(true));

    // Unlocked, every level shows everything.
    for privacy in Privacy::ALL {
        assert!(privacy.shows_title(false));
        assert!(privacy.shows_body(false));
    }
}

#[test]
fn an_actionable_toast_stays_visible_long_enough_to_reach_its_action() {
    let plain = Toast {
        actionable: false,
        dismissible: true,
    };
    let actionable = Toast {
        actionable: true,
        dismissible: true,
    };

    assert!(
        actionable.visible_duration() > plain.visible_duration(),
        "a toast with an action needs longer than one without"
    );
    assert!(actionable.announces_as_live_region());
}

#[test]
fn an_icon_only_button_requires_an_accessible_name() {
    let named = IconButton {
        icon: Icon::new("close", 24, false),
        tooltip: Some("Close"),
        disabled: false,
    };
    let unnamed = IconButton {
        tooltip: None,
        ..named
    };
    let blank = IconButton {
        tooltip: Some("   "),
        ..named
    };

    assert!(named.has_accessible_name());
    assert!(!unnamed.has_accessible_name());
    assert!(!blank.has_accessible_name(), "whitespace is not a name");
}

#[test]
fn a_tooltip_carrying_information_is_reachable_without_a_pointer() {
    let pointer_only = Tooltip {
        focus_enabled: false,
        long_press_enabled: false,
    };
    let reachable = Tooltip {
        focus_enabled: true,
        long_press_enabled: true,
    };

    assert!(!pointer_only.reachable_without_pointer());
    assert!(reachable.reachable_without_pointer());

    assert!(reachable.responds_to(Trigger::Focus));
    assert!(reachable.responds_to(Trigger::LongPress));
    assert!(pointer_only.responds_to(Trigger::Hover));
    assert!(!pointer_only.responds_to(Trigger::Focus));
}

#[test]
fn window_chrome_reserves_the_system_gesture_band() {
    let reserved = WindowChrome {
        desktop: false,
        system_gestures_reserved: true,
    };
    let unreserved = WindowChrome {
        desktop: true,
        system_gestures_reserved: false,
    };

    // An app control must not own a drag starting inside the reserved
    // band; the system's SYSTEM-priority edge_swipe wins there by policy.
    assert!(!reserved.may_own_drag_at(0.0));
    assert!(!reserved.may_own_drag_at(10.0));
    assert!(reserved.may_own_drag_at(40.0));

    // With nothing reserved, the app owns its whole surface.
    assert!(unreserved.may_own_drag_at(0.0));
}

#[test]
fn a_collapsing_app_bar_shrinks_and_others_do_not() {
    let collapsing = AppBar {
        kind: AppBarKind::Collapsing,
        navigation_action: true,
    };
    let standard = AppBar {
        kind: AppBarKind::Standard,
        navigation_action: false,
    };

    assert!(collapsing.height(0.0) > collapsing.height(1.0));
    assert_eq!(standard.height(0.0), standard.height(1.0));

    // Progress outside 0..=1 clamps rather than inverting the bar.
    assert_eq!(collapsing.height(-5.0), collapsing.height(0.0));
    assert_eq!(collapsing.height(5.0), collapsing.height(1.0));
}

#[test]
fn progress_clamps_its_fraction_and_substitutes_reduced_motion() {
    use taim_motion::{Effect, MotionPolicy};

    let determinate = Progress {
        value: Some(2.0),
        circular: false,
    };
    assert_eq!(determinate.fraction(), Some(1.0));
    assert!(!determinate.is_indeterminate());

    let indeterminate = Progress {
        value: None,
        circular: true,
    };
    assert!(indeterminate.is_indeterminate());

    // Reduced motion substitutes a fade for the spin rather than freezing
    // the indicator, which would read as "stalled".
    assert_eq!(
        indeterminate.respects_reduced_motion(MotionPolicy::Reduced),
        Effect::Fade
    );
    assert_eq!(
        indeterminate.respects_reduced_motion(MotionPolicy::Full),
        Effect::Transform
    );
}

#[test]
fn menu_typeahead_matches_prefixes_case_insensitively() {
    assert!(Menu::matches_typeahead("Save As...", "sa"));
    assert!(Menu::matches_typeahead("Save As...", "SAVE"));
    assert!(!Menu::matches_typeahead("Save As...", "as"));
    assert!(
        !Menu::matches_typeahead("Save As...", "   "),
        "an empty query must not jump the selection"
    );
}

/// The touch-target floor is a *policy*, and a policy that two crates
/// state independently is a policy that will eventually disagree with
/// itself. `phase.md` sets 48px; `taim-design` and the widgets must both
/// mean that same 48px, and the compatibility floor must stay an
/// explicit, separately-named opt-out rather than a second default.
#[test]
fn the_touch_target_policy_has_exactly_one_source() {
    assert_eq!(
        MIN_TOUCH_TARGET,
        taim_core::touch::MIN_TARGET,
        "taim-design must re-export the core constant, not restate it"
    );
    assert_eq!(
        MIN_TOUCH_TARGET, 48.0,
        "phase.md's default target is 48x48 logical pixels"
    );

    assert_eq!(
        MIN_TOUCH_TARGET_COMPATIBILITY,
        taim_core::touch::MIN_TARGET_COMPATIBILITY
    );
    const {
        assert!(
            MIN_TOUCH_TARGET_COMPATIBILITY < MIN_TOUCH_TARGET,
            "the compatibility floor only makes sense as a relaxation"
        );
    }

    assert_eq!(TouchTargetPolicy::default(), TouchTargetPolicy::Vyom);
    assert_eq!(TouchTargetPolicy::Vyom.min_edge(), MIN_TOUCH_TARGET);
    assert_eq!(
        TouchTargetPolicy::PlatformCompatibility.min_edge(),
        MIN_TOUCH_TARGET_COMPATIBILITY
    );
}

/// A target that is tall enough but too narrow is still a miss. Both
/// axes are checked, on both policies.
#[test]
fn touch_target_policies_check_both_axes() {
    for policy in TouchTargetPolicy::ALL {
        let edge = policy.min_edge();

        assert!(policy.is_satisfied_by(Size::new(edge, edge)));
        assert!(!policy.is_satisfied_by(Size::new(edge - 0.01, edge)));
        assert!(!policy.is_satisfied_by(Size::new(edge, edge - 0.01)));
    }
}

/// Every component that accepts input must clear the *default* policy at
/// every density -- the compatibility floor is not a licence to ship a
/// smaller control.
///
/// The policy governs **touch targets**, and only a component that
/// accepts input presents one. A pure container declares no actions and
/// takes at least one axis from its parent -- `app_bar` is the case in
/// point: it is a `Role::Group` with `Actions::empty()` whose width is
/// imposed by the window, so it has no intrinsic target to measure.
/// Skipping it here is not a relaxation of the policy, because the
/// controls it *hosts* (an `IconButton` in its navigation slot) are
/// separate specs that are checked on their own. The companion test
/// below pins the exempt set so this cannot quietly grow.
#[test]
fn every_component_clears_the_default_policy_at_every_density() {
    for (name, spec) in every_component() {
        if !spec.is_interactive() {
            continue;
        }

        for density in Density::ALL {
            let size = spec.min_size(density);

            assert!(
                TouchTargetPolicy::Vyom.is_satisfied_by(size),
                "{name}/{density:?}: {size:?} is below the {MIN_TOUCH_TARGET}px default policy"
            );
        }
    }
}

/// The exemption above is only sound while "non-interactive" stays a
/// deliberate property of a small, known set of containers.
///
/// Without this test, a real control that lost its actions -- through a
/// refactor, a wrong `disabled` default, a typo in `actions()` -- would
/// silently drop out of touch-target coverage instead of failing. Pinning
/// the set means that regression shows up here as an unexpected name.
#[test]
fn only_known_containers_are_exempt_from_the_touch_target_policy() {
    let exempt: Vec<&'static str> = every_component()
        .into_iter()
        .filter(|(_, spec)| !spec.is_interactive())
        .map(|(name, _)| name)
        .collect();

    // Each of these is presentation, not control: `app_bar` and
    // `window_chrome` are containers whose buttons are separate
    // `IconButton` specs, and `progress` and `tooltip` report status
    // without ever accepting input.
    assert_eq!(
        exempt,
        ["app_bar", "progress", "tooltip", "window_chrome", "shimmer"],
        "the set of components exempt from the touch-target policy changed; \
         a container may join it deliberately, but a control appearing here \
         means it stopped declaring actions"
    );
}