pub struct FocusHandle { /* private fields */ }Expand description
A way to put keyboard focus on one widget. Compose’s FocusRequester.
Make one with use_focus_handle, give it to a widget with .focus_handle(&handle),
and call FocusHandle::request from a handler or an effect. Cloning is cheap: every
clone is the same handle. The handle follows its widget’s node across re-renders, and
when the widget is replaced by a new node, it follows the new one.
A drawer that takes focus when it opens and gives it back to the control that opened it when Escape closes it:
use compose_rust::runtime::*;
use compose_rust::ui::*;
#[Composable]
fn Screen() {
let open = remember(|| mutable_state_of(false));
let opener = use_focus_handle();
let drawer = use_focus_handle();
Column().content(|| {
Button("Menu")
.focus_handle(&opener)
.on_click(move || open.set(true));
if open.get() {
let back = opener.clone();
Column()
.focus_handle(&drawer)
.on_key_down(move |key| {
if key.text() == "Escape" {
key.consume();
open.set(false);
back.request();
}
})
.content(|| {
Text("Drawer");
});
}
});
// The drawer's node exists once the composition that opened it is applied, so
// the request runs as an effect of that composition rather than in the click.
let take = drawer.clone();
let is_open = open.get();
launched_effect(is_open, move || async move {
if is_open {
take.request();
}
});
}A request made while the handle’s node is not on screen does nothing and is not kept for later, which is why the drawer above asks from an effect.
Implementations§
Source§impl FocusHandle
impl FocusHandle
Sourcepub fn request(&self)
pub fn request(&self)
Asks for keyboard focus on the node this handle is bound to. The next batch
carries one RequestFocus for it, however many times this is called before then.
A handle that is bound to no node on screen, because its widget has not been composed yet or has left, asks for nothing.