bevy_pf 0.2.3

A XAML / WPF-like UI framework for Bevy: XAML in macros or files, styling with resources, and the common WPF control set.
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
//! `{AppThemeBinding}` end to end, against MAUI's semantics.
//!
//! The unit tests in `src/app_theme.rs` pin the pick rules in isolation;
//! these pin that the rules actually reach a painted entity, survive a theme
//! flip without re-instantiation, and behave at each placement (attribute,
//! style setter, trigger setter).

use bevy::asset::AssetPlugin;
use bevy::prelude::*;
use bevy_pf::prelude::*;
use bevy_pf::{XamlEnv, instantiate_document_env};

fn test_app() -> App {
    let mut app = App::new();
    app.add_plugins((MinimalPlugins, AssetPlugin::default()));
    app.add_plugins(PfUiPlugin);
    app
}

fn spawn(app: &mut App, xaml: &str) -> (Entity, Vec<String>) {
    let doc = bevy_pf_xaml::parse(xaml).expect("parses");
    let world = app.world_mut();
    let root = world.spawn_empty().id();
    let result = instantiate_document_env(world, root, &doc, &XamlEnv::default()).expect("builds");
    (root, result.warnings)
}

fn named(app: &App, root: Entity, name: &str) -> Entity {
    app.world()
        .get::<XamlNames>(root)
        .unwrap()
        .get(name)
        .unwrap()
}

/// The painted background, or `None` when the property is unset/cleared.
fn background(app: &App, entity: Entity) -> Option<String> {
    app.world()
        .get::<BackgroundColor>(entity)
        .map(|c| bevy_pf::instantiate::color_to_hex(c.0))
}

fn page(background_value: &str) -> String {
    format!(
        r##"<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
     <Border x:Name="B" Background="{background_value}"/>
   </StackPanel>"##
    )
}

/// Build under `theme` and return the resulting background.
fn under(theme: AppTheme, background_value: &str) -> (Option<String>, Vec<String>) {
    let mut app = test_app();
    set_user_app_theme(app.world_mut(), theme);
    let (root, warnings) = spawn(&mut app, &page(background_value));
    app.update();
    (background(&app, named(&app, root, "B")), warnings)
}

// ---------------------------------------------------------------------
// The pick rules, reaching a painted entity.
// ---------------------------------------------------------------------

#[test]
fn each_theme_takes_its_own_arm() {
    let markup = "{AppThemeBinding Light=#FF0000, Dark=#0000FF}";
    assert_eq!(under(AppTheme::Light, markup).0, Some("#FF0000".into()));
    assert_eq!(under(AppTheme::Dark, markup).0, Some("#0000FF".into()));
}

#[test]
fn unspecified_resolves_as_light() {
    // MAUI's switch has no Unspecified case — it shares Light's `_` arm.
    // Getting this wrong would silently give every un-themed app the DARK
    // palette, or no value at all.
    let (color, warnings) = under(
        AppTheme::Unspecified,
        "{AppThemeBinding Light=#FF0000, Dark=#0000FF}",
    );
    assert_eq!(warnings, Vec::<String>::new());
    assert_eq!(color, Some("#FF0000".into()));
}

#[test]
fn a_missing_arm_falls_back_to_default_only() {
    // Dark is absent, so Dark takes Default — NOT Light.
    assert_eq!(
        under(
            AppTheme::Dark,
            "{AppThemeBinding Light=#FF0000, Default=#00FF00}"
        )
        .0,
        Some("#00FF00".into())
    );
    // ...and symmetrically.
    assert_eq!(
        under(
            AppTheme::Light,
            "{AppThemeBinding Dark=#0000FF, Default=#00FF00}"
        )
        .0,
        Some("#00FF00".into())
    );
}

#[test]
fn a_positional_argument_sets_default() {
    // Default is the extension's ContentProperty in MAUI.
    let markup = "{AppThemeBinding #00FF00}";
    assert_eq!(under(AppTheme::Light, markup).0, Some("#00FF00".into()));
    assert_eq!(under(AppTheme::Dark, markup).0, Some("#00FF00".into()));
}

#[test]
fn no_matching_arm_and_no_default_clears_rather_than_reverting() {
    // The most MAUI-specific behaviour in the feature: MAUI writes NULL to
    // the target, so a style-supplied value underneath does NOT show
    // through. Reverting instead would look reasonable and be wrong.
    let mut app = test_app();
    set_user_app_theme(app.world_mut(), AppTheme::Light);
    let (root, warnings) = spawn(
        &mut app,
        r##"<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
     <StackPanel.Resources>
       <Style x:Key="S" TargetType="Border">
         <Setter Property="Background" Value="#FFFF00"/>
       </Style>
     </StackPanel.Resources>
     <Border x:Name="B" Style="{StaticResource S}"
             Background="{AppThemeBinding Dark=#0000FF}"/>
   </StackPanel>"##,
    );
    app.update();
    assert_eq!(warnings, Vec::<String>::new());
    let painted = background(&app, named(&app, root, "B"));
    assert_ne!(
        painted,
        Some("#FFFF00".into()),
        "must NOT fall back to the style value"
    );
    assert_ne!(
        painted,
        Some("#0000FF".into()),
        "must NOT take the Dark arm under Light"
    );
}

#[test]
fn an_arm_written_as_null_is_supplied_and_stops_the_fallback() {
    // `Light={x:Null}` IS supplied, so Light yields null instead of
    // falling through to Default. "Supplied" is about the markup, not the
    // value.
    let (color, warnings) = under(
        AppTheme::Light,
        "{AppThemeBinding Light={x:Null}, Default=#00FF00}",
    );
    assert_eq!(warnings, Vec::<String>::new());
    assert_ne!(color, Some("#00FF00".into()), "Default must not be reached");
}

// ---------------------------------------------------------------------
// Liveness.
// ---------------------------------------------------------------------

#[test]
fn a_theme_flip_repaints_without_rebuilding() {
    let mut app = test_app();
    set_user_app_theme(app.world_mut(), AppTheme::Light);
    let (root, _) = spawn(
        &mut app,
        &page("{AppThemeBinding Light=#FF0000, Dark=#0000FF}"),
    );
    app.update();
    let border = named(&app, root, "B");
    assert_eq!(background(&app, border), Some("#FF0000".into()));

    set_user_app_theme(app.world_mut(), AppTheme::Dark);
    app.update();
    assert_eq!(
        background(&app, border),
        Some("#0000FF".into()),
        "the SAME entity must repaint — no re-instantiation"
    );
}

#[test]
fn setting_the_theme_already_in_effect_changes_nothing() {
    let mut app = test_app();
    set_user_app_theme(app.world_mut(), AppTheme::Light);
    let generation = app.world().resource::<PfAppTheme>().generation();
    set_user_app_theme(app.world_mut(), AppTheme::Light);
    assert_eq!(
        app.world().resource::<PfAppTheme>().generation(),
        generation,
        "a no-op set must not bump the generation, or every frame would refresh"
    );
}

#[test]
fn a_user_choice_beats_the_platform_and_unspecified_hands_control_back() {
    let mut app = test_app();
    let (root, _) = spawn(
        &mut app,
        &page("{AppThemeBinding Light=#FF0000, Dark=#0000FF}"),
    );
    let border = named(&app, root, "B");

    // Pretend the OS reports dark while the user has asked for light.
    set_user_app_theme(app.world_mut(), AppTheme::Light);
    app.update();
    assert_eq!(background(&app, border), Some("#FF0000".into()));
    assert_eq!(
        app.world().resource::<PfAppTheme>().requested(),
        AppTheme::Light
    );

    set_user_app_theme(app.world_mut(), AppTheme::Dark);
    app.update();
    assert_eq!(background(&app, border), Some("#0000FF".into()));
}

#[test]
fn applying_a_builtin_theme_drives_the_binding() {
    let mut app = test_app();
    let (root, _) = spawn(
        &mut app,
        &page("{AppThemeBinding Light=#FF0000, Dark=#0000FF}"),
    );
    let border = named(&app, root, "B");

    bevy_pf::themes::apply_theme(app.world_mut(), "fluent-dark").unwrap();
    app.update();
    assert_eq!(background(&app, border), Some("#0000FF".into()));

    bevy_pf::themes::apply_theme(app.world_mut(), "fluent-light").unwrap();
    app.update();
    assert_eq!(background(&app, border), Some("#FF0000".into()));
}

// ---------------------------------------------------------------------
// Placements.
// ---------------------------------------------------------------------

#[test]
fn a_style_setter_is_live_and_still_loses_to_a_local_value() {
    let mut app = test_app();
    set_user_app_theme(app.world_mut(), AppTheme::Light);
    let (root, warnings) = spawn(
        &mut app,
        r##"<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
     <StackPanel.Resources>
       <Style x:Key="S" TargetType="Border">
         <Setter Property="Background" Value="{AppThemeBinding Light=#FF0000, Dark=#0000FF}"/>
       </Style>
     </StackPanel.Resources>
     <Border x:Name="Themed" Style="{StaticResource S}"/>
     <Border x:Name="Local" Style="{StaticResource S}" Background="#00FF00"/>
   </StackPanel>"##,
    );
    app.update();
    assert_eq!(warnings, Vec::<String>::new());
    let (themed, local) = (named(&app, root, "Themed"), named(&app, root, "Local"));
    assert_eq!(background(&app, themed), Some("#FF0000".into()));
    assert_eq!(background(&app, local), Some("#00FF00".into()));

    set_user_app_theme(app.world_mut(), AppTheme::Dark);
    app.update();
    assert_eq!(background(&app, themed), Some("#0000FF".into()));
    assert_eq!(
        background(&app, local),
        Some("#00FF00".into()),
        "a local value outranks a Style-tier theme binding, before AND after a flip"
    );
}

#[test]
fn a_trigger_setter_repicks_while_the_trigger_is_already_active() {
    // The regression test for the widened early return in evaluate_triggers:
    // the trigger's CONDITION does not change across the flip, only the
    // value its setter resolves to.
    let mut app = test_app();
    set_user_app_theme(app.world_mut(), AppTheme::Light);
    let (root, warnings) = spawn(
        &mut app,
        r##"<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
     <StackPanel.Resources>
       <Style x:Key="S" TargetType="Border">
         <Setter Property="Background" Value="#101010"/>
         <Style.Triggers>
           <Trigger Property="IsMouseOver" Value="True">
             <Setter Property="Background" Value="{AppThemeBinding Light=#FF0000, Dark=#0000FF}"/>
           </Trigger>
         </Style.Triggers>
       </Style>
     </StackPanel.Resources>
     <Border x:Name="B" Style="{StaticResource S}"/>
   </StackPanel>"##,
    );
    assert_eq!(warnings, Vec::<String>::new());
    let border = named(&app, root, "B");
    app.update();
    assert_eq!(background(&app, border), Some("#101010".into()));

    app.world_mut()
        .entity_mut(border)
        .insert(Interaction::Hovered);
    app.update();
    assert_eq!(background(&app, border), Some("#FF0000".into()));

    // Flip the theme while it stays hovered.
    set_user_app_theme(app.world_mut(), AppTheme::Dark);
    app.update();
    assert_eq!(
        background(&app, border),
        Some("#0000FF".into()),
        "an ACTIVE trigger must re-pick; its condition never changed"
    );

    app.world_mut().entity_mut(border).insert(Interaction::None);
    app.update();
    assert_eq!(
        background(&app, border),
        Some("#101010".into()),
        "still reverts"
    );
}

#[test]
fn a_dynamic_resource_trigger_setter_also_refreshes_while_active() {
    // The same widened early return fixes a pre-existing staleness: a
    // {DynamicResource} trigger setter used to keep the value it resolved
    // when it fired, across a whole theme dictionary swap.
    let mut app = test_app();
    bevy_pf::themes::apply_theme(app.world_mut(), "nord").unwrap();
    let (root, warnings) = spawn(
        &mut app,
        r##"<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
     <StackPanel.Resources>
       <Style x:Key="S" TargetType="Border">
         <Setter Property="Background" Value="#101010"/>
         <Style.Triggers>
           <Trigger Property="IsMouseOver" Value="True">
             <Setter Property="Background" Value="{DynamicResource Pf.ControlBackground}"/>
           </Trigger>
         </Style.Triggers>
       </Style>
     </StackPanel.Resources>
     <Border x:Name="B" Style="{StaticResource S}"/>
   </StackPanel>"##,
    );
    assert_eq!(warnings, Vec::<String>::new());
    let border = named(&app, root, "B");
    app.world_mut()
        .entity_mut(border)
        .insert(Interaction::Hovered);
    app.update();
    let nord = background(&app, border);
    assert_ne!(nord, Some("#101010".into()), "the trigger fired");

    bevy_pf::themes::apply_theme(app.world_mut(), "dracula").unwrap();
    app.update();
    assert_ne!(
        background(&app, border),
        nord,
        "an active trigger's DynamicResource must follow the dictionary swap"
    );
}

#[test]
fn arms_can_be_static_resources() {
    let mut app = test_app();
    set_user_app_theme(app.world_mut(), AppTheme::Dark);
    let (root, warnings) = spawn(
        &mut app,
        r##"<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
     <StackPanel.Resources>
       <SolidColorBrush x:Key="Day" Color="#FF0000"/>
       <SolidColorBrush x:Key="Night" Color="#0000FF"/>
     </StackPanel.Resources>
     <Border x:Name="B"
             Background="{AppThemeBinding Light={StaticResource Day}, Dark={StaticResource Night}}"/>
   </StackPanel>"##,
    );
    app.update();
    assert_eq!(warnings, Vec::<String>::new());
    assert_eq!(
        background(&app, named(&app, root, "B")),
        Some("#0000FF".into())
    );
}

// ---------------------------------------------------------------------
// Rejections and documented limits.
// ---------------------------------------------------------------------

#[test]
fn an_extension_with_no_value_is_rejected() {
    // MAUI throws; bevy_pf warns and skips, which is the crate's idiom.
    for markup in ["{AppThemeBinding}", "{AppThemeBinding Light={x:Null}}"] {
        let (_, warnings) = under(AppTheme::Light, markup);
        assert!(
            warnings
                .iter()
                .any(|w| w.contains("at least one theme or Default")),
            "{markup} should be rejected, got {warnings:?}"
        );
    }
}

#[test]
fn an_unknown_argument_is_rejected() {
    let (_, warnings) = under(AppTheme::Light, "{AppThemeBinding Lite=#FF0000}");
    assert!(
        warnings.iter().any(|w| w.contains("no `Lite` argument")),
        "expected the typo to be named, got {warnings:?}"
    );
}

#[test]
fn a_property_outside_the_store_resolves_once_and_stays() {
    // A documented limit, pinned rather than pretended away: live
    // re-resolution reaches only the store-managed properties, exactly the
    // ceiling {DynamicResource} sits under.
    let mut app = test_app();
    set_user_app_theme(app.world_mut(), AppTheme::Light);
    let (root, warnings) = spawn(
        &mut app,
        r##"<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
     <TextBlock x:Name="T" Text="{AppThemeBinding Light=Sun, Dark=Moon}"/>
   </StackPanel>"##,
    );
    app.update();
    assert_eq!(warnings, Vec::<String>::new());
    let text = named(&app, root, "T");
    let read = |app: &App| app.world().get::<Text>(text).map(|t| t.0.clone());
    assert_eq!(read(&app), Some("Sun".into()));

    set_user_app_theme(app.world_mut(), AppTheme::Dark);
    app.update();
    assert_eq!(
        read(&app),
        Some("Sun".into()),
        "Text is not store-managed, so it resolves once — this pins the LIMIT"
    );
}

// ---------------------------------------------------------------------
// Another dialect's spelling of the same idea.
// ---------------------------------------------------------------------

#[test]
fn requested_theme_variant_sets_the_app_theme() {
    // RequestedThemeVariant is written on Application/Window. Light and
    // Dark are this crate's own, and `Default` means "follow the
    // system" — which is exactly Unspecified.
    for (variant, expected) in [
        ("Light", AppTheme::Light),
        ("Dark", AppTheme::Dark),
        ("Default", AppTheme::Unspecified),
    ] {
        let mut app = test_app();
        // Start from the opposite so a no-op would fail the assert.
        set_user_app_theme(app.world_mut(), AppTheme::Dark);
        let (_, warnings) = spawn(
            &mut app,
            &format!(
                r##"<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        RequestedThemeVariant="{variant}">
             <Border x:Name="B"/>
           </StackPanel>"##
            ),
        );
        assert_eq!(warnings, Vec::<String>::new(), "{variant}");
        assert_eq!(
            app.world().resource::<PfAppTheme>().user(),
            expected,
            "RequestedThemeVariant={variant}"
        );
    }
}

#[test]
fn an_unknown_theme_variant_is_reported() {
    let mut app = test_app();
    let (_, warnings) = spawn(
        &mut app,
        r##"<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                RequestedThemeVariant="Sepia">
     <Border x:Name="B"/>
   </StackPanel>"##,
    );
    assert!(
        warnings.iter().any(|w| w.contains("Sepia")),
        "got {warnings:?}"
    );
}

#[test]
fn compiled_binding_metadata_is_accepted_silently() {
    // x:DataType and x:CompileBindings are consumed by a XAML
    // compiler and mean nothing at runtime. Warning about them would report
    // a non-problem on nearly every such document.
    let mut app = test_app();
    let (_, warnings) = spawn(
        &mut app,
        r##"<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                x:DataType="vm:MainWindowViewModel" x:CompileBindings="True">
     <Border x:Name="B"/>
   </StackPanel>"##,
    );
    assert_eq!(warnings, Vec::<String>::new());
}