Widgets
How ember widgets are built, the rules every widget follows, and the widgets whose behaviour is worth knowing before you use or change them.
renzora_ember is the one UI crate. The editor builds its panels from it and a shipped game builds its menus and HUD from it, so its widgets are runtime code: EmberRuntimePlugin installs them in every session, and EmberPlugin adds docking on top for the editor.
The builder-function pattern
A widget is a pub fn that takes &mut Commands (and fonts, when it draws text), spawns ordinary bevy_ui entities and returns the root Entity. There is no retained widget object and no layout pass beyond Bevy's own.
use bevy::prelude::*;
use renzora_ember::font::{ui_font, EmberFonts};
use renzora_ember::theme::{accent, border, close_red, rgb};
/// A labelled pill that shows a status colour.
pub fn status_pill(commands: &mut Commands, fonts: &EmberFonts, label: &str, ok: bool) -> Entity {
let color = if ok { accent() } else { close_red() };
let pill = commands
.spawn((
Node {
align_items: AlignItems::Center,
padding: UiRect::axes(Val::Px(10.0), Val::Px(4.0)),
border: UiRect::all(Val::Px(1.0)),
border_radius: BorderRadius::all(Val::Px(10.0)),
..default()
},
BorderColor::all(rgb(border())),
Name::new("status-pill"),
))
.id();
let text = commands
.spawn((Text::new(label), ui_font(&fonts.ui, 11.0), TextColor(rgb(color))))
.id();
commands.entity(pill).add_child(text);
pill
}
The conventions every built-in widget follows:
- Colours come from the palette.
renzora_ember::themeexposes accessors (accent(),border(),panel_bg(),text_primary(),text_muted()and the rest) that return(u8, u8, u8);rgb(..)turns one into aColor. They are read at spawn time; see Theming for what that means on a theme switch. - Text takes a font from
EmberFonts.ui_font(&fonts.ui, size)builds aTextFontwith the user's UI scale applied;icon_text(commands, &fonts.phosphor, name, color, size)spawns a Phosphor glyph by kebab-case name. - Give nodes a
Name. Markup bindings, the dock and the debugging tools find nodes by it. - Interaction is
UiInteraction, not Bevy'sInteraction. Bevy 0.20 deprecatedInteractionand the focus system behind it, so ember derivesrenzora_ember::UiInteraction(Pressed,Hovered,None) from picking. Read it the same way (Changed<UiInteraction>). A query for Bevy'sInteractionon an ember widget never sees a press. Bevy'sButtonis private in 0.20; game UI marks buttons with ember'sUiButton. - Hidden text is cheap. ember keeps text under a
Display::Noneancestor from being re-measured when the UI scale changes, and frees glyph atlases that no laid-out text has used for about ten seconds. Code that reads glyphs from an atlas must copy them out while it builds.
To use a builder in a panel, call it from the build closure of register_panel_content, which hands you (&mut Commands, &EmberFonts). See Editor Panels.
Blocking the pointer
A widget that owns a press needs an explicit BLOCK. Blocking is Bevy's Pickable, and ember starts every UI node and text span as renzora_ember::interaction::PASS_THROUGH: hit-testable, but not blocking. A press lands on every node under the cursor, front to back, until one blocks, and every direct hit goes Pressed. A plain button therefore hands its press to whatever is behind it, its own ancestors included.
use renzora_ember::interaction::BLOCK;
use renzora_ember::UiInteraction;
commands.spawn((
Node { /* ... */ ..default() },
UiInteraction::default(),
BLOCK, // without this, the row or card behind also sees the press
MyButton,
));
Pickable::IGNORE takes a node out of picking altogether. ResizeHandle and UiButton insert BLOCK themselves. The failure this prevents is concrete: a launcher row's remove button once removed a recent project and also opened it, because the row behind it is the "open" hit box.
What should not get BLOCK:
- Layout scaffolding. Wrappers, spacers, and the text and icons inside a button stay
PASS_THROUGH, which is how a click on a button's label reaches the button. - Hover.
Hoveredfollows picking's hover, which counts descendants the way CSS:hoverdoes, so a row stays hovered while the pointer is on a button inside it.UiCursor::cursor_overfollows the same rule.UiCursorreplaces Bevy's removedRelativeCursorPosition; itsnormalizedposition is filled outside the node too, for drags that run past an edge. - The cursor icon. Several nodes are hovered at once when they overlap, so
apply_cursor_iconresolvesHoverCursorfrom the topmost hovered node byComputedStackIndex. AddBLOCKbecause the widget owns its press, not to win the cursor.
correct_pointer_state (in ember's crate root) runs after UiSystems::Focus and clears UiInteraction and cursor_over for anything clipped by a scroll area or covered by an overlay, so both can be trusted in Update.
The widget library
renzora_ember::widgets holds about a hundred modules, each a builder (or several) plus the systems that animate it; use renzora_ember::widgets::*; brings them in. The gallery_* panels in Add Panel show them live in the current theme. A selection:
| Category | Builders |
|---|---|
| Buttons | button, icon_button, icon_label_button |
| Toggles | checkbox, toggle, toggle_switch, radio_group, segmented |
| Numbers | slider, drag_value, spin_slider, number_stepper, knob, fader, fader_horizontal, range, xy_pad |
| Selection | dropdown, dropdown_compact, dropdown_with_icons, multi_select, tags_input, search_list |
| Text | text_input, password_input, textarea, floating_label, input_group |
| Colour and curves | color_picker, the gradient and curve editors |
| Data | gauge, line_chart, bar_chart, sparkline, line_chart_live, waveform, vu_meter, table, tree_node, timeline_view |
| Containers | card, section, accordion_section, collapsible, tabs, divider, scroll_view, scroll_area |
| Pickers | folder_picker, folder_new_button, font_picker, asset_slot |
| Overlays | modal, popover, tooltip, popup_panel, screen_menu, menu_submenu, context_menu, toast, alert |
| Editors | node_graph, node_graph_view, code_editor, property_row, vec3_edit |
| Feedback | progress, spinner, skeleton |
let b = button(commands, &fonts.ui, "Apply");
let c = checkbox(commands, true);
let s = slider(commands, 0.5); // 0..1
let g = gauge(commands, fonts, 0.8);
let dd = dropdown(commands, fonts, &["Low", "Medium", "High"], 1);
Interactive widgets keep their value in a Bound<T> component (Bound<f32> on a slider, Bound<bool> on a checkbox, Bound<usize> on a dropdown). bind_2way(commands, widget, get, set) connects that to a piece of state in both directions; see Reactivity.
Faders and meters
fader and vu_meter are vertical; fader_horizontal and vu_meter_bound_horizontal are the same controls laid along x. Orientation is a field on the widget's component that picks every dimension, the drag axis and the fill's anchor edge, so they are one control mirrored rather than two. Fills and hit-testing are percentages, so stretching the travel axis (flex_grow with an Auto length) works at any size.
Depth inside panel content
Some widgets need GlobalZIndex: node_graph_view puts cables in viewport space and nodes in the pan/zoom canvas, so a cable has to sit between children of a sibling subtree, which local ZIndex cannot express. But GlobalZIndex is global, and the bottom panel sits at 100, so a depth below 100 vanishes under the bottom panel's background the moment a user docks that panel there.
renzora_ember::stacking::ZTier gives a part a depth relative to its widget, and z_tier_rebase resolves it against whatever context the widget ends up in:
commands.spawn((Node { /* ... */ ..default() }, ZTier(10), GlobalZIndex(10)));
Spawn both: GlobalZIndex is the value used until the first rebase and the component the rebase writes. To change a depth at runtime, write ZTier from a system ordered .before(ZTierSet); a direct GlobalZIndex write is overwritten next frame.
Genuinely floating surfaces (menus, dropdowns, modals, drag ghosts) keep their absolute bands above everything. A full-window modal scrim uses stacking::MODAL_SCRIM_Z (300): above the bottom panel, below the dropdowns and menus that open over it.
Two copies of one panel
Add Panel does not hide panels that are already open, so any panel can be mounted twice. Everything a panel builds must therefore be per instance:
- A toolbar button names what it drives. A bare marker (
struct FitBtn;) queried by a system acts on every instance at once. Store the target on the marker (ViewOpBtn { op, view }) and build the toolbar after the thing it controls. View state (pan, zoom, per-view selection) is per instance; document state (the graph itself) is shared, so both copies show the same edit. - Gate on
UiCursor::cursor_over. It is already cleared for anything an overlay covers. Do not also checkPointerOverOverlayin a handler that has a node to ask: the bottom panel is itself an overlay surface, so that resource reads true for a widget docked there and the widget goes dead. It is for handlers with no UI rect of their own (a viewport raycast).
Floating UI
Tooltips
Insert renzora_ember::widgets::HoverTooltip::new("Label") on any entity with UiInteraction. Tooltips are one shared, parentless bubble with Pickable::IGNORE, so nothing clips it and it never takes hover. Do not spawn a bubble as a child of your widget: bevy_ui clips absolutely positioned children by every clipping ancestor, and GlobalZIndex changes paint order, not clipping.
Dropdowns and popups
- A choice:
dropdown(commands, fonts, &options, selected), ordropdown_compact(.., width)for a toolbar row.dropdown_with_iconstakes(icon, label)pairs. To hide options that do not apply, flipNode.displayon theEmberDropdownOptionrows of your box; the value stays a stable index. - A panel of mixed content:
popup_panel(commands, &rows)for the surface,icon_popup_trigger(commands, fonts, icon, panel)for an icon-and-caret trigger, andpopup_anchor(commands, trigger, panel)for the wrapper you add to your layout.popup_panel_aligned(.., PopupAlign::Left)when the trigger is at the start of a strip.popover,icon_popoverandlabeled_icon_popoverwrap the same parts in one call.
Use these rather than hand-rolling. Ember tags every popup panel and dropdown menu as an OverlaySurface, which is what stops clicks, scrolls and hover leaking through to what is behind it; a hand-rolled panel lets a click on its rows also land in the viewport underneath. If you must build a floating surface yourself, give it OverlaySurface and a UiCursor.
Author a popup opening downward (top: Val::Percent(100.0)). Ember flips it above the trigger when below is where the room is not, re-deciding every frame it is open, and "room" is measured against the clip rect the trigger is in, not the window. Never put Overflow::clip() on a trigger: the panel is its child, so the popup opens inside the trigger's own box and is never seen. Clip the label instead (min_width: 0, Overflow::clip(), TextLayout::no_wrap()).
Menus and submenus
A right-click menu is screen_menu(commands, x, y): ember keeps it on screen, blocks pass-through and closes it on an outside click. Fill the returned entity with menu_item, menu_item_styled, menu_header and menu_sep; each item carries a Fn(&mut World) that runs on click.
let menu = screen_menu(&mut commands, cursor.x, cursor.y);
let (row, content) = menu_submenu(&mut commands, &fonts, "lightbulb", "Lighting");
let item = menu_item(&mut commands, &fonts, "lightbulb", "Point Light", move |w: &mut World| spawn_light(w));
commands.entity(content).add_children(&[item]);
commands.entity(menu).add_children(&[row]);
menu_submenu returns (row, content); submenus nest to any depth and flip sides at the window edge. screen_menu_parts and menu_submenu_parts also return the card, for a menu painted on a different surface. Row metrics are shared constants in widgets/popup.rs (MENU_ICON, MENU_TEXT, MENU_PAD_X, MENU_PAD_Y, MENU_GAP).
Rules for this machinery:
- Never order a system against
screen_menu_dismiss. Any.before/.aftermakes Bevy insert anApplyDeferredbefore it, which flushes a menu a panel just spawned for this very press, and dismiss then closes it on the frame it appeared. - A submenu panel is a parentless root, despawned by an
on_removehook on its row. As a child of the row it would be clipped by the menu's scroll area. - Read a UI node's placement from
UiGlobalTransform, neverGlobalTransform. Bevy's layout writes the former (anAffine2whose translation is the node's centre in physical pixels; multiply byComputedNode::inverse_scale_factor()for logical pixels). A UI node'sGlobalTransformstays at the origin.
Draggable floating cards
drag_grip(commands, &fonts.phosphor, target) spawns a six-dot grip that drags target. Insert DragHandle::new(target) on a whole title bar instead, and .with_margin(px) to change how much of the card stays on screen (24 px by default). It differs from moving a node by hand in three ways: it reads the card's real rect from UiGlobalTransform and switches it from right/bottom to left/top anchoring, so the first drag does not jump; it clamps the card on screen so its close button stays reachable; and it ends on button release, not on UiInteraction, so a fast drag is not dropped. Buttons inside a draggable header need BLOCK.
Strips and toolbars
Capped tab strips: overflow_strip
overflow_strip(commands, budget, name) returns (row, items): a horizontal strip that folds items it cannot fit into a caret menu at its end.
let (row, items) = overflow_strip(commands, OverflowBudget::Fill { measure: bar, reserve: 66.0 }, "my-tabs");
keyed_list(commands, items, my_tab_snapshot);
// On each item, so it can be reached once folded:
commands.entity(tab).insert(OverflowEntry::new("file", name, move |w| activate(w, id)));
commands.entity(active_tab).insert(OverflowKeep); // never folds
OverflowBudget::Fill { measure, reserve } takes the width measure was laid out to, less reserve; OverflowBudget::Fixed(px) is a constant cap for a strip with no container to measure. The fold is decided from each item's last width measured while visible, cached on the item and by OverflowEntry::label, because a hidden node measures zero and deciding from live layout would oscillate. A new item is spawned absolutely positioned and hidden so it can be measured without pushing its neighbours. OverflowEntry::on_drag makes the folded row draggable back out of the menu, and icon_color keeps an item's icon colour in the menu.
Wrapping toolbars: arrange_row
arrange_row(commands, name) is a toolbar row that wraps instead of hiding what does not fit, and whose groups can be dragged into another order. The in-viewport tool strip is one.
let bar = arrange_row(commands, "vp-toolbar");
let holders = arrange_row_items(commands, fonts, bar, &[(tools, "tools"), (snaps, "snaps")]);
Each group gets a holder with a grip, so a group moves and wraps whole; pass clusters, not single buttons. The row publishes its order as ArrangeOrder(Vec<String>) after every drop; write a saved list back to restore it. Two rules it depends on: the dragged holder stays parented (orphaning a live node mid-frame panics taffy), and nothing above it may clip.
Pickers and editors
Folder picker
folder_picker(commands, fonts, root, selected, max_depth) shows the project's folders as a scrolling list and flex-grows to fill an overlay body. The pick lives in the FolderPick resource (read it with FolderPick::path()), because a picker only appears in a modal, so one is on screen at a time and a shared resource lets the selected-row highlight be a plain binding.
folder_new_button(commands, fonts, picker) returns a parentless New Folder button for the overlay's button row. It creates the folder at once (New Folder, New Folder 1, ...), selects it, and opens its name for editing in place; Enter keeps the typed name, Escape keeps the generated one. While a rename is open, folder_rename_keys consumes Enter and Escape in PreUpdate, ahead of form_enter_submit and overlay_dismiss. The walk skips dot-folders, target/ and node_modules/, and stops at 300 rows.
Code editor
code_editor is a monospace, syntax-highlighted editable view that owns no document. The host attaches a CodeBindingSpec with bind_code: closures for the document identity (doc_key), load, store, make_highlighter, and optional font_size, word_wrap, show_whitespace, auto_close and line_comment. renzora_code_editor wires it to its open files; its highlighters cover Rust, WGSL and WESL, TOML, JSON, BSN, HTML and others, chosen by extension.
- Rendering is incremental.
code_renderhashes everything a row draws and leaves a row with an unchanged hash completely alone, so a keystroke rebuilds one row instead of the whole view. - The advance is measured. A hidden probe reads the mono font's real laid-out width, so carets line up for any monospace font.
- It is monospace on purpose. Bevy's positioned glyphs do not carry their source character index, so a proportional font cannot be mapped from a click back to a column.
- Colours come from the theme's
[syntax]section throughSyntaxPalette; see Theming.
Text inputs and forms
text_input and password_input are single-line fields with full caret editing, drag selection and Ctrl+C/X/V/A; textarea shares the EmberTextInput component and keeps Enter as a newline. A panel may write EmberTextInput.value directly (to clear it after a send) and the displayed text follows.
IME input. While an ember input is focused, ember turns on the window's IME and places the candidate window at the caret. Text being composed is drawn at the caret but is not in EmberTextInput.value until committed (the in-progress text is the ImeComposition resource), and a key the IME consumed has its just_pressed cleared, so finishing a composition with Enter submits no form. wasm takes no IME input.
Forms. Insert EmberForm { submit } on a container holding inputs and a submit button:
let input = text_input(commands, &fonts.ui, "Say something...", "");
let send = button(commands, &fonts.ui, "Send");
commands.entity(row).insert(EmberForm { submit: send }).add_children(&[input, send]);
Enter in a single-line input writes UiInteraction::Pressed on submit in PreUpdate, so the button's existing click handler fires with no separate event. Tab and Shift+Tab cycle through the form's inputs and drag_value fields; without the marker, Tab uses the smallest subtree holding at least two inputs.
Numeric fields
- A
drag_valuewith aDragRangedraws a fill bar and maps its own width to the range, so one pixel of drag is one pixel of bar. Shift scrubs at a tenth of the rate. - Clicking a field selects the whole value; the first keystroke replaces it.
- A plain mouse wheel always scrolls the enclosing scroll area. Only Shift+wheel scrubs the value, so scrolling a panel never silently changes a number under the pointer.
Scroll areas
scroll_view, scroll_view_bar, scroll_view_pinned, scroll_view_xy and scroll_area wrap content in a smooth-scrolling view. The position lives on the entity, so a view that is despawned and rebuilt (every panel on a tab switch, all chrome on a theme switch) starts at the top. To keep it, use a keyed variant with a key unique to that list:
let s = scroll_view_keyed(commands, content, "hierarchy");
let m = scroll_area_keyed(commands, content, 260.0, "status-theme-menu");
The offset is saved in ScrollMemory and restored once the content is laid out. The wheel, holding the arrow keys while hovering, and middle-drag all scroll the frontmost scroll area under the cursor, scaled by the ScrollConfig resource's speed.
Themed widgets: Styled and Role
Instead of baking colours in at spawn, a widget can carry renzora_ember::style::Styled naming a Role. apply_theme repaints it from the active style::Theme whenever the theme or the widget's Styled changes, with no rebuild. Your interaction system sets Styled.state:
use renzora_ember::style::{Role, Styled, WidgetState};
use renzora_ember::UiInteraction;
fn my_button_state(mut q: Query<(&UiInteraction, &mut Styled), (With<MyButton>, Changed<UiInteraction>)>) {
for (i, mut s) in &mut q {
s.state = match i {
UiInteraction::Pressed => WidgetState::Pressed,
UiInteraction::Hovered => WidgetState::Hover,
UiInteraction::None => WidgetState::Normal,
};
}
}
The roles, the token fields and the theme file format are on Theming.
GPU-drawn widgets
Gauges, knobs, charts and waveforms are fragment shaders on bevy_ui MaterialNodes, not stacks of rectangles. Ember has three UiMaterials, each with an embedded WESL shader:
| Material | Shader | Draws |
|---|---|---|
ArcMaterial | widgets/gauge/gauge.wesl | gauge, knob, markup vector="arc" and speedometer |
ChartMaterial | widgets/chart/chart.wesl | line_chart, sparkline, line_chart_live, markup vector="line" |
WaveMaterial | widgets/waveform/waveform.wesl | waveform, markup vector="wave" |
Each material's plugin returns early if its UiMaterialPlugin is already added, because both WidgetsPlugin and the markup runtime register it and adding a UiMaterialPlugin twice panics.
Writing one
use bevy::asset::Asset;
use bevy::prelude::*;
use bevy::reflect::TypePath;
use bevy::render::render_resource::AsBindGroup;
use bevy::shader::ShaderRef;
use bevy::ui_render::prelude::{MaterialNode, UiMaterial};
use bevy::ui_render::UiMaterialPlugin;
#[derive(Asset, TypePath, AsBindGroup, Clone)]
pub struct RingMaterial {
#[uniform(0)]
pub color: Vec4,
#[uniform(0)]
pub params: Vec4, // x = progress 0..1
}
impl UiMaterial for RingMaterial {
fn fragment_shader() -> ShaderRef {
"embedded://my_crate/ring.wesl".into()
}
}
pub struct RingPlugin;
impl Plugin for RingPlugin {
fn build(&self, app: &mut App) {
if app.is_plugin_added::<UiMaterialPlugin<RingMaterial>>() {
return;
}
bevy::asset::embedded_asset!(app, "ring.wesl");
app.add_plugins(UiMaterialPlugin::<RingMaterial>::default());
}
}
// ring.wesl
import bevy_ui_render::ui_vertex_output::UiVertexOutput;
struct Ring { color: vec4<f32>, params: vec4<f32> };
@group(1) @binding(0) var<uniform> u: Ring;
@fragment
fn fragment(in: UiVertexOutput) -> @location(0) vec4<f32> {
let p = in.uv * in.size - in.size * 0.5;
let r = length(p) / (min(in.size.x, in.size.y) * 0.5);
if (r < 0.85 || r > 1.0) { discard; }
return vec4<f32>(u.color.rgb, u.color.a * u.params.x);
}
Spawn a node with MaterialNode(materials.add(RingMaterial { .. })) and animate it by mutating the material through its handle, as arc_sync does; that touches only the uniform buffer. Shaders are WESL; see Shaders.
Markup widgets
Game UI can also be written as .html markup, which the markup loader (renzora_ember::markup) turns into the same bevy_ui entities; authoring it is covered in Game UI. Two parts of it map onto the widgets above.
Vector widgets. vector="..." on a node stamps a VectorSpec, and its {{ path }} attributes are re-bound each frame:
vector= | Aliases | Drawn with |
|---|---|---|
arc | gauge, ring | ArcMaterial, with an optional centred readout |
bars | bar | one bevy_ui rectangle per value |
line | chart | ChartMaterial |
wave | waveform | WaveMaterial |
speedometer | dial | ArcMaterial plus text ticks, labels, a needle and a readout |
<node width="120px" height="120px" vector="gauge" value="{{ speed }}" min="0" max="240"
readout="{{ speed }}" unit="km/h" />
Interaction attributes (renzora_ember::markup::widgets). These write through the scripting layer's reflection queue:
| Attribute | Component | Behaviour |
|---|---|---|
toggle="Path.bool" | Toggle | A click flips the bound boolean. |
drag_value="Path.num" drag_min drag_max | DragValue | A horizontal drag sets the bound number. |
fill="Path.num" fill_min fill_max | ValueFill | The node's width follows the value's fraction of the range. |
toggles="name" | Disclose | A click shows or hides the entity with that Name. |
Keeping an unused widget free
A widget's systems run in every editor and every game whether or not the widget is on screen, and each system the scheduler starts costs something even when it finds nothing. The built-in widgets gate their systems in groups, on the one thing that can give them work:
- The widget existing:
(knob_drag, knob_apply).run_if(any_with_component::<EmberKnob>), for systems that only touch the widget's own entities. - The pointer doing something: a click handler whose trigger is a
Changed<UiInteraction>query joinsrenzora_ember::UiInteractionReactions. That set runs only on a frame where someUiInteractionchanged or a key, mouse or gamepad button went down or up (keyboard and gamepad navigation writePressedduringUpdate, so input has to count).
app.add_systems(Update, (settings_btn_click, palette_btn_click).in_set(UiInteractionReactions));
Put a condition on the tuple, not on each system, so it is checked once. Three kinds of system stay ungated:
- one that resets a shared flag every frame, which a gate would leave stuck;
- one holding a drag in a
Localthat must see the release even after its widget is gone; - one reading a message stream such as
KeyboardInputorMouseWheel, because a gated reader resumes on messages from before its widget existed (a shortcut that opens a search box would type its own key into it).