bevy_input_focus/
autofocus.rs

1//! Contains the [`AutoFocus`] component and related machinery.
2
3use bevy_ecs::{component::HookContext, prelude::*, world::DeferredWorld};
4
5use crate::InputFocus;
6
7#[cfg(feature = "bevy_reflect")]
8use bevy_reflect::{prelude::*, Reflect};
9
10/// Indicates that this widget should automatically receive [`InputFocus`].
11///
12/// This can be useful for things like dialog boxes, the first text input in a form,
13/// or the first button in a game menu.
14///
15/// The focus is swapped when this component is added
16/// or an entity with this component is spawned.
17#[derive(Debug, Default, Component, Copy, Clone)]
18#[cfg_attr(
19    feature = "bevy_reflect",
20    derive(Reflect),
21    reflect(Debug, Default, Component, Clone)
22)]
23#[component(on_add = on_auto_focus_added)]
24pub struct AutoFocus;
25
26fn on_auto_focus_added(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
27    if let Some(mut input_focus) = world.get_resource_mut::<InputFocus>() {
28        input_focus.set(entity);
29    }
30}