User Interface Controls
User interface controls provide familiar text editing, selection, and input within Pax's scene. They share layout with your drawings and images while the browser or operating system supplies the underlying controls. Pax also provides composed controls such as ComboBox and ColorPicker.
Pax uses native controls, whose implementations vary based on the target platform of your app. For example, the same <Button /> Pax element will render and style a DOM button in the browser and a UIKit button on iOS. Native controls are transformed, composed, clipped, and masked similarly to text.
This chapter builds on Properties and Events & Rust. For keyboard navigation, screen-reader support, and testing, see Accessibility.
Choose a control
The standard library's controls are available through use pax_kit::*;.
These controls use native input, with availability and styling differences
covered under Current support:
| Control | Editable property or content | Control event |
|---|---|---|
| Button | label or a text body supplies its visible title | @button_click; also @submit when submit=true |
| Textbox | text: String | @textbox_input while editing; @textbox_change when the platform commits a change; @submit for single-line Return |
| Checkbox | checked: bool | @checkbox_change, with event.checked |
| Slider | value: f64, bounded by min and max | @slider_change, with event.value |
| Dropdown | options: Vec<String> and selected_id: u32 | Bind selected_id; there is no dedicated public dropdown-change event |
| RadioList | options: Vec<String> and selected_id: u32 | Bind selected_id; there is no dedicated public radio-list-change event |
| PhotoPicker | Slotted content opens a native photo picker; configure source and allow_multiple | @photo_picker_change, with selection status and photo metadata |
The library also provides controls composed from Pax components:
| Control | Use and binding |
|---|---|
| ComboBox | Filter a list by typing; bind text and selected separately |
| ColorPicker | Edit a bound color through a palette, sliders, and RGBA fields |
| ColorPickerSwatch | Open the color editor from a compact swatch; bind color |
| Tabs | Switch between slotted panels; supply names and bind the selected index |
| ThemeToggle | A moon/sun switch that edits a bound light_mode preference |
| Toast | Show a temporary notification when message changes to nonempty text; accepts a text body |
| Tooltip | Show tip beside slotted content on hover or click/tap |
| ConfirmationDialog | Show a Yes/No prompt with open=true; supply text as an attribute or text body |
See Making custom controls for how these compositions work. Ordinary pointer events are covered in Events & Rust.
A small editable form
This settings form stores a notebook name, location preference, visibility,
and detail level. Each control edits a property through bind:. The Save
button calls Rust to validate and report the choices.
In src/lib.rs:
#![allow(unused)] fn main() { use pax_kit::*; pax_kit::runnable! { root: crate::Example } #[pax] #[file("lib.pax")] pub struct Example { pub name: Property<String>, pub include_location: Property<bool>, pub visibility: Property<u32>, pub detail: Property<f64>, pub message: Property<String>, } impl Example { pub fn save(&mut self, _ctx: &NodeContext, _event: Event<ButtonClick>) { let name = self.name.get(); if name.trim().is_empty() { self.message.set("Give this notebook a name first.".into()); return; } let visibility = match self.visibility.get() { 1 => "shared", _ => "private", }; let location = if self.include_location.get() { "on" } else { "off" }; self.message.set(format!( "{}: {}, location {}, detail {:.1}.", name.trim(), visibility, location, self.detail.get() )); } } }
In src/lib.pax:
<Group x=24px y=24px width={100% - 48px} height=452px>
<Text class="label" width=100% height=28px>Notebook name</Text>
<Textbox y=32px width=100% height=40px
text=bind:self.name placeholder="e.g. Moss and rain" />
<Checkbox y=92px width=24px height=24px
checked=bind:self.include_location />
<Text class="label" x=36px y=90px width={100% - 36px} height=28px>Include location</Text>
<Text class="label" y=140px width=100% height=28px>Visibility</Text>
<Dropdown y=172px width=100% height=40px
options=["Private", "Shared"] selected_id=bind:self.visibility />
<Text class="label" y=236px width=100% height=28px>{"Detail: " + self.detail}</Text>
<Slider y=268px width=100% height=32px
min=0.0 max=1.0 step=0.1 value=bind:self.detail />
<Button y=324px width=180px height=44px
color=rgb(56, 100, 78) hover_color=rgb(43, 79, 60)
@button_click=self.save>Save notebook</Button>
<Text class="label" y=388px width=100% height=64px>{self.message}</Text>
</Group>
@settings {
.label {
style: {font: "Arial", font_size: 16px, fill: rgb(36, 54, 47)}
}
}
Try saving before entering a name, then change the fields and save again. The detail label updates while the slider moves. The message changes only when Save runs. This sample reports the choices on screen; a real app would also persist or submit them from Rust.
bind:self.name connects the Textbox's editable property to the component's
property. Typing updates both. A one-way expression such as text={self.name}
supplies a value to the control without making it an editor for the parent
property. Bind directly to state; put formatting and derived display values
in separate expressions. See Two-way bindings
for the underlying model.
The visible labels above help someone looking at the form. They are separate Text elements: Pax does not currently turn that proximity into a semantic label association for assistive technology. Keep the accessibility boundary in mind when adapting the form.
Bindings and events
selected_id is a zero-based index into options, despite its name. The
first option is index 0. Keep the index valid when replacing or reordering
the options; map it to your application's own identifier in Rust when needed.
On web, replacing options preserves the requested index even when the index
itself has not changed. An empty list or an out-of-range index shows no selected
option; refilling the list restores that index if it becomes valid again.
Multiple Sliders can share a bound property. Editing one updates the others
without emitting extra @slider_change events. A handler can also correct the
incoming value.
On web and Apple, TextboxInput, CheckboxChange, and SliderChange handlers run after the bound property has been updated. Use handlers for validation or side effects; there is no need to copy the event value back just to maintain the binding.
Use @textbox_input for immediate feedback and @submit for single-line
Return or a Button with submit=true. The bound text is current before
submission handlers run. @textbox_change follows the browser's change
event on web and the end of editing on Apple; it does not mean Enter was pressed.
Multiline Return inserts a newline. See
Submit an action for handlers and propagation.
Slider-change handlers can run repeatedly during a drag, so keep expensive work
out of that path.
Set focus_on_mount=true to focus a Textbox when it appears. See
Focus and keyboard interaction
for choosing when to request focus and how to test navigation.
Multiline text and styling
For a longer note, add a Property<String> named notes and use
multiline=true:
<Textbox x=24px y=24px width={100% - 48px} height=140px
multiline=true text=bind:self.notes
background=rgb(249, 247, 239)
stroke={paint: rgb(155, 170, 153), width: 1px}
corner_radius=8
style={font: "Arial", font_size: 18px, fill: rgb(36, 54, 47)} />
Give a multiline editor enough height for its contents. A placeholder is available for single-line Textbox on web and Apple, and multiline Textbox on web; the current Apple multiline views do not display one. Keep a persistent visible label when the field needs an explanation.
Native controls expose their own styling properties. Button uses color,
hover_color, outline, corner_radius, and style; Textbox uses
background, stroke, outline, corner_radius, and style. Checkbox has
separate unchecked and checked backgrounds, while Slider exposes an accent.
Consult the control's API for its exact property names and defaults. The
platform still influences its appearance, especially focus and hover states.
An ordinary Button renders its own label and surface. For a custom composition, build a component and handle its interactions deliberately; adding a click handler to a drawing does not supply a button's keyboard and assistive-technology behavior. PhotoPicker's slotted design below is a specific API for a custom visible affordance.
Picking a color
ColorPicker combines a saturation/lightness palette with native hue and
opacity sliders and four RGBA fields. Give the component bounds for its palette
and controls. Bind its color to a Property<Color> to update the preview
when the user picks a color and update the picker when the app changes it.
<ColorPicker width=310px height=350px color=bind:paint/>
<Rectangle x=330px width=80px height=80px fill={self.paint}/>
Drag or touch the palette to change saturation horizontally and lightness vertically. For exact values, commit a number from 0 to 255 in a channel field. An out-of-range entry shows the accepted range below its field and keeps the selected color.
For a compact form, use ColorPickerSwatch with the same binding.
<ColorPickerSwatch width=34px height=34px color=bind:paint/>
Activating the swatch opens the editor beside it in a viewport overlay. Clicking another control on web dismisses the editor and operates that control in the same gesture. The swatch owns its open state and outside binding. See outside clicks and the color picker API.
Filtered selection with ComboBox
ComboBox combines an editable Textbox with a
Pax list. Add these fields to your form component, initializing them in its
Default implementation if it has one:
#![allow(unused)] fn main() { pub query: Property<String>, pub choice: Property<Option<usize>>, }
Use Property::new(String::new()) and Property::new(None) for an initially
empty control. Then place it in the template:
<ComboBox width=240px height=36px
options=["Alpha", "Beta", "Gamma"]
text=bind:self.query selected=bind:self.choice
background=WHITE stroke={paint: rgb(155, 170, 153), width: 1px}
style={font_size: 16px, fill: rgb(36, 54, 47)} />
Click or tap the input to open the list, then type to filter it. Matching is
case-sensitive and uses substrings; prefix matches appear first, with
alphabetical order within each group. Selecting a row commits its original
zero-based index in options, copies its label to query, and closes the
list. For example, filtering to Gamma and choosing it sets choice to
Some(2), even though only one row is visible. Separate instances keep their own
selection unless bound to shared state.
query is the editable text, while choice is the last committed
selection. Typing, including an exact label match, does not select a row
or clear the previous selection. Leaving the field does not commit it either.
Do not treat a nonempty query as a valid selection or assume it still matches
the last choice. The clear icon resets both values.
Changing options updates the label at the selected index. An out-of-range
index becomes None and clears the text. Duplicate labels are supported,
but reordering the source list keeps the index, not an application's item
identity. If records have stable IDs, translate between those IDs and option
indices in your application when updating the list.
new_item controls the no-match row:
| Value | Behavior |
|---|---|
NewItem::Disallow (default) | Shows a disabled “No Results Found” row. It does not prevent typing unmatched text. |
NewItem::AllowInvalid | Shows no no-match row and preserves initial free text when no option is selected. It does not commit a new selection. |
NewItem::Text("Create item") | Shows a custom row that dispatches @new_item when clicked or tapped. |
For the custom row, set new_item=NewItem::Text("Create item") and
@new_item=self.create_item. Define
pub fn create_item(&mut self, ctx: &NodeContext) on the containing component.
The handler reads the bound query and decides whether to add and select an
option. See custom events.
The composed list supports pointer selection on web and Apple chassis, but it does not implement arrow-key/Enter list selection or a complete accessible combobox contract. Native text editing does not supply those list behaviors. Use Dropdown when a native fixed-choice control fits the task, and evaluate the accessibility needs of any editable selector.
Making custom controls
Native controls require special handling in the engine to coordinate with each target's chassis. Higher-level custom controls are simply Pax components.
ComboBox, for example, combines a native Textbox with a Scroller and filtered list of Pax rows. ColorPicker combines a drawn palette with native Sliders and RGBA text fields. Both expose properties that the containing application can bind, just like the controls they are built from.
Build your own controls the same way: compose their appearance in a template,
expose the editable value as a Property, and bind it to the child controls.
Use Rust handlers for state changes and
custom events for actions the
containing application should handle. Slots
let callers supply content, such as a picker label or a tab panel.
Native inputs retain their platform's editing and activation behavior, but a composed control still needs appropriate keyboard navigation and focus handling. Tabs and ConfirmationDialog, for example, do not yet provide a complete accessible interaction contract. See Accessibility when designing and testing a custom control.
PhotoPicker
PhotoPicker lets someone select images for the application. Its children draw the visible affordance; a transparent native control above them opens the platform picker. Keep those children simple and give the whole picker a usable size:
<PhotoPicker x=24px y=24px width=240px height=48px
source=PhotoPickerSource::Library allow_multiple=true
include_bytes=false max_bytes_per_photo=26214400
@photo_picker_change=self.choose_photos>
<Text width=100% height=100%
style={
font: "Arial", font_size: 18px, fill: WHITE
align_horizontal: HorizontalAlign::Center
align_vertical: VerticalAlign::Center
}>Choose photos</Text>
<Rectangle width=100% height=100% corner_radius=8
fill=rgb(56, 100, 78) />
</PhotoPicker>
The default accept filter is "image/*". On web it is passed to the file
input; Apple's current pickers select images without applying a custom
accept filter. Use allow_multiple=false when only one existing photo is
needed. Camera capture produces one photo at a time.
Handle selection and partial results
The completion event includes status, an optional message, request_id,
and a list of photos. Add Property<String> fields named preview_url and
message to the component for this handler:
#![allow(unused)] fn main() { pub fn choose_photos(&mut self, _ctx: &NodeContext, event: Event<PhotoPickerChange>) { if event.status == PhotoPickerStatus::Cancelled { return; } if event.status == PhotoPickerStatus::Selected { if let Some(handle) = event.photos.first().and_then(|photo| photo.handle.as_ref()) { self.preview_url.set(handle.clone()); } self.message.set(event.message.clone().unwrap_or_else(|| { format!("Selected {} photo(s).", event.photos.len()) })); } else { self.message.set(event.message.clone().unwrap_or_else(|| { "No photo was added. Try another image or source.".into() })); } } }
Selected can include a warning: if some files exceed the configured size
limit, the accepted files can still be returned. SizeLimitExceeded reports
a selection in which the size limit prevented any accepted photos. Other
statuses are Cancelled, PermissionDenied, Unavailable, and Failed.
Keep the person's existing selection when a request is cancelled. Browser
dismissal does not always deliver a completion event in the current web
implementation, so do not depend on every close resetting an app-level
“picker open” flag.
Each photo includes a temporary identifier, MIME type, byte size, source kind, and optional file name, dimensions, preview handle, and copied bytes. Show a returned handle with NativeImage:
if self.preview_url != "" {
<NativeImage x=24px y=96px width=240px height=160px
url={self.preview_url} fit=ImageFit::Fit />
}
Handles are transient object URLs or temporary file URLs. Persist an app-owned copy if the image must survive beyond the current session. Selection does not upload a file; networking and storage belong to your Rust application logic.
include_bytes=true asks for copied data in photo.data. Web supplies it
when the read succeeds; the current Apple implementation returns metadata
and file handles without copied bytes in the event. Treat data as optional.
include_bytes=false avoids that web byte copy when a preview is enough.
The default max_bytes_per_photo is 25 MiB (26,214,400 bytes); a positive
limit is checked even when include_bytes is false. It is a per-photo
limit, so also consider how many selections your app retains.
Library, camera, and permissions
| Target | PhotoPickerSource::Library | PhotoPickerSource::Camera |
|---|---|---|
| Web | Browser file picker with image filtering and optional multiple selection | Requests the file input's camera-capture hint; the browser/device decides what UI is available |
| macOS | Image-file selection through NSOpenPanel | Returns Unavailable |
| iOS and iPadOS | System photo picker with optional multiple selection | System camera UI on a capable device, subject to permission |
On iOS and iPadOS, library selection uses the system's scoped photo picker.
The camera path needs a purpose string in the project's Cargo.toml:
[package.metadata.pax.ios.info_plist]
NSCameraUsageDescription = "Add a photo to your field notes."
iPadOS inherits the iOS metadata unless
[package.metadata.pax.ipados.info_plist] overrides it. Check permission
denial and unavailable hardware as well as a successful capture; a simulator
cannot stand in for every device capability.
Incrementing the picker's trigger property requests a programmatic open,
and the value is returned as request_id. On web, prefer direct activation
of the picker itself: browsers restrict opening file dialogs without a
user gesture, so a delayed property update is not a reliable substitute.
The canonical examples/fixtures/photo-picker project shows library and camera
selection, metadata, size limits, and thumbnail previews. From the repository
root, run it with:
pax-cli run --path examples/fixtures/photo-picker --target web
Current support
Button, Textbox (single-line and multiline), Checkbox, Slider, Dropdown, and RadioList are implemented on web, macOS, iOS, and iPadOS. The shared API does not make every platform detail identical:
- Web Slider applies
step; Apple sliders are continuous and do not apply it. Check the target behavior when discrete values are essential. - Button's
hover_colorapplies on web but not in the current Apple button views. - Multiline placeholders, photo bytes, and camera availability have the limits described above.
- Keyboard and assistive-technology support have additional limits; see Accessibility.
Android, Windows, and Linux (alpha)
These alpha hosts provide native Text, Textbox, Button, Checkbox, Slider, Dropdown, RadioList, NativeImage, and scrolling containers through Android, WinUI, or GTK. PhotoPicker is not supported. Styling and input behavior vary:
- Android: Button labels have no default padding; size the button for its font and touch target. Button hover styling and scroll snapping are not implemented. Radio indicators retain their native shape and thickness. Text supports native selection, editing through the Android IME, and Markdown/source highlighting.
- Windows and Linux: Sliders require finite bounds and values with
min <= maxand a positive step. User input snaps to a grid anchored atmin; programmatic values are clamped without snapping or emitting events. Dropdown and RadioList preserve the requested index when options change; an empty list or invalid index leaves no selection. Dropdown popups are separate native surfaces, so test their placement and clipping too.
For text sizing and styling, see Android fonts and Windows and Linux text. Leave dimensions that should grow with enlarged text unspecified. Android setup and desktop setup cover requirements and remaining limits, including translucent vector/native blending. Test your intended keyboards, physical devices, and assistive technologies.
The native-controls fixture
exercises shared slider values, changing option lists, transformed controls,
and scrolling. Use it alongside your application's keyboard and accessibility checks.
Read more
Continue to Accessibility for keyboard and screen-reader support. Compositing explains how native controls and rendered content share clipping and stacking; Scrolling covers longer forms and content regions.
For more detail, see the forms API, PhotoPicker API, event payloads, and image sources.