The Wings Framework book
Second edition · By DoubleG Arts · · Wings 0.2.0 / Bevy 0.20 / Rust 1.97.1+
Build an application from its first scene to the platform's own design, Liquid Glass, safe areas, background data and navigation. Each chapter explains working code, then gives you an exercise and a checkpoint.
Download this edition as Markdown
Package reference
bevy_wings: Facade, shared prelude and WingsUiPluginsbevy_wings_domain: Entities, use cases, validation and repository contractsbevy_wings_data: Data sources, offline caching and background loadingbevy_wings_di: Dependency injection, modules and scopesbevy_wings_ui_core: System ordering, reactive state and subtree opacitybevy_wings_ui_animation: Tweens, springs, keyframes and visibility transitionsbevy_wings_ui_theme: Theme tokens, painting and the embedded Inter fontbevy_wings_ui_responsive: Breakpoints, responsive layout and UI scalingbevy_wings_ui_modifiers: Fluent layout and styling modifier chainsbevy_wings_ui_shaders: Ripple, shimmer, progress, aurora and glass materialsbevy_wings_ui_widgets: Themed widgets and interaction feedbackbevy_wings_ui_mvvm: View models, bindings, intents and effectsbevy_wings_ui_navigation: Typed back stacks, destinations and adaptive panes
1. Your first Wings application
[dependencies]
bevy = "0.20"
bevy_wings = "0.2"Wings Framework builds application interfaces with Bevy's entity component system. A button is an entity with components for appearance, input and semantics, and a screen is a hierarchy of those entities. This second edition targets Wings 0.2.0, Bevy 0.20 and Rust 1.97.1 or newer. The largest change since 0.1 is that one scene now takes the look of the platform it runs on: Cupertino on iPhone, iPad and Mac, Fluent on Windows and Material on Android and Linux.
Start with the repository examples rather than assembling every feature at once. Clone https://github.com/doublegarts/bevy_wings, enter the checkout and run cargo run --example widgets. For the complete application, run cargo run -p wings-gallery. The UI examples need a display and a working graphics driver; on Ubuntu and Debian, install libudev-dev, libx11-dev, libxi-dev, libxrandr-dev, libxcursor-dev and libxkbcommon-dev first. Add -- --headless for a fixed frame terminal smoke run, which cannot validate the rendered appearance.
For a new application, depend on Bevy 0.20 and bevy_wings 0.2 as shown above; all 13 library crates share the version. The default features are shaders, for the custom UI materials and Liquid Glass, and native, which reads safe areas from iOS, Android and macOS. Register DefaultPlugins before WingsUiPlugins and spawn a Camera2d before your first scene. Dependency injection and navigation take application specific configuration and are added separately.
The code below is the working widgets example. Its support module configures the camera, the window and headless mode, so run it inside the checkout; copying the file alone does not copy the support module. Run it on two kinds of machine, or switch the design as chapter 3 shows, and the same checkboxes, switches and slider take each platform's form. The linked source includes the tests omitted here.
cargo run --example widgets · Complete source and tests
//! Interactive controls, text input, a progress indicator and snackbars.
mod support;
use bevy::prelude::*;
use bevy_wings::prelude::*;
fn main() {
support::run("Wings: widgets", configure);
}
fn configure(app: &mut App) {
app.add_systems(Startup, setup);
}
fn setup(mut commands: Commands) {
commands.spawn_scene(bsn! {
@WingsScaffold
Children [
@WingsScrollColumn { @padding: 24.0, @gap: 16.0 }
Children [
@WingsText { @text: "Widget playground", @role: TypeRole::HeadlineMedium }
--
@WingsCheckbox { @label: "Checkbox" }
--
@WingsSwitch { @label: "Switch" }
--
@WingsRadioGroup { @gap: 8.0 }
Children [
@WingsRadioButton { @label: "Option A", @checked: true }
--
@WingsRadioButton { @label: "Option B" }
]
--
@WingsSlider { @value: 0.5 }
on(|change: On<ValueChange<f32>>| println!("Slider: {:.2}", change.value))
--
@WingsTextField { @label: "Type here", @value: "Hello" }
on(|change: On<WingsTextChanged>| println!("Text: {}", change.value))
--
@WingsLinearProgress { @progress: 0.65 }
--
@WingsButton { @text: "Show snackbar" }
on(|_: On<Activate>, mut messages: MessageWriter<WingsShowSnackbar>| {
messages.write(WingsShowSnackbar::new("Button activated").with_action("OK"));
})
]
]
});
}Try it
Run the widgets example, activate the snackbar button, drag a slider and use Tab to move keyboard focus. Repeat with -- --headless.
Checkpoint
A graphical run responds to input and draws a focus ring around the control that Tab reached; a headless run completes without opening a window. These checks exercise different parts of the application.
2. Compose screens from entities
The bsn! macro describes a scene. A declaration such as @WingsText supplies a scene component's initial properties; Children defines the hierarchy. The -- separator starts a sibling. That distinction matters: a misplaced separator can attach a control to the preceding widget instead of placing it next to it.
Use WingsColumn and WingsRow for common layout, WingsCard for a grouped surface, WingsList for grouped rows and WingsScaffold for the outer application structure. Choose props for what a widget is, and let the design decide how it looks: a button with @variant: WingsButtonVariant::Outlined becomes an outlined Material button, a bordered iOS button, a macOS push button with a hairline or a Fluent standard button. Add marker components when you need to find a particular entity later; a marker is more reliable than searching for a visible label that might be translated or edited.
A modifier chain is a value containing layout and style choices. Bind it to a variable and place that value alongside the scene component it should affect. fill_max_width fills available width; padding adds inner space; background and shape select semantic theme roles. Chaining hover_scale adds an interaction animation without changing your business logic. Keep modifiers for your own layout decisions and leave a widget's internal metrics to its design.
At runtime, query and change the owning component rather than rebuilding the entire screen each frame. Wings folds a changed modifier into the underlying Bevy UI components. If the modifier does not change, its system can skip that entity. This is a useful reason to keep static decoration separate from frequently changing model data.
cargo run --example modifiers · Complete source and tests
//! Compose layout, theme paint, shape, elevation and hover scale on a node.
mod support;
use bevy::prelude::*;
use bevy_wings::prelude::*;
#[derive(Component, Default, Clone)]
struct ModifiedCard;
fn main() {
support::run("Wings: modifiers", configure);
}
fn configure(app: &mut App) {
app.add_systems(Startup, setup);
}
fn setup(mut commands: Commands) {
let style = modifier()
.width(360.0)
.padding(32.0)
.background(ColorRole::PrimaryContainer)
.shape(ShapeRole::Large)
.elevation(3)
.hover_scale(1.08);
commands.spawn_scene(bsn! {
@WingsScaffold
Children [
@WingsColumn { @padding: 48.0, @gap: 24.0 }
Children [
@WingsText { @text: "Hover the styled card", @role: TypeRole::HeadlineMedium }
--
Node style ModifiedCard bevy::picking::hover::Hovered
Children [ @WingsText { @text: "A modifier chain becomes ordinary ECS components." } ]
]
]
});
}Try it
Add a second card with a different padding value. Give it a marker component, then change its modifier from a Bevy system.
Checkpoint
Only the marked card changes. The other card remains a separate entity and keeps its own modifier chain.
3. Choose a design: Material, Cupertino or Fluent
# "system": Material on Android and Linux, Fluent on Windows,
# Cupertino on iOS, iPadOS and macOS.
# "custom": the design in [custom], identical on every platform.
ui = "system"
# "light", "dark" or "system".
appearance = "system"
# Tints Cupertino and Fluent controls and seeds the Material palette.
accent = "#3D59FC"
[custom]
design = "material"WingsTheme now carries a WingsDesign: Material, Ios, MacOs or Fluent. Every widget keeps one API and gets its look from a skin for the active design. The skin systems run in the new WingsUiSystems::Skin set, between Responsive and Modifier. They style widgets as they spawn and restyle all of them when the design changes, so a running app switches designs without respawning a single entity.
A wings.toml file next to Cargo.toml chooses the look. With ui = "system", the default, an app gets Cupertino on iOS, iPadOS and macOS, Fluent on Windows and Material on Android, Linux and the web. With ui = "custom", the design named in [custom] applies on every platform, with your own font family, font scale, radii, spacing and color roles. The appearance key picks light, dark or the system setting, and the accent key tints Cupertino and Fluent controls and seeds the Material palette.
The wings_config! macro embeds the file at compile time, so the setting also travels inside iOS and Android packages. An invalid file panics at startup, before any window opens, with a message that names the problem. WingsUiPlugins::configured(wings_config!()) installs the theme the file describes; without a file, the default theme behaves like ui = "system".
theme.set_design switches at runtime. It replaces every token set with the new design's defaults, colors, type, shapes, spacing, elevation and motion, and keeps the mode and the accent. Tokens from [custom] are not reapplied, so treat runtime switching as a preview or a user preference and keep brand overrides in the file. The Apple designs follow measurements taken from a SwiftUI reference app and use the system font, San Francisco, which Wings never bundles; Fluent uses Segoe UI Variable where Windows provides it, and other text falls back to the embedded Inter.
WINGS_DESIGN=fluent cargo run -p wings-gallery · Gallery source
use bevy::prelude::*;
use bevy_wings::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// Embeds wings.toml from next to Cargo.toml at compile time.
.add_plugins(WingsUiPlugins::configured(wings_config!()))
.add_systems(Startup, setup)
.add_systems(Update, report_design)
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
commands.spawn_scene(bsn! {
@WingsScaffold
Children [
@WingsTopAppBar { @title: "Designs" }
Children [
@WingsButton { @text: "Next", @variant: WingsButtonVariant::Text }
on(|_: On<Activate>, mut theme: ResMut<WingsTheme>| {
let next = theme.design.next();
theme.set_design(next);
})
]
--
@WingsScrollColumn
Node { height: percent(100) }
Children [
@WingsList
Children [
@WingsListSection { @header: "Design", @footer: "Every widget restyles in the next frame." }
Children [
@WingsListItem { @headline: "Material", @supporting: "Android and Linux" }
on(|_: On<Activate>, mut theme: ResMut<WingsTheme>| theme.set_design(WingsDesign::Material))
--
@WingsListItem { @headline: "iOS", @supporting: "iPhone and iPad" }
on(|_: On<Activate>, mut theme: ResMut<WingsTheme>| theme.set_design(WingsDesign::Ios))
--
@WingsListItem { @headline: "macOS", @supporting: "Mac" }
on(|_: On<Activate>, mut theme: ResMut<WingsTheme>| theme.set_design(WingsDesign::MacOs))
--
@WingsListItem { @headline: "Fluent", @supporting: "Windows" }
on(|_: On<Activate>, mut theme: ResMut<WingsTheme>| theme.set_design(WingsDesign::Fluent))
]
--
@WingsListSection { @header: "Controls" }
Children [
@WingsSwitch { @label: "Notifications", @checked: true }
--
@WingsSlider { @value: 0.4 }
]
]
]
]
});
}
fn report_design(theme: Res<WingsTheme>) {
if theme.is_changed() {
info!("design: {}", theme.design.name());
}
}Try it
Run the program and switch designs from the list and with the Next button. Then set ui = "custom" and design = "fluent" in wings.toml and rebuild.
Checkpoint
The same entities restyle in place on every switch and the log prints each design's name. With the custom file, the Fluent look appears on a Mac or an Android device too.
4. Theme with roles instead of colors
A theme resource connects semantic choices to a concrete light or dark palette. A button expresses Primary and OnPrimary rather than storing an application wide color pair. The painter resolves those roles and writes Bevy colors. Changing the theme resource repaints existing entities, cross fading over theme.motion.theme_transition; you do not need to respawn them.
Each design brings its own palette. Material builds tonal palettes from a seed; the Apple designs use the iOS and macOS system colors, labels, fills and grouped backgrounds; Fluent uses the Fluent 2 colors. ColorRole gained Fill, SecondaryFill, TertiaryFill, TertiaryLabel, GroupedBackground and SecondaryGroupedBackground for those surfaces. WingsTheme::from_seed builds the platform's design around a seed: Material derives the whole palette from it, while Cupertino and Fluent use it as the tint.
For handwritten Bevy nodes, add WingsBackground, WingsForeground or WingsBorderPaint to opt into painting, and WingsContentColor with inheritance when several descendants share a content color. Widgets supply these components for you, so start with a widget before adding custom paint. A fixed color suits a photograph, a brand illustration or an exact status indicator, but it is not a substitute for a role: fixed colors do not follow the design or the scheme.
Themes can also live in asset files. A .wings.toml file has the same format as wings.toml, and WingsThemeFilePlugin keeps the theme in sync with it. With Bevy's file_watcher feature, saving the file restyles the running app. A light or dark switch made at runtime survives edits unless the file changes appearance, and a file with an error keeps the current theme and logs the problem. Check both schemes and keyboard focus whenever you customize a palette.
# A custom design that looks the same on every platform. Run the gallery with
# WINGS_THEME_FILE=themes/brand.wings.toml, then edit and save this file: the theme reloads.
ui = "custom"
appearance = "system"
accent = "#6750A4"
[custom]
design = "material"
font_scale = 1.0
radii = [0, 6, 10, 14, 20, 28]
spacing = [4, 8, 16, 24, 32]
[custom.light]
primary = "#6750A4"
background = "#FFFBFE"
[custom.dark]
primary = "#D0BCFF"
background = "#141218"// Follows assets/themes/brand.wings.toml; edit and save it while the app runs.
app.add_plugins(WingsThemeFilePlugin::new("themes/brand.wings.toml"));cargo run --example theme · Complete source and tests
//! Toggle light/dark mode and choose a seeded color scheme.
mod support;
use bevy::prelude::*;
use bevy_wings::prelude::*;
fn main() {
support::run("Wings: theme", configure);
}
fn configure(app: &mut App) {
app.add_systems(Startup, setup);
}
fn setup(mut commands: Commands) {
commands.spawn_scene(bsn! {
@WingsScaffold
Children [
@WingsColumn { @padding: 32.0, @gap: 16.0 }
Children [
@WingsText { @text: "Theme roles update together", @role: TypeRole::HeadlineMedium }
--
@WingsButton { @text: "Toggle light / dark" }
on(|_: On<Activate>, mut theme: ResMut<WingsTheme>| theme.toggle_dark())
--
@WingsButton { @text: "Use a green seed", @variant: WingsButtonVariant::Outlined }
on(|_: On<Activate>, mut theme: ResMut<WingsTheme>| {
let mode = theme.mode;
*theme = WingsTheme::from_seed(Color::srgb(0.15, 0.65, 0.35));
theme.mode = mode;
})
--
@WingsCard Children [ @WingsText { @text: "Surface, content, border and typography come from roles." } ]
]
]
});
}Try it
Switch between light and dark in the theme example, then use the green seed. Run the gallery with WINGS_THEME_FILE=themes/brand.wings.toml, change primary in the file and save it.
Checkpoint
Existing widgets repaint in place, text stays readable and focus stays visible in both schemes. The gallery applies the saved file without a rebuild.
5. Float chrome on Liquid Glass
In the iOS and macOS designs, bars float over the content, which keeps scrolling underneath them. On iOS that is the navigation bar, the tab bar and toasts; on macOS the toolbar, the sidebar and toasts. Wings moves this chrome out of the scaffold into an overlay root drawn by a second camera, the overlay camera. Wings creates it next to your UI camera and points it at the same render target, so glass also works in an image or a second window. Menus, dropdowns and tooltips open on the same layer.
Before the overlay camera draws, the shaders crate captures what lies below, blurs it with a dual Kawase filter at half and quarter resolution, and WingsLiquidGlassMaterial refracts that blur at the edges and adds a rim light. WingsGlass puts a node on glass in one of three styles: Regular for bars and panels, Clear over rich media, or Tinted with a color role for prominent buttons. Real glass appears only on the overlay layer with the shaders feature. Elsewhere, in headless apps, or with reduce_transparency set in WingsGlassSettings, glass falls back to a translucent fill with a hairline border.
The iOS navigation bar follows iOS 26. Its buttons sit on glass capsules, and the soft scroll edge, WingsScrollEdge, covers the status bar and the toolbar row: content that scrolls into it blurs progressively and settles into the background color without a hard line. With WingsTitleDisplay::Large, or the default Automatic on a root screen, the large title moves up and fades with the scroll while the inline title fades in, centered like UIKit and shortened with an ellipsis when the buttons leave no room. Both follow the scroll offset, so scrolling back reverses them exactly.
The program below forces the iOS design and previews an iPhone, so the effect shows on any desktop. Point the navigation item icons at PNG files in your assets folder; the gallery's assets/icons folder has suitable ones. Glass is a visual effect, so check it in a real window, and use the Opaque button, which flips reduce_transparency, to confirm that the interface still reads clearly without it.
WINGS_DESIGN=ios WINGS_DEVICE=iphone cargo run -p wings-gallery · Gallery source
use bevy::prelude::*;
use bevy_wings::prelude::*;
fn main() {
let phone = WingsDeviceProfile::IPHONE_PRO;
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
resolution: (phone.size.x as u32, phone.size.y as u32).into(),
..default()
}),
..default()
}))
// Chrome floats on glass in the iOS and macOS designs.
.add_plugins(WingsUiPlugins.set(WingsThemePlugin::with_theme(WingsTheme::ios())))
.insert_resource(WingsDevicePreview::new(phone))
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
let messages: Vec<_> = (1..=40)
.map(|i| {
let headline = format!("Message {i}");
bsn! { @WingsListItem { @headline: headline, @supporting: "Scrolls under the bars" } }
})
.collect();
commands.spawn_scene(bsn! {
@WingsScaffold
Children [
@WingsTopAppBar { @title: "Inbox", @title_display: WingsTitleDisplay::Large }
Children [
@WingsButton { @text: "Opaque", @variant: WingsButtonVariant::Text }
on(|_: On<Activate>, mut glass: ResMut<WingsGlassSettings>| {
glass.reduce_transparency = !glass.reduce_transparency;
})
]
--
@WingsScrollColumn
Node { height: percent(100) }
Children [ {messages} ]
--
@WingsNavigationBar
Children [
@WingsNavigationItem { @label: "Inbox", @icon: "icons/home.png", @selected: true }
--
@WingsNavigationItem { @label: "Settings", @icon: "icons/settings.png" }
]
]
});
}Try it
Scroll the inbox slowly under the top bar and the tab bar, then press Opaque. Repeat in the gallery with WINGS_DESIGN=macos.
Checkpoint
Rows blur under both bars and the large title hands over to the inline one as you scroll. With reduced transparency the bars turn solid and every label stays readable.
6. Adapt layout to the available window
Responsiveness starts with available logical width rather than device names. The viewport class changes when the window crosses the configured breakpoints: Compact below 600, Medium to 839, Expanded to 1199, Large to 1599 and ExtraLarge above. A desktop window can be narrow; a tablet can be wide. Designing around those classes keeps layout decisions tied to actual space.
WingsResponsiveNode applies layout patches for width classes, WingsResponsiveVisibility changes visibility, and WingsResponsiveColumns changes the number of items in a row. Use those tools for presentation decisions. Keep the underlying records and domain rules unchanged when a window changes size.
The focused example changes its grid around 600, 840 and 1200 logical pixels. Resize slowly across those boundaries and watch the same content reflow. Navigation adapts by itself: the Material navigation bar becomes a rail on wide windows, and in narrow windows the macOS sidebar and the Fluent navigation pane collapse to their icons. Adaptive list and detail navigation shows two panes from the Expanded class without a different detail screen.
A responsive page still needs minimum usable sizes, sensible wrapping and scroll behavior. Long translated labels are a useful stress test. Prefer a scroll container for long content rather than shrinking every control until the page fits, and WingsAutoScale when the whole UI should grow on large screens. For custom breakpoints, document the intended classes and validate both sides of each boundary.
cargo run --example responsive · Complete source and tests
//! Resize the window: the grid grows from one column to four.
mod support;
use bevy::prelude::*;
use bevy_wings::prelude::*;
#[derive(Component, Default, Clone)]
struct ResponsiveGrid;
fn main() {
support::run("Wings: responsive layout", configure);
}
fn configure(app: &mut App) {
app.add_systems(Startup, setup);
}
fn setup(mut commands: Commands) {
let columns = WingsResponsiveColumns(WingsResponsive::new(1).medium(2).expanded(3).large(4));
commands.spawn_scene(bsn! {
@WingsScaffold
Children [
@WingsColumn { @padding: 24.0, @gap: 16.0 }
Children [
@WingsText { @text: "Resize me: <600 / 600 / 840 / 1200 px", @role: TypeRole::TitleLarge }
--
@WingsGrid { @gap: 16.0 } columns ResponsiveGrid
Children [
@WingsCard Children [ @WingsText { @text: "One" } ]
--
@WingsCard Children [ @WingsText { @text: "Two" } ]
--
@WingsCard Children [ @WingsText { @text: "Three" } ]
--
@WingsCard Children [ @WingsText { @text: "Four" } ]
]
]
]
});
}Try it
Run the responsive example and resize just below and above each breakpoint. Add a long label to one item.
Checkpoint
Column counts change at the intended boundaries and the long label wraps without covering another control.
7. Safe areas, device previews and right to left
WingsSafeArea describes what covers the screen, in logical pixels: insets for status bars, notches, the Dynamic Island, the home indicator, Android's system and gesture bars and display cutouts, plus the macOS title bar, the on screen keyboard, TV overscan and the folds of foldable devices. With the native feature, on by default, the values come from the platform: winit's safe area on iOS, the content rectangle on Android and the transparent title bar on macOS.
Scaffolds apply the insets by themselves. Bars grow under the system bars so their color reaches the edge, while their content and the screen's content stay clear. For a node of your own, add WingsSafeAreaPadding with the edges that should respect the safe area; it adds the insets to the node's own padding and keeps that padding when the insets change. Read the resource directly when a layout needs a number, for example to keep a control away from a fold.
Device profiles make this testable on a desktop. WingsDevicePreview takes a WingsDeviceProfile, such as IPHONE_PRO, ANDROID_PHONE or ANDROID_TABLET, with more for iPads, foldables, TVs, Mac and desktop windows and Vision. It gives the viewport the profile's size and the safe area its insets, and draws its status bar, Dynamic Island and home indicator. landscape() rotates a profile, and the keyboard field simulates the on screen keyboard. Size the window to the profile, as the program below does, so the preview matches the device.
Right to left layouts arrive in the same release. Set the WingsLayoutDirection resource, for example to WingsLayoutDirection::for_language("ar"), and the UI mirrors: rows run from the right, leading padding moves to the right, and chevrons and back buttons swap sides, while text and images stay readable. Mirroring is a transform on UI roots, so your layout code stays in left to right terms. Mark leaf content that keeps its orientation, such as playback progress or a logo, with WingsNoMirror.
WINGS_DEVICE=iphone-landscape cargo run -p wings-gallery · Gallery source
use bevy::prelude::*;
use bevy_wings::prelude::*;
fn main() {
// An iPhone on its side: the Dynamic Island moves to the left edge.
let device = WingsDeviceProfile::IPHONE_PRO.landscape();
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
resolution: (device.size.x as u32, device.size.y as u32).into(),
..default()
}),
..default()
}))
.add_plugins(WingsUiPlugins)
.insert_resource(WingsDevicePreview::new(device))
.insert_resource(WingsLayoutDirection::for_language("ar"))
.add_systems(Startup, setup)
.add_systems(Update, log_safe_area)
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
// The scaffold keeps its bars and content clear of the insets by itself.
commands.spawn_scene(bsn! {
@WingsScaffold
Children [
@WingsTopAppBar { @title: "Podcast" }
--
@WingsColumn { @gap: 16.0, @padding: 24.0 }
Children [
@WingsText { @text: "Rows, padding and chevrons mirror from right to left." }
--
@WingsListItem { @headline: "Episodes", @accessory: WingsListAccessory::Chevron }
--
// Playback progress keeps running left to right.
@WingsLinearProgress { @progress: 0.3 }
WingsNoMirror
]
]
});
// Your own full width bar respects the sides and the home indicator.
let safe = WingsSafeAreaPadding::edges(WingsEdges::SIDES_AND_BOTTOM);
commands.spawn_scene(bsn! {
Node {
position_type: PositionType::Absolute,
bottom: px(0),
width: percent(100),
padding: px(12),
}
safe
Children [ @WingsButton { @text: "Play", @fill_width: true } ]
});
}
fn log_safe_area(safe: Res<WingsSafeArea>) {
if safe.is_changed() {
info!("insets {:?}, keyboard {}", safe.insets, safe.keyboard);
}
}Try it
Run the program, then change the profile to WingsDeviceProfile::FOLDABLE and to ANDROID_PHONE_BUTTONS. Set keyboard to true on the preview, and switch the direction back with WingsLayoutDirection::LeftToRight.
Checkpoint
The logged insets change with each profile, the Play bar always clears the home indicator and the keyboard, and in right to left order only the progress bar keeps running from left to right.
8. Menus, pickers, sheets and long lists
Wings 0.2 adds the controls most applications reach for after buttons and switches. WingsSegmented and WingsTabs choose one of a few options and trigger WingsSegmentChanged; the selection lives in WingsSelectedIndex, so a view model can drive it too. WingsDropdown picks a value and WingsMenuButton offers actions, and both report WingsMenuSelected with the index and the label. WingsTooltip is a component: add it to any widget with a text and a delay.
WingsDatePicker shows a month grid with steppers and triggers WingsDateChanged; WingsDate does the calendar math without extra dependencies. WingsTimePicker shows hour and minute fields with steppers and arrow key support. WingsBottomSheet and WingsSideSheet slide over the content with a scrim; their children are the content, and a bottom sheet is Medium, Large or Fit tall. Show a sheet or a dialog by setting visible on its WingsAnimatedVisibility. A click on the scrim or a back press hides a sheet and triggers WingsSheetDismissed.
Settings style screens use WingsList and WingsListSection with a header and a footer. A WingsListItem can show detail text on the trailing side and an accessory: a chevron for rows that open another screen, or a check mark for the selected option. Each design draws sections its own way: a plain Material list, inset grouped iOS sections, a grouped macOS form or Fluent settings cards. WingsDialog gains destructive, which draws the confirm action in the error color.
Long collections use WingsVirtualList, or WingsVirtualGrid for cells in columns. Give it a count, a fixed row height and a closure that builds one row. Only the rows in view, plus a few above and below, exist as entities, and rows are despawned as they scroll away. Place the list on a node with a height, as the program does inside a card. In the repository's benchmark, scrolling 100,000 rows costs about 0.03 ms per frame on an Apple M1 Max.
WINGS_SCREEN=controls cargo run -p wings-gallery · Gallery source
use bevy::prelude::*;
use bevy_wings::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(WingsUiPlugins)
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
// Ten thousand rows; only the ones on screen exist as entities.
let rows = WingsVirtualList::new(10_000, 56.0, |index| {
let headline = format!("Order {}", index + 1);
Box::new(bsn! { @WingsListItem { @headline: headline } })
});
commands.spawn_scene(bsn! {
@WingsScaffold
Children [
@WingsTopAppBar { @title: "Orders" }
--
@WingsScrollColumn { @gap: 16.0, @padding: 24.0 }
Node { height: percent(100) }
Children [
@WingsSegmented { @options: vec!["Day".into(), "Week".into(), "Month".into()] }
on(|ev: On<WingsSegmentChanged>| info!("range {}", ev.index))
--
@WingsRow { @gap: 12.0, @wrap: true }
Children [
@WingsDropdown { @options: vec!["Newest".into(), "Oldest".into(), "Largest".into()] }
on(|ev: On<WingsMenuSelected>| info!("sort by {}", ev.label))
--
@WingsMenuButton { @label: "Export", @items: vec!["CSV".into(), "PDF".into()] }
on(|ev: On<WingsMenuSelected>| info!("export {}", ev.label))
--
@WingsButton { @text: "Filters", @variant: WingsButtonVariant::Tonal }
WingsTooltip { text: "Opens a sheet", delay: 0.5 }
on(|_: On<Activate>, mut sheets: Query<&mut WingsAnimatedVisibility, With<WingsSheetDetent>>| {
for mut sheet in &mut sheets {
sheet.visible = true;
}
})
]
--
@WingsDatePicker
on(|ev: On<WingsDateChanged>| info!("from {:?}", ev.date))
--
@WingsCard { @style: WingsCardStyle::Outlined }
Node { height: px(280), padding: px(0) }
Children [
Node { height: percent(100) }
rows
]
--
@WingsList
Children [
@WingsListSection { @header: "Account" }
Children [
@WingsListItem { @headline: "Plan", @detail: "Team", @accessory: WingsListAccessory::Chevron }
--
@WingsListItem { @headline: "Delete all orders" }
on(|_: On<Activate>, mut dialogs: Query<&mut WingsAnimatedVisibility, With<WingsDialog>>| {
for mut dialog in &mut dialogs {
dialog.visible = true;
}
})
]
]
--
@WingsBottomSheet { @title: "Filters" }
on(|_: On<WingsSheetDismissed>| info!("filters closed"))
Children [
@WingsSwitch { @label: "Only open orders", @checked: true }
]
--
@WingsDialog {
@title: "Delete all orders?",
@text: "This cannot be undone.",
@confirm: "Delete",
@destructive: true,
}
on(|result: On<WingsDialogResult>| info!("confirmed: {}", result.confirmed))
]
]
});
}Try it
Open the Filters sheet and close it with Escape, then again with a click on the scrim. Scroll the order list to the end, open the delete dialog and confirm it.
Checkpoint
Every event prints once in the terminal, and the order list stays smooth at order 10,000 because only the rows in view exist.
9. Touch, keyboard, gamepad and back
Every scroll area in Wings scrolls by touch: scroll columns, lists and virtual lists follow the finger and keep gliding after a flick, slowing down like iOS. Touching a gliding area stops it, and a drag that turns into a scroll cancels the tap on the button under the finger. Taps that start and end within one frame, such as quick taps and simulator clicks, now activate widgets instead of leaving them pressed. The WingsTouchScroll resource tunes the slop, the deceleration and the speed limits, or turns touch scrolling off.
When the keyboard moves focus, with Tab, the arrow keys or a gamepad, the focused widget shows the focus ring of the active design; pointer clicks do not show rings, as on every platform. Add WingsNoFocusRing to a widget that shows focus itself. Every interactive widget also joins directional navigation: the D-pad, the left stick and the arrow keys move focus to the nearest widget in that direction, South activates and East goes back. WingsGamepadNavigation sets the stick threshold, the repeat rate and whether arrow keys take part.
Back is one pipeline. Escape, the browser back key, gamepad East and Android's back button and gesture arrive as one press in WingsBack. The press closes the topmost layer first, a menu, then a dialog, then a sheet, and only a press that nothing used goes back a screen. At the first screen nothing happens, so Android apps stay open. On Android 13 and newer, set android:enableOnBackInvokedCallback="false" in the manifest so the gesture reaches the app. On iOS the leading edge swipe is interactive and goes back past a third of the width or on a quick flick.
Your own overlays join the pipeline. A system in WingsBackSystems::Overlays calls WingsBack::consume, which returns true only for a press that nothing used yet, and closes its panel; navigation runs later, in WingsBackSystems::Navigation, and skips a used press. WingsBack::press sends a back from code, for example from a toolbar button, and is handled from the next frame. The program below closes its help card that way before anything else sees the press.
WINGS_SCREEN=settings cargo run -p wings-gallery · Gallery source
use bevy::prelude::*;
use bevy_wings::prelude::*;
/// A panel of our own that should close on back, like a sheet.
#[derive(Component, Default, Clone)]
struct HelpPanel;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(WingsUiPlugins)
// Touch scrolling and gamepad focus are on by default; tune them here.
.insert_resource(WingsTouchScroll { deceleration: 0.997, ..default() })
.insert_resource(WingsGamepadNavigation { arrow_keys: false, ..default() })
.add_systems(Startup, setup)
.add_systems(Update, close_help_on_back.in_set(WingsBackSystems::Overlays))
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
commands.spawn_scene(bsn! {
@WingsScaffold
Children [
@WingsTopAppBar { @title: "Input" }
Children [
// A toolbar back button sends the same press as Escape or gamepad B.
@WingsButton { @text: "Back", @variant: WingsButtonVariant::Text }
on(|_: On<Activate>, mut back: ResMut<WingsBack>| back.press())
]
--
@WingsColumn { @gap: 12.0, @padding: 24.0 }
Children [
@WingsButton { @text: "Show help" }
on(|_: On<Activate>, mut panels: Query<&mut Node, With<HelpPanel>>| {
for mut node in &mut panels {
node.display = Display::Flex;
}
})
--
@WingsCard
HelpPanel
Node { display: Display::None }
Children [
@WingsText { @text: "Escape, gamepad B or Android's back closes this first." }
]
]
]
});
}
/// Uses the back press before navigation sees it.
fn close_help_on_back(mut back: ResMut<WingsBack>, mut panels: Query<&mut Node, With<HelpPanel>>) {
for mut node in &mut panels {
if node.display != Display::None && back.consume() {
node.display = Display::None;
info!("help closed by {:?}", back.source());
}
}
}Try it
Show the help card, then press Escape twice. Connect a gamepad and move focus with the D-pad. In the gallery, open Wi-Fi from Settings and go back with Escape, then with the back button on the Wi-Fi screen.
Checkpoint
The first Escape closes only the help card and logs Keyboard; the second does nothing, because there is no screen to go back to. Focus moves between the buttons and the ring follows the design.
10. State, bindings and user intent
A Wings view model is a component on the screen root. It contains the presentation state for that screen. Implement WingsViewModel and register its type. Child bindings find the closest view model of the requested type by walking the entity hierarchy, so two screens can use the same model type without sharing an instance.
In the counter example, bind_text derives a label from Counter.count. on_activate converts an Activate event into a mutation of Counter. The mutation participates in Bevy change detection; the binding recalculates and writes text only when necessary. This is the complete reactive path, with no parallel observer graph outside the ECS, and it is the same in every design.
Use bind_enabled for actions that depend on state, bind_visible for optional content and bind_checked for selections. For another component type, use the generic bind and register it. New in 0.2, the Loadable bindings show each phase of a background load from one view model field, as chapter 13 shows. Derived display strings belong near the binding; validation and business operations belong in the domain layer.
Keep transient notifications separate from durable state. WingsEffects queues one shot events that are drained into Bevy messages. A count belongs in the model; a snackbar saying that a reset happened is an effect. View models can also come from dependency injection through view_model providers, and a navigation entry keeps its model alive while that entry stays on the back stack, then clears it when despawned.
cargo run --example mvvm · Complete source and tests
//! A component view model, change-driven text bindings and button intents.
mod support;
use bevy::prelude::*;
use bevy_wings::prelude::*;
#[derive(Component, Default, Clone)]
struct Counter {
count: u32,
}
impl WingsViewModel for Counter {}
#[derive(Component, Default, Clone)]
struct IncrementButton;
fn main() {
support::run("Wings: MVVM", configure);
}
fn configure(app: &mut App) {
app.register_view_model::<Counter>()
.add_systems(Startup, setup);
}
fn setup(mut commands: Commands) {
let label = bind_text(|vm: &Counter| format!("Count: {}", vm.count));
commands.spawn_scene(bsn! {
@WingsScaffold Counter
Children [
@WingsColumn { @padding: 32.0, @gap: 16.0 }
Children [
@WingsText { @role: TypeRole::HeadlineMedium } label
--
@WingsButton { @text: "Increment" } IncrementButton
on(on_activate(|vm: &mut Counter| vm.count += 1))
--
@WingsButton { @text: "Reset", @variant: WingsButtonVariant::Outlined }
on(on_activate(|vm: &mut Counter| vm.count = 0))
]
]
});
}Try it
Add a decrement action that is enabled only when count is greater than zero. Trigger it from the UI and from a test.
Checkpoint
The label follows the component value and the disabled state follows the same model. No separate mutable display count is needed.
11. Put business rules in the domain
The domain crate is ordinary Rust without a Bevy dependency. It defines entities, typed identifiers, repository contracts, validation, paging and use cases. This boundary lets you test a business operation without opening a window, and reuse it from a server or a command line tool.
Id<T> distinguishes identities by entity type: a user identifier cannot be passed where an order identifier is expected. DomainEntity gives a record its identity. ReadRepository and WriteRepository describe access operations without committing the caller to a database, an HTTP backend or an in memory implementation. With the serde feature, which the data crate turns on, Id<T>, Page<T> and PageRequest serialize, so entities that derive Serialize and Deserialize can be stored.
A use case represents one meaningful operation with input and output. Collect validation failures before writing. The focused example validates a title and creates an entity with a typed ID. In an application, the screen turns a user action into a use case call, then converts the resulting value or DomainError into presentation state. Do not let the domain depend on widget entities or theme roles.
Version 0.2 adds pipelines through UseCaseExt. retry(policy) repeats a failed call according to a RetryPolicy, by default only for retryable errors such as DomainError::Unavailable, waiting the backoff before the first retry and twice as long before each next one. timeout(limit) fails with a retryable Unavailable error when the call takes too long, logged(name, sink) reports the name, duration and error of every run, and map(f) transforms the output. Each decorator is a use case itself, so they nest in any order and register in dependency injection like the use case they wrap.
use bevy_wings::prelude::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;
fn main() -> DomainResult<()> {
// A backend that is busy for the first two calls.
let calls = Arc::new(AtomicU32::new(0));
let counter = calls.clone();
let load_title = use_case(move |id: u32| {
if counter.fetch_add(1, Ordering::SeqCst) < 2 {
Err(DomainError::Unavailable("server busy".into()))
} else {
Ok(format!("note {id}"))
}
})
// Unavailable errors are retryable; waits 100 ms, then 200 ms.
.retry(RetryPolicy::times(3).with_backoff(Duration::from_millis(100)))
.timeout(Duration::from_secs(2))
.logged("load title", |event| println!("{event:?}"))
.map(|title: String| title.to_uppercase());
let title = load_title.execute(7)?;
println!("{title} after {} calls", calls.load(Ordering::SeqCst));
Ok(())
}cargo run --example domain · Complete source and tests
//! Plain Rust business rules: typed identity, validation and a use case.
use bevy_wings::prelude::*;
#[derive(Clone, Debug, PartialEq)]
struct Note {
id: Id<Note>,
title: String,
}
impl DomainEntity for Note {
fn id(&self) -> Id<Note> {
self.id
}
}
fn main() -> DomainResult<()> {
let validator = Validator::<String>::new()
.rule(
"title",
|title| rules::not_blank(title),
"A title is required",
)
.rule(
"title",
|title| rules::length_between(title, 1, 40),
"Use at most 40 characters",
);
println!("Invalid title: {:?}", validator.errors(&" ".into()));
let create = use_case(move |title: String| {
validator.validate(&title)?;
Ok(Note {
id: Id::new(1),
title,
})
});
println!("Created: {:?}", create.execute("Ship Wings".into())?);
Ok(())
}Try it
Run the pipeline program, then lower the attempts to two. In the domain example, reject a blank title, add another rule and test a valid entity and every expected failure.
Checkpoint
With three attempts the program prints one log event and NOTE 7 after 3 calls, about 300 ms later; with two it fails with the retryable error. Invalid input produces field errors without a write.
12. Cache, persist and synchronize
[dependencies]
bevy = "0.20"
bevy_wings = { version = "0.2", features = ["http", "database"] }
serde = { version = "1", features = ["derive"] }The data layer implements the domain's access contracts. OfflineFirstRepository combines a local DataSource with a RemoteSource. CacheFirst, the default, returns fresh local data without asking the backend, refreshes expired values and serves the local copy when the remote is unavailable. RemoteFirst, CacheOnly and RemoteOnly represent the other explicit tradeoffs. Choose a policy from the needs of each operation, not from the convenience of a global default.
In 0.1 the local copy lived in memory. Version 0.2 adds durable sources. FileSource keeps entities in a JSON file and replaces it atomically on every write, which suits settings, drafts, small caches and save games. DatabaseSource, behind the database feature, stores them in an embedded redb database, a crash safe single file with one table per source: WingsDatabase::open opens the file and its source method returns a table. Pass either to with_local.
HttpRemote implements RemoteSource for a REST resource: GET on the base URL for the list, and GET, PUT and DELETE on the base URL plus an id for one entity, encoded as JSON. It talks to any WingsHttpClient. The http feature adds UreqClient and HttpRemote::new, and a closure works as a client in tests. Status codes become domain errors: 401 and 403 are Unauthorized, 409 is a conflict, and 408, 429, 5xx and network failures are Unavailable, which is retryable. Calls block, so run them through load as chapter 13 shows.
Writes apply locally at once and are pushed to the remote; a retryable failure queues the write, and sync delivers the queue in order once the backend answers. The queue itself is kept in memory: a FileSource keeps the entity across a restart, but a pending write that never synchronized is not replayed. Call sync before the app goes to the background, or reconcile local and remote records at startup. FakeRemote and ManualClock keep caching and expiry tests deterministic, as the focused example shows.
use bevy_wings::data::{WingsHttpRequest, WingsHttpResponse};
use bevy_wings::prelude::*;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Duration;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct Note {
id: Id<Note>,
title: String,
}
impl DomainEntity for Note {
fn id(&self) -> Id<Note> {
self.id
}
}
fn main() -> DomainResult<()> {
let dir = std::env::temp_dir().join("wings-book");
// In the app: HttpRemote::new(url) sends real requests (feature http).
// Here a client without a network shows the offline path.
let offline = |_: WingsHttpRequest| -> Result<WingsHttpResponse, String> { Err("no network".into()) };
let remote = HttpRemote::<Note>::with_client("https://api.example.com/notes", offline);
// The local copy lives in a JSON file and survives restarts.
let local = FileSource::open(dir.join("notes.json"))?;
println!("notes on disk: {}", local.len());
let repository = OfflineFirstRepository::new(Arc::new(remote))
.with_local(local)
.with_policy(CachePolicy::CacheFirst)
.with_ttl(Duration::from_secs(60));
repository.save(Note { id: Id::new(1), title: "Written offline".into() })?;
println!("pending writes: {}", repository.pending_writes());
println!("notes: {:?}", repository.all()?);
Ok(())
}
#[test]
fn server_errors_are_retryable() {
let busy = |_: WingsHttpRequest| -> Result<WingsHttpResponse, String> {
Ok(WingsHttpResponse { status: 503, body: Vec::new() })
};
let remote = HttpRemote::<Note>::with_client("https://api.example.com/notes", busy);
assert!(remote.fetch_all().unwrap_err().is_retryable());
}cargo run --example data · Complete source and tests
//! Cached reads, offline writes and synchronization after reconnecting.
use bevy_wings::prelude::*;
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq)]
struct Note {
id: Id<Note>,
title: String,
}
impl DomainEntity for Note {
fn id(&self) -> Id<Note> {
self.id
}
}
fn main() -> DomainResult<()> {
let remote = Arc::new(FakeRemote::with_items([Note {
id: Id::new(1),
title: "Read me".into(),
}]));
let repo = OfflineFirstRepository::new(remote.clone());
println!("First read: {:?}", repo.all()?);
let _ = repo.all()?;
println!("Two reads, {} remote call", remote.calls());
remote.set_online(false);
repo.save(Note {
id: Id::new(2),
title: "Written offline".into(),
})?;
println!(
"Offline: {:?}; queued writes: {}",
repo.all()?,
repo.pending_writes()
);
remote.set_online(true);
println!(
"Synced {} write; remote: {:?}",
repo.sync()?,
remote.items()
);
Ok(())
}Try it
Run the program twice, then run its test with cargo test. Replace the offline client with HttpRemote::new and a server you control, and call sync once it answers.
Checkpoint
The first run finds no notes on disk and the second finds one, because notes.json survived; each run queues one write again. The test turns a 503 answer into a retryable error.
13. Load in the background without losing context
Blocking work must not run on the UI update path. Register the loadable value type, then call commands.entity(owner).load with a closure returning a domain result. Wings runs that closure on Bevy's compute pool and records the lifecycle on WingsLoadable<T>. The entity is the owner of the visible loading state.
The focused example loads a String, marks it as refreshing and displays failures. load.value() keeps the previous successful value while a new operation runs or after it failed, so a refresh does not replace useful content with an empty screen. Use a Changed<WingsLoadable<T>> query when rendering the lifecycle, and react to the result rather than starting new work from the render system.
Version 0.2 adds Loadable bindings to the MVVM crate. Keep a Loadable<T> field in a view model and bind each part of the screen to one phase. bind_loading shows a progress indicator while nothing is there yet, bind_refreshing shows a small indicator while a newer value loads over a shown one, bind_loaded shows content whenever there is a value, bind_failed shows an error area and bind_error_text writes the message. WingsLoadPhase::of names the phase in your own code.
The program below mirrors WingsLoadable into the view model with one small system, so the bindings stay ordinary visibility and text bindings that need nothing beyond register_view_model. When a use case comes from dependency injection, move the resolved service into the closure. A background task does not make a network call instant or guarantee success: design the failure state and a deliberate retry action, and treat the example's artificial delay as something to observe, not to copy.
use bevy::prelude::*;
use bevy_wings::prelude::*;
use std::time::Duration;
#[derive(Component, Default, Clone)]
struct NotesScreen {
notes: Loadable<Vec<String>>,
}
impl WingsViewModel for NotesScreen {}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(WingsUiPlugins)
.register_view_model::<NotesScreen>()
.register_loadable::<Vec<String>>()
.add_systems(Startup, setup)
.add_systems(Update, (start_loading, copy_into_view_model))
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
let spinner = bind_loading(|vm: &NotesScreen| &vm.notes);
let refreshing = bind_refreshing(|vm: &NotesScreen| &vm.notes);
let failed = bind_failed(|vm: &NotesScreen| &vm.notes);
let error = bind_error_text(|vm: &NotesScreen| &vm.notes);
let loaded = bind_loaded(|vm: &NotesScreen| &vm.notes);
let summary = bind_text(|vm: &NotesScreen| match vm.notes.value() {
Some(notes) => format!("{} notes", notes.len()),
None => String::new(),
});
commands.spawn_scene(bsn! {
@WingsScaffold
NotesScreen
Children [
@WingsColumn { @gap: 12.0, @padding: 24.0 }
Children [
@WingsLinearProgress spinner
--
@WingsText { @text: "Refreshing…" } refreshing
--
@WingsText { @color: ColorRole::Error } failed error
--
@WingsText { @role: TypeRole::TitleMedium } loaded summary
--
@WingsButton { @text: "Refresh" }
on(|_: On<Activate>, screens: Query<Entity, With<NotesScreen>>, mut commands: Commands| {
for screen in &screens {
commands.entity(screen).load(fetch_notes);
}
})
]
]
});
}
fn fetch_notes() -> DomainResult<Vec<String>> {
std::thread::sleep(Duration::from_millis(600));
Ok(vec!["Buy milk".into(), "Call Ada".into()])
}
fn start_loading(mut commands: Commands, screens: Query<Entity, Added<NotesScreen>>) {
for screen in &screens {
commands.entity(screen).load(fetch_notes);
}
}
/// The load lifecycle lives on the entity; the view model mirrors it for the bindings.
fn copy_into_view_model(
mut screens: Query<(&WingsLoadable<Vec<String>>, &mut NotesScreen), Changed<WingsLoadable<Vec<String>>>>,
) {
for (load, mut screen) in &mut screens {
screen.notes = load.0.clone();
}
}cargo run --example loading · Complete source and tests
//! Load on a background task, keep previous data while refreshing and show failures.
mod support;
use bevy::prelude::*;
use bevy_wings::prelude::*;
#[derive(Component, Default, Clone)]
struct ResultLabel;
fn main() {
support::run("Wings: background loading", configure);
}
fn configure(app: &mut App) {
app.register_loadable::<String>()
.add_systems(Startup, setup)
.add_systems(Update, render);
}
fn setup(mut commands: Commands) {
commands.spawn_scene(bsn! {
@WingsScaffold
Children [
@WingsColumn { @padding: 32.0, @gap: 16.0 }
Children [
@WingsText { @text: "Background loading", @role: TypeRole::HeadlineMedium }
--
@WingsText { @text: "Press Load" } ResultLabel
--
@WingsButton { @text: "Load / refresh" }
on(|_: On<Activate>, labels: Query<Entity, With<ResultLabel>>, mut commands: Commands| {
for label in &labels {
commands.entity(label).load(|| {
std::thread::sleep(std::time::Duration::from_millis(500));
Ok("Loaded on the compute pool".to_owned())
});
}
})
--
@WingsButton { @text: "Simulate failure", @variant: WingsButtonVariant::Outlined }
on(|_: On<Activate>, labels: Query<Entity, With<ResultLabel>>, mut commands: Commands| {
for label in &labels {
commands.entity(label).load(|| Err::<String, _>(DomainError::Unavailable("Offline".into())));
}
})
]
]
});
}
fn render(mut labels: Query<(&WingsLoadable<String>, &mut Text), Changed<WingsLoadable<String>>>) {
for (load, mut text) in &mut labels {
text.0 = format!(
"{}{}{}",
load.value().map(String::as_str).unwrap_or("No data"),
if load.is_loading() {
" (refreshing...)"
} else {
""
},
load.error()
.map(|error| format!("; {error}"))
.unwrap_or_default(),
);
}
}Try it
In the loading example, load, refresh while the label shows a value, then simulate a failure. In the bindings program, press Refresh after the first load completes.
Checkpoint
The previous value stays visible during refresh and failure. In the bindings program the progress bar shows only during the first load, Refreshing only during later ones, and the error text stays hidden.
14. Wire implementations with dependency injection
Build services at the composition root rather than inside screen constructors. A WingsModule declares values and providers. A singleton is shared; a factory creates a new instance on resolution; a scoped provider shares within one scope. Named providers distinguish several implementations of the same Rust type.
Use trait bindings to provide a concrete data repository behind a domain contract, for example an OfflineFirstRepository over an HttpRemote behind ReadRepository. Parameterized factories accept runtime values, such as the identity of a selected record. Resolve services with WingsDi or Inject in a system. Register navigation and view model providers only after their dependencies have definitions.
Pick a lifetime deliberately. A shared HTTP client is a reasonable singleton. Screen specific editable state generally belongs to the navigation entry's scope. A factory is useful when each operation needs isolated temporary state. Avoid putting per user or per screen mutable values into an application wide singleton.
Wings detects cycles and missing definitions and reports the dependency chain. verify() constructs every definition during a check, so errors appear before a visitor opens the affected screen. Duplicate definitions are rejected unless a module allows overrides. A scope closes when its owning entity is despawned. The example makes the difference between shared and fresh instances visible.
cargo run --example di · Complete source and tests
//! Singleton sharing, factories, scoped services and dependency resolution.
use bevy_wings::prelude::*;
use std::sync::Arc;
struct Config {
greeting: &'static str,
}
struct Greeting {
config: Arc<Config>,
}
struct ScreenState;
fn main() -> Result<(), DiError> {
let di = WingsDi::from_modules([WingsModule::new("example")
.single(|_| Config {
greeting: "Hello from DI",
})
.factory(|r| Greeting { config: r.get() })
.scoped(|_| ScreenState)])?;
assert!(di.verify().is_empty());
let first = di.get::<Greeting>();
let second = di.get::<Greeting>();
assert!(!Arc::ptr_eq(&first, &second));
assert!(Arc::ptr_eq(&first.config, &second.config));
let scope = ScopeId::Id(7);
assert!(Arc::ptr_eq(
&di.scope(scope).get::<ScreenState>(),
&di.scope(scope).get::<ScreenState>()
));
di.close_scope(scope);
println!(
"{}; factories differ, singleton is shared, screen scope closed",
first.config.greeting
);
Ok(())
}Try it
Resolve a singleton twice and a factory twice, then close a scope containing a scoped service. Add an intentionally missing dependency in a test.
Checkpoint
Shared values keep their identity, factory values are distinct, and a bad provider graph fails during verification rather than later in a screen.
16. Add purposeful motion and shader effects
Animation communicates changes rather than substituting for them. Use a tween when you want a known duration and easing curve. Use a spring when the target may change while motion is underway: the spring keeps its velocity when retargeted, so repeated actions remain continuous rather than jumping. Each design brings its own motion tokens; the Apple designs describe springs by response and damping, as SwiftUI does.
An animator targets a component property. The focused example animates ScaleProperty with a spring. WingsProperty supports additional component fields; keyframes, repeat and ping pong cover multi stage effects. Animated visibility can combine fade, scale and slide, ending hidden content with Display::None so it costs nothing in layout. WingsAnimationFinished is triggered on the entity when an animation ends.
The default shaders feature adds WESL UI materials: ripples, shimmer skeletons, circular progress, aurora backgrounds and frosted glass, and in 0.2 Liquid Glass with its backdrop blur, the soft scroll edge, WingsGradientBorderMaterial and WingsNoiseMaterial. The gradient border is a seamless angular gradient as wide as the node's border, still or turning; the noise material draws fractal patterns, from drifting clouds to still film grain. Scenes cannot reach material assets, so attach a material from a system when a marker appears, as the program does.
Every shader is validated with naga in the test suite and its uniform layout is checked against the Rust struct, but a passing test is not a visual check: inspect effects in a real window. Without shaders, skeletons fall back to an opacity pulse, glass to a translucent fill and circular progress is unavailable, so the interface must still communicate its state when decorative effects are absent. Test retargeting while an animation is running and inspect the final value.
use bevy::prelude::*;
use bevy_wings::prelude::*;
/// Nodes that get a material once spawned (scenes cannot reach material assets).
#[derive(Component, Clone, Copy, Default, PartialEq, Eq)]
enum Effect {
#[default]
Clouds,
TurningBorder,
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(WingsUiPlugins)
.add_systems(Startup, setup)
.add_systems(Update, attach_effects)
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
commands.spawn_scene(bsn! {
@WingsScaffold
Children [
@WingsRow { @gap: 12.0, @padding: 24.0 }
Children [
Node { width: px(220), height: px(140), border_radius: BorderRadius::all(px(20)) }
Effect::Clouds
--
Node {
width: px(220),
height: px(140),
border: UiRect::all(px(2)),
border_radius: BorderRadius::all(px(20)),
}
Effect::TurningBorder
]
]
});
}
fn attach_effects(
mut commands: Commands,
added: Query<(Entity, &Effect), Added<Effect>>,
mut noise: ResMut<Assets<WingsNoiseMaterial>>,
mut borders: ResMut<Assets<WingsGradientBorderMaterial>>,
) {
for (entity, effect) in &added {
match effect {
Effect::Clouds => {
let clouds = WingsNoiseMaterial::clouds(Color::srgb(0.08, 0.1, 0.22), Color::srgb(0.42, 0.55, 0.98));
commands.entity(entity).insert(MaterialNode(noise.add(clouds)));
}
Effect::TurningBorder => {
// As wide as the node's border, one turn every four seconds.
let border = WingsGradientBorderMaterial::new(Color::srgb(0.25, 0.55, 1.0), Color::srgb(0.95, 0.35, 0.75))
.turning(0.25);
commands.entity(entity).insert(MaterialNode(borders.add(border)));
}
}
}
}cargo run --example animation · Complete source and tests
//! Click to retarget a spring while preserving its velocity.
mod support;
use bevy::prelude::*;
use bevy_wings::prelude::*;
#[derive(Component, Default, Clone)]
struct AnimatedCard;
fn main() {
support::run("Wings: animation", configure);
}
fn configure(app: &mut App) {
app.add_systems(Startup, setup);
}
fn setup(mut commands: Commands) {
commands.spawn_scene(bsn! {
@WingsScaffold
Children [
@WingsColumn { @padding: 48.0, @gap: 32.0 }
Children [
@WingsText { @text: "Spring retargeting", @role: TypeRole::HeadlineMedium }
--
@WingsCard AnimatedCard UiTransform
Children [ @WingsText { @text: "I keep my velocity when you click again." } ]
--
@WingsButton { @text: "Toggle scale" }
on(|_: On<Activate>, mut commands: Commands, cards: Query<(Entity, &UiTransform), With<AnimatedCard>>| {
for (entity, transform) in &cards {
let scale = if transform.scale.x > 1.1 { 1.0 } else { 1.25 };
commands.entity(entity).animate::<ScaleProperty>(Vec2::splat(scale), AnimationSpec::spring());
}
})
]
]
});
}Try it
Toggle the animation target while the card is moving. In the effects program, change turning(0.25) to turning(1.0) and try WingsNoiseMaterial::grain instead of clouds.
Checkpoint
Motion retargets continuously. The border goes from one turn every four seconds to one per second, and the grain stays still where the clouds drifted.
17. Test behavior and ship a reproducible application
Build tests around behavior visible at the framework boundary. A domain test asserts validation and repository outcomes. A data test controls time and remote availability. A UI test triggers an event, advances the app and inspects components. This is more useful than asserting that a function was called.
The focused examples contain small integration tests next to the runnable code: the MVVM test triggers Activate and checks the text, the navigation test pushes and pops a destination and checks which labels remain, and the loading test waits through a bounded sequence of updates. The gallery has a headless test that runs the complete app with navigation, dependency injection, MVVM and both data layers. Headless tests use MinimalPlugins and WingsWidgetsPlugin::headless().
Wings systems run in ten ordered WingsUiSystems sets, from WingsUiSystems::Input to WingsUiSystems::Animate. WingsUiSystems::Skin is new in 0.2 and runs between Responsive and Modifier, so exhaustive matches on WingsUiSystems need the new arm. Put application systems that mutate view models in WingsUiSystems::ViewModel so bindings observe them in the same frame. If a value appears one frame late, examine ordering before adding another system.
Two tools in 0.2 cover what headless tests cannot see. cargo bench -p bevy_wings_ui_widgets --bench stress measures spawning, idle frames, theme switches and re-skinning with thousands of widgets. scripts/visual-regression.py renders the gallery in every design, light and dark, at phone and desktop sizes, offscreen on a GPU with a fixed frame time, and compares the screenshots with baselines kept per platform, because fonts and drivers differ. The gallery's WINGS_CAPTURE mode shows how an app can do the same.
Run formatting, Clippy, unit, integration and example tests and documentation tests for every configuration you support, including one without default features. Cargo's --all-targets does not include documentation tests, so run them separately, and keep Cargo.lock for reproducible --locked checks. A release also needs real window checks of input, narrow and wide layouts, every design you ship, safe areas on real devices, and keyboard and gamepad navigation.
cargo fmt --all -- --check
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
cargo test --workspace --all-targets --all-features --locked
cargo test --workspace --doc --all-features --locked
cargo test --workspace --exclude wings-gallery --all-targets --no-default-features --locked
cargo bench -p bevy_wings_ui_widgets --bench stress
python3 scripts/visual-regression.pyTry it
Run the commands in the checkout, then capture one gallery screen: WINGS_DESIGN=ios WINGS_CAPTURE=shot.png cargo run -p wings-gallery. Extend the test in examples/mvvm.rs with a reset assertion after incrementing.
Checkpoint
Both feature configurations pass, shot.png shows the iOS design, and the extended test proves that the intent changes the model and the bound text follows it. A window check confirms the visual presentation separately.