ui
Garnet UI
Use Garnet::UI::Messages to format labels with a configured fallback catalog. For example, format("fr-CA", "menu.play") checks Canadian French, French and the configured default. Pass named arguments as a string hash for placeholders such as {player}. Keep the active locale in a signal to update reactive labels when it changes.
locale = Garnet::Signals::State.new("en")
caption = Garnet::Signals::Computed.new { messages.format(locale.get, "menu.play") }
Garnet::UI::Components.mount(parent) do |scope|
Garnet::UI::Widgets.label(scope, caption, family)
end
locale.set("fr-CA")
The next layout uses the updated caption for text measurement, drawing, and accessibility. Closing the scope releases the binding. Dialogue and headless code can use the same catalog directly through Garnet Localization.
The GLFW adapter routes D-pad focus, A activation and B dismissal alongside the keyboard and pointer paths.
Use TextField.new(..., multiline: true) for a wrapping editor with grapheme-safe navigation and scrolling. Use Widgets.virtual_list(row_heights, height) to recycle visible rows with precomputed variable heights. Fixed heights continue to use the count and row-height overload.
garnet-ui/ios publishes the router's semantic snapshot as UIKit accessibility elements and routes activation back to the presented control. Link ui/native/ios_bridge.m with the reusable iOS host. Call IOSBridge#open_text(buffer, bounds) to attach a UIKit editor in view points. The editor delivers committed text, selections, and IME marked text to the shared buffer. Close the bridge before releasing its router.
Code-first flexbox widgets built from ordinary scene entities and components. garnet-layout stays independently usable. UI has no renderer or host dependency; applications choose their font provider and supply input in their layout units.
Build prerequisites are a C++20 compiler and Make for Yoga, plus pkg-config, FriBidi and libunibreak for the text-layout dependency. The interactive example also needs GLFW/OpenGL and HarfBuzz 14+; it uses the pinned OFL font fixtures from harfbuzz/testing. HarfBuzz is a development/example provider, not a required UI runtime provider; applications can supply another Text::Font implementation.
require "garnet-ui"
alias U = Garnet::UI
alias L = Garnet::Layout
panel = U::Widgets.panel(U::Style.new(layout: L::Style.new(padding: 12_f32)))
button = U::Widgets.button(style: U::Style.new(
layout: L::Style.new(width: L::Length.points(140), height: L::Length.points(40)),
background: Garnet::Color.new(0.1_f32, 0.3_f32, 0.5_f32, 1_f32)))
panel << button
button[U::Interactive].state.on(:click) { |_event| puts "Play" }
view = U::Root.new(panel)
input = U::Router.new
frame = view.layout(640_f32, 480_f32)
# Render/present frame.drawing with the chosen renderer, then:
input.present(frame)
input.move(20_f32, 20_f32)
input.down
input.up
# On shutdown: input.close; view.close
Widgets.label(Label.new(text, family, size)) adds shaped, measured text. Pass a Label to Widgets.button for a caption. Label content, font, size and color are immutable; replace the Caption component to update them. Each label retains up to eight width-constrained paragraphs/drawings, so unchanged text reuses vector primitives. A captioned node is a measured leaf; compose separate caption entities inside containers when children are required. The standalone examples/headless.cr works without a font provider, window or renderer.
Scene and layout ownership
Every live descendant under a UI root requires a UI Style. Game components can coexist on these same entities. The existing entity hierarchy is the only hierarchy authority. Each layout derives a temporary Yoga tree, then publishes Box, scene Placement, Visibility, graphics Picture and optional rectangle Clip components. UI owns those output components and rewrites them every layout, so layout raises ArgumentError when it finds one the game set instead of silently replacing it. Position nodes with Layout::Style (absolute: true, x:, y:), hide them with Style visible: false or display: false, and author the separate scene Transform for animation; effective placement is T(layout) * visual_transform. To draw on a UI node, give it a UI::Picture (or build it with Widgets.picture(drawing, style)) and replace that component whenever the drawing changes; ContentPaint draws with a callback instead. Padding/border is included once, in content measurement and painting.
layout.display: false removes a subtree from layout/render/input; visible: false keeps layout space but hides painting/input. enabled: false disables input through a subtree without changing layout or painting. Rectangle clips affect descendants in both rendering and hit testing, including rotations and nonuniform scales. Singular transforms are not hittable. Input is bounded by the presented viewport. Custom masks, live viewports/surfaces/patterns and authored non-UI clips are rejected within this UI slice rather than routed against incorrect geometry. Other drawable components may coexist, but hit regions remain layout rectangles rather than pixel-alpha tests.
Roots and routers belong to one execution owner. Layout currently rebuilds the small native layout tree and scene pictures each call; it is not an incremental layout engine. Prior frames/drawings remain immutable. Root#close cancels owned handlers; removed entities are cleaned up on layout or input synchronization.
Input and handler lifetime
Publish a frame to the router only after presenting its drawing. Pointer positions are in that frame's coordinate system. For HiDPI, the menu example uses window units for layout/input and scales the drawing into framebuffer pixels. The frame retains transform, clip and stacking data. Changes to layout, visual transforms or Z do not change hit testing until a new frame is presented; current destruction, detachment, disabled and hidden state is checked before every listener invocation.
Interaction#on(kind, capture: false) returns a subscription; close it to detach the listener (cancel remains as a deprecated alias). Pointer down/up/move and click dispatch through capture, target and bubble phases with target, current_target, world x/y and phase. Listener lists and the route are snapshotted for an event. Additions start on the next event, and cancelled listeners are skipped. stop_propagation preserves remaining listeners on the current target; stop_immediate_propagation also stops them. prevent_default cancels pointer-down focus/activation or a pointer-up click. event.defer { ... } applies changes after the complete input action. Direct structural edits are allowed but invalidate pending routes immediately.
There is one primary pointer. Down implicitly captures its owner until up or cancellation; releasing elsewhere does not click. Hover signals follow the actual hit path while captured moves/up still route to the pressed owner. tab(reverse: true) cycles focus through eligible entries in paint order; activate invokes the same click action. The menu maps Tab/Shift-Tab and Enter/Space to these calls. Focus/hover notifications are target-only. blur cancels pointer capture, focus and hover on host focus loss. Disabled owners lose interaction state; dead/detached owners and closed views cancel callbacks. Reparenting within the same root cancels stale focus/capture routes but preserves the live widget's handlers for the next presented frame. Routing is synchronous and not reentrant; use defer for nested input work.
hovered, pressed and focused are typed signals written by the router. Application-owned tracks/tweens can consume them; UI owns no clock or update loop. Callback exceptions propagate to the caller after dispatch cleanup. No global input hooks or native callbacks are installed by requiring this shard.
Labels retain paragraph geometry through the text-layout primitive's bounded preparation cache. Panel backgrounds and rectangular clips use the existing shared quad with draw-local size transforms; changing paint or rectangle size does not allocate new mesh streams. Scene placement and hit-test regions still come from the current layout frame.
Run and validation
From the workspace root:
scripts/check-composition unit
scripts/check-composition example-ui
"${TMPDIR:-/tmp}/garnet-ui-menu"
GARNET_UI_SMOKE=1 "${TMPDIR:-/tmp}/garnet-ui-menu"
GARNET_UI_BENCHMARK_FRAMES=300 "${TMPDIR:-/tmp}/garnet-ui-menu"
The GLFW/OpenGL menu is resizable, has measured labels and buttons, hover/press and focus transitions driven by garnet-animation, pointer handlers, and keyboard activation. Smoke mode resizes, performs a pointer click and keyboard activation, and asserts two actions across 16 presented frames. These smoke actions drive the public router; native OS input injection is not claimed. Benchmark mode uses an invisible window, reports frame-time percentiles after five warmup frames, and emits geometry/scratch allocation counters every 60 frames. Its timing covers layout through renderer collection, including render, presentation and swap. Use at least six frames and run it separately from smoke. GARNET_UI_CAPTURE=/tmp/menu.ppm optionally records a GPU readback at frame 12.
The shared gl, gles, metal, vulkan composition modes verify the same UI drawing, text, placement, clipping, retained output and input correspondence. The native interactive example uses GLFW/GL; Metal/Vulkan host input examples remain future adapters. The headless example verifies use without a font provider. The original menu fixture covers panels, labels and buttons. The sections below cover the current scroll, text editing, modal routing, accessibility snapshots and widget APIs.
Validation: 219 workspace unit examples and 56 shared rendering examples on each of GL/GLES, Metal and Vulkan pass (Vulkan validation enabled). Native menu smoke and HiDPI GPU readback inspection pass. On the unlocked desktop, native pointer activation, Tab/Enter activation and corner resizing were verified on-screen; text rewrapped and the buttons moved into multiple flex rows. Earlier automation attach failures no longer limit these specific input checks. This is not an accessibility or non-GL input claim.
A reported lag led to geometry retention fixes. The final 300-frame menu benchmark measured a 23.5 ms median in a default development build, with GPU stream count constant at 567. See the investigation for matched baseline measurements, scope, cold-frame timing and remaining transient-target allocation costs. The native linker may emit a duplicate -lc++ warning when multiple C++ adapters are linked together.
Vertical scroll views
Widgets.scroll_view(layout: ...) creates a panel with a Scroll component. The panel clips its children and translates their layout placement by the current scroll offset. Give overflowing children shrink: 0_f32 when their intended height should exceed the viewport. The extent comes from immediate child layout boxes. Frame#box still reports layout coordinates, while Frame#scroll_limit reports the maximum offset for that frame.
Send router.wheel(x, y, delta_y) in logical coordinates. A positive delta moves toward later items. Nested views consume the delta from the innermost visible view outward. Layout clamps the offset again after resizing or content changes. Publish the resulting frame after presentation to keep rendered positions and pointer routing synchronized.
Build the GLFW example with scripts/check-composition example-scroll and run "${TMPDIR:-/tmp}/garnet-ui-scroll". Its GLFW wheel callback forwards vertical input and its items respond to clicks. GARNET_SCROLL_SMOKE=1 exercises the router with a scripted wheel delta and two presented frames.
Text entry
Widgets.text_field combines a single-line TextField and a focusable interaction component. Its TextBuffer keeps cursor and selection offsets on Unicode grapheme boundaries. It supports pointer selection, logical movement, Home/End, deletion, select all, and bounded undo and redo. The router accepts committed text and preedit updates from the host, and cancels composition on focus loss. Clipboard adapters use copy_text and cut_text to write the focused selection and can paste through text_input.
The GLFW adapter maps native pointer, wheel, key, focus and committed-character callbacks into the same router.
Touch, focus, and semantics
An adapter can call router.touch(id, phase, x, y) in logical coordinates. The router tracks one primary touch and reports its ID on pointer events. Cancel releases capture and prevents a click. Directional focus uses the presented layout through router.navigate(direction). frame.accessibility publishes the clipped bounds, roles, labels, values, and focus state for host accessibility adapters.
Styling and retained components
Attach UI::BoxStyle to a panel, label, or control for solid and gradient fills, theme colors, rounded corners, per-side borders, outlines and shadows. Set Style.clip to use the same rounded boundary for drawing and pointer routing. Border decoration is paint. Use the layout border and padding fields to reserve content space.
alias U = Garnet::UI
alias L = Garnet::Layout
panel = U::Widgets.panel(U::Style.new(layout: L::Style.new(padding: 12_f32), clip: true))
panel << U::BoxStyle.new(fill: :surface, radius: 10_f32, border: U::Border.new(1_f32, :edge))
theme = U::Theme.new({:surface => Garnet::Color.new(0.08_f32, 0.10_f32, 0.14_f32, 1_f32),
:edge => Garnet::Color.new(0.2_f32, 0.24_f32, 0.3_f32, 1_f32)})
ui = U::Root.new(panel, theme: theme)
Replace ui.theme to retint token-driven paint on the next layout. Foreground supplies a label color token, and Icon fits an authored vector path into its box. Components.mount builds a retained entity once and owns its signal watches and cleanup callbacks. show mounts a conditional branch, for_each keeps rows by key, and typed Context keys share values through component scopes. Watches close when the owning UI root observes detachment or closes.
Bounds publishes transformed, clipped bounds after layout. Frame#find matches visible semantic roles, labels and test IDs. Widgets.popover creates a root-level anchored overlay, with optional modal focus. The overlay follows the current solved geometry and flips above its anchor if it would overflow below. The shared router supports checkboxes, switches, radio groups, sliders, tabs and collapsibles through ordinary typed signals and handlers. Use corners: {tl, tr, br, bl} for individual corner radii.
Stylesheets
How elements look comes from stylesheets, which work like CSS but act on components. An element says what it is with marker components, like Tooltip or a game's own Button and Danger. State components such as Hovered, Pressed, Focused, Disabled, Current, Changed and Badged say what is happening to it. A rule adds the components it lists to every matching element that lacks them:
sheet = U.stylesheet do
rule ".Button" { |style| style.box(fill: GREY, radius: 4).foreground(WHITE).spacing(padding: 6) }
rule(".Button:hovered", &.box(fill: BLUE, radius: 4))
rule(".Button.Danger", &.foreground(RED))
rule("#save", &.spacing(padding: 10))
rule(":changed", &.glow(ORANGE, width: 2, tint: 0.2, fades_with: U::Changed.name))
end
root << U::Styles.new(U::StyleSheet.standard + sheet)
Selectors are Garnet::Selectors from the ECS. U.selector("#name.Component:state") builds one at compile time:
#namematches aGarnet::Name..Nameis a component type, resolved where the macro is used, so a typo is a compile error.:stateis one of the UI states::hovered,:pressed,:focused,:disabled,:current,:changedand:badged.
U.stylesheet lets rule take those strings, and StyleSheet#rule takes any Garnet::Selector.
What a rule adds. Each builder call adds one component: box (BoxStyle), foreground, spacing (padding, gap and size over the Style layout), glow and dot (decorations drawn over the element), or add for any component. Values are plain values, with no theme lookups. A theme is just a stylesheet: StyleSheet.standard(theme), .dark and .light.
Scope. Put a sheet on an entity with Styles. It applies to that entity and its descendants. Sheets nest, with the inner one winning, and isolated: true stops outer sheets from applying.
Precedence. The innermost sheet wins, then the most specific rule (names count most), then the later rule. A component set by hand is never touched: ui.styles only adds missing components, and replaces or removes the ones it added itself (recorded in Styled).
Cost. Each Styles scope is followed by a Garnet::SelectorTracker, whose hooks note only changes to the component types its rules mention. Each frame restyles just the elements whose matches changed: one that gained or lost a marker or state, moved, or came under or left a sheet. When nothing like that happened, it does no work.
The built-in widgets carry markers (Popover, MenuItem, Tooltip, Toast, Dialog, Tab, UnderlinedTab, DockRegion, Pill, KeyCap, Avatar, Progress and others), and dock tabs set Current and DropTarget. StyleSheet.standard gives them their look. UI::Plugin applies it unless the tree has its own Styles.
Systems
The UI's per-frame work is done by ECS systems that UI::Systems installs in PrepareRender, before layout:
| System | Does |
|---|---|
ui.states |
sets Hovered, Pressed, Focused and Disabled from interaction |
ui.bindings |
brings Bound values up to date |
ui.attention |
sets Changed (with an expiry) and Badged from the last layout |
ui.styles |
applies stylesheets |
UI::Plugin installs them along with layout. A host that lays out a Root itself installs UI::Systems.new(root) on the tree's world and calls world.frame(seconds) before root.layout. Changed is removed by Garnet::Expiry (garnet-ecs/gameplay), so it shares the world's clocks.
Attention and value bindings
Both work by looking, not by being told, which matches the pull-based ECS underneath. Nothing has to report a change.
Value bindings tie a control to a value that lives elsewhere, such as a game entity's component or a document property, in both directions. ValueBinding(T) takes a revision (a number that changes whenever the value may have, such as Garnet::ComponentRef#revision), a read, a show that updates the control, and optionally a write and an editing check. Put it on the element with Bound, and ui.bindings keeps it current:
health = player.component_ref(Health)
binding = U::ValueBinding(Int32).new(
revision: -> { health.revision || 0_u64 },
read: -> { health.get?.try(&.points) || 0 },
show: ->(points : Int32) { field.buffer.replace_all(points.to_s); nil },
write: ->(points : Int32) { health.set(Health.new(points)); nil },
editing: -> { control[U::Interactive].state.focused.get })
control << U::Bound.new(binding)
binding.write(12) # from the control's commit
A binding reads the value only when its revision moves, and shows it if it differs. While the control is being edited, the update waits. Writes go to the source and count as seen, so they don't bounce back.
Attention marks what has changed since the user last saw it. Give an element a Garnet::Name, which works like an HTML id. Its fingerprint comes from its Bound value or from a Fingerprint (Fingerprint.of(name)). Root#attention remembers each id's fingerprint from when it was last visible (on screen, not clipped or scrolled away). When a visible element's fingerprint has changed, ui.attention gives it Changed for attention.duration. That covers a value changing in view and one that changed while hidden, in another mode, or not built yet. An element seen for the first time has nothing to compare with, so it isn't marked.
A Badge gives its element Badged while the badge's fingerprint differs from its value when the element it watches was last visible. DockLayout#badge(:console) { errors.size.to_u64 } badges a dock tab until its panel is shown.
What Changed and Badged look like is up to the stylesheet. The standard one draws a fading :ring glow and a :primary dot.
Retained runtime and widgets
Call ui.advance(delta) before layout to drive scope-owned timers and transitions. scope.after and scope.interval return timers that stop on close (cancel remains as a deprecated alias); closed? reports it. Components.dynamic(parent, source) rebuilds just its own fragment when the value changes. Transitions.box and Transitions.icon animate signal-driven paint using Garnet's animation shard. Theme.dark and Theme.light provide the default tokens. Use with_colors to override them and StyleVariants to share named box styles.
Widgets.portal mounts an overlay at the UI root. Anchored popovers can choose a side and alignment, flip across the anchor near an edge, and dismiss on outside press or Escape. Dialogs trap and restore focus, and can dim the surrounding view. The framework also includes tooltips, dropdown and context menus, toasts, and a searchable command palette.
Use number_input, select, toggle_group, accordion and tree for common forms and navigation. virtual_list recycles fixed-height row slots and gives each slot a readable index for binding its content. data_table uses this list and sorts from its column headers. split_pane provides pointer and keyboard resizing. DockLayout groups panels into draggable tabs, keeps content mounted across moves, and exposes a layout snapshot for game or tool code to store and restore. Each panel can set drag, drop, stacking, and per-axis resize policies.
Use CursorHint to supply hover and drag cursors. Window hosts can read router.cursor, and GLFWInput#present applies the hint automatically. Provide Router.new(on_error: handler) to receive event callback failures and continue routing input.
UI state errors raise Garnet::UI::Error (a Garnet::Error): reentrant advancement or dispatch, or an Event method after its dispatch ended. Using a closed Root, Router, Interaction or component scope raises its subclass UI::ClosedError. Root, Router, TestDriver, IOSBridge and GLFWInput all answer closed?. Invalid arguments, including TextInputError, still raise ArgumentError.
For headless interaction tests, require garnet-ui/testing. TestDriver presents real layout frames and can click by role, label or test ID, route keys and committed text, and advance the same timer clock as a host.
Build the desktop gallery with scripts/check-composition example-gallery and run "${TMPDIR:-/tmp}/garnet-ui-gallery". Set GARNET_UI_GALLERY_SMOKE=1 to render three frames in a hidden window and exit.
Field Pack exercises a virtualized game inventory, a settings modal, text editing, and UI-first key dispatch. Its desktop smoke reports frame timings while filtering, scrolling, and resizing.
UI plugin
require "garnet-ui/plugin" runs a UI tree inside a Garnet::World:
world.add_plugin(Garnet::UI::Plugin.new(menu_root))
It installs UI::Root and UI::Router as resources and, in PrepareRender (system ui.layout), advances retained scopes, lays the tree out to Scene::Screen (logical units, snapped to screen.scale), presents the frame to the router and submits its drawing to Scene::RenderQueue at RenderQueue::UI. The router's cursor goes to Input::Devices#cursor.
Input comes from Input::Devices (the plugin requires Input::Plugin) and the UI claims first: presses over UI regions or with a dismissible overlay open, wheel distance consumed by scroll views, focus/activation/escape/navigation keys that change something, text editing keys and typed text while a field is focused, touches that begin on UI, and gamepad navigation edges. Everything else, including Enter or Escape when the UI has nothing to do with them, reaches gameplay actions. Arrow keys only navigate once a control has focus (after Tab, a click or gamepad navigation) or a modal is open, so gameplay can use them alongside on-screen buttons; pass navigation: :always for menu-only screens, and navigation: :none when the game steers with the arrow keys or D-pad and only needs clickable buttons (Tab and the pointer still move focus). Tab is only claimed when there is something to focus.
An open Modal (such as Widgets.dialog) claims its navigation, activation and escape keys (Tab, arrows unless navigation: :none, Enter, Space, Escape and Menu) even when they do nothing, so they never reach the game behind it. Every other key still reaches gameplay actions, so a dialog can be answered with E or 1 and 2 bound as actions. A focused text field claims every key.
Click handlers reach the world through event.world, which UI::Plugin sets on the router:
restart[UI::Interactive].state.on(:click) { |event| event.world.emit(Restart.new) }
restart[UI::Interactive].state.on_click_emit(Restart.new) # the same
pulse[UI::Interactive].state.on_click_press(:pulse) # Input::Actions#press
on_click_press lets an on-screen button drive the same gameplay action as its key. Pass layer: to draw elsewhere in the queue and line_height: to scale wheel lines.
UI::Label.new(text, family, 14) and Layout::Style.new(width: 140, padding: 8) take any number; a number for a length means points.
ui
- 0
- 0
- 0
- 4
- 15
- about 9 hours ago
- November 30, 2026
MIT License
Wed, 02 Dec 2026 02:09:45 GMT