Keyboard and focus
Make elements focusable, style focus, add shortcuts, move focus from code, trap focus in a dialog, and handle keys in text fields.
Keyboard input goes to the one element in the window that has focus. To make an interface usable from the keyboard, you choose which elements can take focus, add shortcuts, and control where focus goes when dialogs and menus open and close. Read Events first.
Make an element focusable
control, field and editor are focusable by default. Any other element needs tabindex, which
takes a Focus:
column(
class = "card",
tabindex = Focus::Sequential,
on:key_down = move |ev| if ev.key == Key::Named(NamedKey::Delete) { remove() }
) { … }| Value | Written as | Means |
|---|---|---|
Focus::Sequential (the default) | tabindex="0" | reached by Tab, in document order |
Focus::Programmatic | tabindex="-1" | focusable only from code or a pointer press |
tabindex is reactive:
control(tabindex = move || {
if collapsed.get() { Focus::Programmatic } else { Focus::Sequential }
})An element can take focus only if it is not :disabled and generated at least one visible box in
the last layout. At most one element per window has focus at a time.
Tab order
Tab and Shift-Tab walk the focusable elements of the document, or of the innermost focus trap, as of the last completed frame:
- Elements with a positive
tabindex, in increasing order. - Everything else with
tabindex0 or focusable by default, in document order. - Elements with a negative
tabindexare focusable but skipped by Tab.
With nothing focused, Tab starts at the first element and Shift-Tab at the last. Without a trap, Tab past the last element clears focus, and the next Tab starts again at the first. Only a trap wraps.
Focus cannot express a positive tabindex. You can write one with attr:tabindex = "3", but a
numbered tab order is hard to keep consistent across an application. A value that does not parse
is treated as no tabindex at all, not as 0.
Activate with Enter and Space
Enter or Space on the focused element dispatches a real click through the normal path, with the
modifiers that were held. Assistive-technology activation does the same. One on:click handles
pointer, keyboard and screen reader:
control(class = "button", a11y:role = Role::Button, on:click = move |_| save()) {
"Save"
}This works for any focused element, not only control.
To activate on another key, synthesise a click instead of calling the action directly, so capture and propagation behave as they do for a pointer:
on:key_down = move |ev| {
if ev.key == Key::Named(NamedKey::ArrowRight) && !ev.repeat {
ev.prevent_default();
ev.synthesize(events::CLICK);
}
}ev.synthesize dispatches on ev.current.
Style the focused element
| Selector | Matches | Use it for |
|---|---|---|
:focus | the focused element | styles that should show however focus arrived |
:focus-within | the focused element and every ancestor | a wrapper that highlights when its field has focus |
:focus-visible | the focused element, when focus came from the keyboard or from code | the focus ring |
The framework's base sheet draws the ring with a custom property:
:focus-visible { outline: 2px solid var(--zgui-ring); outline-offset: 2px; }Define --zgui-ring in your theme, or the ring has no colour. See
Theming.
:focus-visible depends on how focus arrived:
| Focus arrived by | :focus-visible |
|---|---|
| Tab, or an arrow key inside a composite control | yes |
NodeRef::focus, focus_move, or a trap | yes |
| a pointer press | no |
Clicking an element that already has keyboard focus removes its ring.
Handle a key
on:key_down and on:key_up go to the focused element and travel the normal capture, target and
bubble path, so every ancestor of the focused element sees them. When nothing has focus, keys go to
the document root and to any window-wide shortcuts.
on:key_down = move |ev| {
if ev.key == Key::Named(NamedKey::Escape) { close(); }
if ev.modifiers.primary() && ev.key_without_modifiers.as_str() == Some("z") { undo(); }
if ev.physical == PhysicalKey::Code(KeyCode::KeyW) { move_up(); }
}The payload has several fields that describe the same press. Read the one that matches what you are deciding:
| Decision | Read | Example |
|---|---|---|
| what text to insert | key.inserted_text() | Shift-A inserts A |
| what the key means | key | Escape closes, on every layout |
| which shortcut this is | key_without_modifiers | the binding stays on the printed keycap when a modifier remaps the key |
| where the key is | physical | WASD movement in a game, whatever the keys type |
Do not match a physical position for a text shortcut. KeyCode::KeyZ is the Z key on QWERTY and
the W key on AZERTY.
Insert typed text
Space is a named key: it arrives as Key::Named(NamedKey::Space), and its standard value is " ".
That makes two common ways of reading text wrong:
| Reading | Space | Enter | Result |
|---|---|---|---|
if let Key::Character(text) = &ev.key | no match | no match | drops every space |
ev.key.as_str() | Some(" ") | Some("Enter") | inserts the word "Enter" |
ev.key.inserted_text() | Some(" ") | None | correct |
Use inserted_text() for text. The full payload is in KeyEvent and Key.
Add a shortcut
A listener on an ancestor sees every key aimed at a focused descendant. Use Modifiers::PRIMARY,
or ev.modifiers.primary(), for cross-platform shortcuts: Cmd-K on macOS, Ctrl-K on Linux and
Windows.
column(class = "editor-pane", on:key_down = move |ev| {
if !ev.repeat && ev.modifiers.primary() && ev.key_without_modifiers.as_str() == Some("k") {
ev.prevent_default();
palette.set(true);
}
}) { … }Skip repeats in command handlers. Holding a key fires on:key_down repeatedly with repeat set,
because a held letter must keep typing, but a command should run once per press. zgui's own Tab,
Enter and Space handling already ignores repeats.
To require an exact chord, compare with ==. It does not match when another modifier is also held,
which is usually what you want for a destructive command:
let chord = Modifiers::PRIMARY | Modifiers::SHIFT;
if ev.modifiers == chord { … } // exactly these, nothing else held
if ev.modifiers.contains(chord) { … } // at least theseLeave text fields alone
A shortcut on a key with no modifier, such as Delete or Escape, must not take the key from a text
field. Check focus_is_text_entry() first:
on:key_down = move |ev| {
if ev.key == Key::Named(NamedKey::Delete) && !focus_is_text_entry() {
delete_selected();
}
}It returns true when a field or editor has focus, including a read-only or disabled one. It
returns false when nothing has focus or when called outside a window. It is not reactive.
Window-wide shortcuts
A listener on your view's outer element misses keys in two cases:
- Nothing is focused. The key goes only to the document root, so your view hears nothing. A window that was just opened is in this state.
- Portals. Content rendered through a
Portalsits under the window's overlay root, outside your view, so its keys never pass your listener.
For the first case, call NodeRef::window_shortcut(). While the returned WindowShortcut guard is
held, the element's own listeners also receive keys when nothing in the window has focus. The
element's ancestors are not added. Renew the registration whenever the handle binds:
use zgui::reactive::RenderEffect;
let shell = NodeRef::new();
let registration = RenderEffect::new(move |previous: Option<Option<WindowShortcut>>| {
drop(previous);
shell.get(); // re-run when the element binds
shell.window_shortcut()
});
on_cleanup_local(move || drop(registration));
view! {
column(node_ref = shell, on:key_down = move |ev| { /* shortcuts */ }) { … }
}For the second case, take NodeRef::window_root() and attach a listener with NodeRef::listen. It
returns a ListenerGuard, and the listener lives as long as the guard.
When the focused element is removed, the next frame clears focus and focused_node() reads None.
Keys then go to the root and to window shortcuts again, so shortcuts keep working.
Application-menu shortcuts
On a desktop with an application menu (macOS, through with_menu), a MenuAction can carry a
shortcut with with_shortcut. The chord goes to the focused window first. The menu action runs
only if nothing in the document claimed it: no listener called prevent_default, and no text field
used it. A field therefore keeps Cmd-C, Cmd-V and Cmd-Z even when the menu binds them. Repeats and
keys without modifiers never trigger menu actions. AppKit keeps the chords of its non-editing menu
roles (such as Quit, Hide and Minimize) and window cycling (Cmd + backtick).
Move focus from code
Call focus() on a NodeRef. It works from any handler, effect or callback:
let search = NodeRef::new();
view! {
control(on:click = move |_| search.focus()) { "Search" }
field(node_ref = search)
}| Want | Call |
|---|---|
| focus one element | node_ref.focus() |
| move within a subtree | node_ref.focus_move(FocusMove) -> Option<NodeId> |
| what holds focus, reactively | focused_node() -> Signal<Option<NodeId>, LocalStorage> |
| whether focus is in a text field | focus_is_text_entry() -> bool |
| list Tab-reachable elements | node_ref.focusables() -> Vec<NodeId> |
| whether a node is inside this one | node_ref.contains(node) -> bool |
| whether this node is inside another | node_ref.is_within(node) -> bool |
| document order of two nodes | node_ref.precedes(node) -> bool |
FocusMove is First, Last, Next or Prev. focus_move uses the same order as Tab, wraps
only inside a wrapping trap, and returns the node it chose, or None without moving if there is
nowhere to go.
focused_node() must be called inside a window's scope; outside one it panics in debug builds.
Combined with contains, it tells an overlay whether focus is still inside it:
let panel = NodeRef::new();
let focus = focused_node();
let inside = move || focus.get().is_some_and(|node| panel.contains(node));Do not use ev.request_focus(node) from on:click, on:focus_in or on:focus_out. These are
synthesised events, and queued commands issued from their handlers are discarded. Call
node_ref.focus() instead.
Trap focus in a dialog
A focus trap confines Tab to one subtree. Every modal surface needs one: without it, Tab moves to a control hidden behind the backdrop.
The component library's FocusScope primitive
and its dialogs install traps for you. Use the API below when you build your own surface.
node_ref.trap_focus(options) installs a trap and returns a FocusTrap guard, or None if the
handle is not bound. Dropping the guard removes the trap. Hold the guard for as long as the surface
is open:
use std::cell::RefCell;
use std::rc::Rc;
use zgui::reactive::RenderEffect;
#[component]
fn Confirm(open: RwSignal<bool>) -> impl IntoView {
let panel = NodeRef::new();
let held: Rc<RefCell<Option<FocusTrap>>> = Rc::new(RefCell::new(None));
let installing = {
let held = Rc::clone(&held);
RenderEffect::new(move |_| {
// Re-runs when `open` changes and when the panel binds or unbinds.
if open.get() && panel.get().is_some() {
if held.borrow().is_none() {
*held.borrow_mut() = panel.trap_focus(FocusTrapOptions::MODAL);
}
} else {
// Take the guard out before dropping it: removing a trap moves focus,
// which can re-enter code that borrows `held`.
let released = held.borrow_mut().take();
drop(released);
}
})
};
on_cleanup_local(move || drop(installing));
view! {
if move || open.get() {
Portal(layer = OverlayLayer::Modal) {
box(node_ref = panel, class = "dialog", a11y:role = Role::Dialog) {
label(class = "dialog__title") {"Delete this file?"}
control(class = "button", on:click = move |_| open.set(false)) {"Cancel"}
control(class = "button", on:click = move |_| open.set(false)) {"Delete"}
}
}
}
}
}When open becomes true, the panel binds, the effect installs the trap, and focus moves to the
first control after layout. Tab and Shift-Tab cycle inside the panel. When open becomes false,
the effect drops the guard and focus returns to the control that opened the dialog. A NodeRef
unbinds when its element is removed, so the effect also re-runs if the panel goes away some other
way.
Trap options
FocusTrapOptions has three fields: wrap (Tab past the end returns to the start), auto_focus
(move focus inside on install) and restore (return focus when the trap is removed).
| Constant | wrap | auto_focus | restore | For |
|---|---|---|---|---|
FocusTrapOptions::MODAL (also Default) | yes | yes | yes | dialogs, sheets, drawers |
FocusTrapOptions::CONFINE_ONLY | yes | no | no | a menu that leaves focus where it was |
The struct is #[non_exhaustive]: start from a constant and change fields for other combinations.
FocusTrap::root() and id() identify a trap.
Nested traps and restoring focus
Traps stack, and the most recently installed one is in force.
| Event | Where focus goes |
|---|---|
an auto_focus trap is installed | to the first focusable element inside, after the frame lays it out; skipped if focus is already inside; retried next frame if nothing inside is focusable yet (for example a surface laid out hidden to be measured) |
the newest trap is removed, restore on | back to the element that had focus when the trap was installed |
| the same, but focus is already outside the trap, or a focus request from the same turn points outside it | stays there |
| an older trap is removed while a newer one is active | unchanged; the newer trap takes over the older one's restore target |
| a trap's subtree leaves the document while its guard is still held | the trap is removed the next time the window looks up the active trap, and focus is restored as above if the target still exists |
The third row covers a menu entry that opens a tab and focuses it, or a click outside a popover that lands on another control. The fourth row covers a dialog that opens a second dialog and then closes itself: closing the second returns focus to whatever opened the first.
Move focus with arrow keys
In a toolbar, tab strip or menu, Tab reaches the group once and the arrow keys move inside it. The
RovingFocus primitive does this for you. To
build it by hand:
- Give exactly one item
tabindex = Focus::Sequentialand the restFocus::Programmatic, driven by a "current item" signal. - On an arrow key in the group's
on:key_down, skip repeats, callprevent_default(), update the signal and callfocus()on the next item'sNodeRef.focus_movedoes not work here because it skipsProgrammaticitems. - In each item's
on:focus_in, set the signal to that item, so the tab stop follows pointer focus too. - Put each item's action in
on:click, which Enter and Space already produce.
Text fields
Partial· Onlyfield (single line) and editor (multi-line) accept typing.
field and editor handle the caret, selection, undo and input-method composition themselves. The
text lives in the document, so your view does not keep a second copy. Read changes through
on:input and on:change, and drive the field through NodeRef::set_value, selection,
set_selection and select_all.
Editing is a default action. A field whose on:key_down calls prevent_default types nothing for
that key, which is how you write a numeric-only field.
A keystroke in a field reshapes one paragraph and repaints one box. See Measurements for timings.
Editing keys
The keymap follows the platform the program is built for. "Line" means a paragraph, which is the whole text of a single-line field. Add Shift to any motion to extend the selection.
| Action | Linux and Windows | macOS |
|---|---|---|
| move by character | ← → | ← →, Ctrl-B, Ctrl-F |
| move by word | Ctrl or Alt + ← → | Option + ← → |
| line start or end | Home, End | Cmd + ← →, Home, End, Ctrl-A, Ctrl-E |
| text start or end | Ctrl + Home, End | Cmd + ↑ ↓ |
| delete a character | Backspace, Delete | Backspace, Delete, Ctrl-H, Ctrl-D |
| delete a word | Ctrl or Alt + Backspace, Delete | Option + Backspace, Delete |
| delete to line edge | — | Cmd + Backspace, Delete; Ctrl-K to the end |
| select all, copy, cut, paste | Ctrl-A, C, X, V | Cmd-A, C, X, V |
| undo, redo | Ctrl-Z; Ctrl-Shift-Z or Ctrl-Y | Cmd-Z; Cmd-Shift-Z or Cmd-Y |
The dedicated Copy, Cut, Paste, Undo and Redo keys work everywhere. A Ctrl chord (Cmd on macOS)
that the field does not use inserts nothing and continues to other handlers and the menu. A field
does not take Enter, so Enter in a field still reaches your listeners and activates the field.
Read-only and disabled fields
| State | Typing | Select, move, copy | Caret |
|---|---|---|---|
state:read_only | refused | yes, with keys and pointer drag; text cursor shown | not drawn |
state:disabled | refused | no | not drawn |
A program can still set the value of either with NodeRef::set_value.
Not yet supported
- Up and Down arrows (there is no visual-line motion), and PageUp/PageDown inside a field.
- Double-click word selection and triple-click line selection.
- Dragging text, spell checking, rich text, and caret width or shape styling (
caret-colorworks). - A
valueorplaceholderattribute; set text withNodeRef::set_value.
Build text from key presses
Any focusable element can build text from key presses. You draw the text and caret yourself, and you get no selection, undo, word motion or input method:
let draft = RwSignal::new(String::new());
view! {
column(
class = "prompt",
tabindex = Focus::Sequential, // a column is not focusable by default
on:key_down = move |ev| match &ev.key {
Key::Named(NamedKey::Backspace) => draft.update(|draft| { draft.pop(); }),
Key::Named(NamedKey::Escape) => draft.set(String::new()),
// Named keys such as Tab return None and fall through, so Tab still moves focus.
key => if let Some(text) = key.inserted_text() {
draft.update(|draft| draft.push_str(text));
},
}
) {
text(class = "prompt__draft") {{move || draft.get()}}
}
}examples/todo.rs in the zgui repository uses this pattern at full size.
Input methods
An input method composes one character from several presses: Japanese kana, Chinese candidates, a compose sequence. While composing, it shows provisional text.
In an editable field or editor, zgui handles composition for you:
- It tells the platform that text input is wanted and where the caret is, so the candidate window follows the caret.
- Provisional text goes into the document and is laid out like other text. A commit is one undo step.
- Abandoning a composition restores the text it replaced.
- Keys that arrive during a composition take no default action, so Tab cannot move focus away mid-composition.
Partial· Composition works only inside editable field and editor elements.
An element that builds text from on:key_down receives no composition. The input purpose is
always reported as TextInputPurpose::Normal, so a field cannot yet tell the input method it holds
a password.
The events are routed like key events:
on: name | ImeEvent | Cancelable | Means |
|---|---|---|---|
ime_start | Enabled | yes | the input method took over |
ime_preedit | Preedit { text, cursor } | no | the provisional text changed |
ime_commit | Commit(text) | no | the provisional text became real |
ime_end | Disabled | no | the input method let go, dropping any provisional text |
cursor is a byte range into the provisional text. ImeEvent::is_composing() is true for
Enabled and Preedit.
Default key handling
zgui's own key handling runs after every listener on the path, and only if no listener called
ev.prevent_default():
| Order | Condition | Behaviour |
|---|---|---|
| 1 | an editable field or editor has focus | the field takes the key; if it uses the key, nothing below runs |
| 2 | Tab, not a repeat | focus moves to the next element in sequence; Shift-Tab moves back |
| 2 | Enter or Space, not a repeat, something focused | the focused element is activated with a real click |
| 3 | a chord nothing above claimed | the matching application-menu action runs |
Tab, Enter and Space are matched against key_without_modifiers. on:key_up has no default
behaviour. While an input method is composing, keys take no default action at all.
Focus events
on:focus_in fires when focus arrives at the element or a descendant. on:focus_out fires when
focus leaves the element and all its descendants. Both bubble, and neither is cancelable. They
target the element that gained or lost focus.
The payload is a FocusEvent with related: Option<NodeId> (the element at the other end of the
move) and cause: FocusCause (Pointer, Keyboard, Programmatic or Window).
FocusCause::shows_ring() is true for Keyboard and Programmatic.
focus_outis dispatched beforefocus_in, and both after the event that moved focus has finished. Reading focus from either handler gives the new location.- A handler that moves focus again starts a new round of events.
FocusEvent::related is an accessibility NodeId, not a zgui::view::NodeId. Convert it with
zgui::view::NodeId::from_u64(related.0), which returns an Option.
KeyEvent and Key
pub struct KeyEvent {
pub key: Key, // layout and modifiers applied
pub key_without_modifiers: Key, // layout applied, modifiers not applied
pub physical: PhysicalKey, // position on the keyboard
pub location: KeyLocation, // Standard | Left | Right | Numpad
pub repeat: bool, // produced by holding the key down
}location separates same-named keys, such as left and right Shift or the numpad Enter.
ev.modifiers, available on every event, holds the modifiers.
on:text (TextEvent) also exists, but Not built yet· nothing produces it yet.
Key is what a press means under the active layout. It is #[non_exhaustive].
| Variant | Holds | Example |
|---|---|---|
Key::Named(NamedKey) | a key whose meaning is a name | Enter, Escape, ArrowLeft, F5 |
Key::Character(SharedString) | the text the key produces | "a", "é" |
Key::Dead(Option<char>) | an accent waiting for the next key | acute on a French layout |
Key::Other(SharedString) | a standard key name not in NamedKey | "TVPower" |
Key::Unidentified | the platform could not identify the key |
Character holds a string because one press can produce several characters.
| Method | Returns |
|---|---|
as_str() -> Option<&str> | the standard value: the name of a named key, the text of a character key |
inserted_text() -> Option<&str> | the text the key inserts; None for keys that are names |
is_modifier() -> bool | whether the key is a modifier |
Key::character(text) | builds a Character |
NamedKey
#[non_exhaustive], with NamedKey::ALL, as_str(), is_modifier(), is_navigation(),
FromStr and Display.
| Group | Members |
|---|---|
| modifiers | Alt, AltGraph, CapsLock, Control, Fn, FnLock, NumLock, ScrollLock, Shift, Meta, Symbol, SymbolLock, Hyper, Super |
| whitespace | Enter, Tab, Space |
| navigation | ArrowDown, ArrowLeft, ArrowRight, ArrowUp, End, Home, PageDown, PageUp |
| editing | Backspace, Clear, Copy, Cut, Paste, Delete, Insert, Redo, Undo |
| general | Cancel, ContextMenu, Escape, Execute, Find, Help, Pause, Play, Select, PrintScreen, Again, Props |
| input methods | Accept, Compose, Convert, NonConvert, ModeChange, Process, NextCandidate, PreviousCandidate, AllCandidates, HangulMode, HanjaMode, KanaMode, KanjiMode, Hiragana, Katakana, ZenkakuHankaku |
| browser | BrowserBack, BrowserForward, BrowserRefresh, BrowserSearch, BrowserHome |
| media and device | MediaPlayPause, MediaStop, MediaTrackNext, MediaTrackPrevious, AudioVolumeDown, AudioVolumeUp, AudioVolumeMute, BrightnessDown, BrightnessUp |
| function | F1 to F24 |
PhysicalKey and KeyCode
PhysicalKey is Code(KeyCode) for a known position or Unidentified(u32) with the platform's
own code; PhysicalKey::code() returns the KeyCode, if any. KeyCode names positions on a US
layout, so on a Dvorak keyboard the key labelled . is still KeyCode::KeyE. It covers
KeyA–KeyZ, Digit0–Digit9, punctuation, modifiers (ShiftLeft, ControlRight, MetaLeft,
…), navigation, the numpad (Numpad0–Numpad9, NumpadEnter, …), F1–F24 and media keys. It
has KeyCode::ALL, as_str(), FromStr and Display, and is #[non_exhaustive].
Modifiers
A small bit set carried on every event as ev.modifiers.
| Constant | Test | Key |
|---|---|---|
Modifiers::SHIFT | shift() | Shift |
Modifiers::CONTROL | control() | Control |
Modifiers::ALT | alt() | Alt, Option on macOS |
Modifiers::META | meta() | Super on Linux, Command on macOS, the Windows key on Windows |
Modifiers::PRIMARY | primary() | the platform's shortcut modifier: META on macOS, CONTROL elsewhere |
Also: Modifiers::NONE, Modifiers::ALL, is_empty(), contains(other), bits(),
from_bits_truncate(raw) and with(flag, on). |, & and ! work, so a chord is a value.
primary() is a contains test.