1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
use std::{borrow::Cow, iter::repeat};

use bevy::{
    ecs::system::{EntityCommands, SystemParam},
    input::{keyboard::KeyboardInput, ButtonState},
    prelude::*,
    window::PrimaryWindow,
};

use crate::{focus::FocusedQuery, GuiCommands, OuterStyle};

const FOCUSED_COLOR: Color = Color::WHITE;
const INACTIVE_COLOR: Color = Color::rgb(0.8, 0.8, 0.8);

pub(crate) struct TextBoxPlugin;

impl Plugin for TextBoxPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(
            Update,
            (
                focus_system,
                input_system
                    .run_if(on_event::<ReceivedCharacter>().or_else(on_event::<KeyboardInput>())),
            ),
        );
    }
}

pub trait TextBoxCommands<'w, 's> {
    fn spawn_text_box(&mut self, size: OuterStyle, secret: bool) -> EntityCommands<'_>;
}

impl<'w, 's> TextBoxCommands<'w, 's> for GuiCommands<'w, 's> {
    fn spawn_text_box(&mut self, style: OuterStyle, secret: bool) -> EntityCommands<'_> {
        let text_style = self.text_props().input_text_style();

        let mut commands = self.spawn(NodeBundle {
            style: Style {
                padding: UiRect::horizontal(Val::Percent(2.)),
                justify_content: JustifyContent::FlexStart,
                align_items: AlignItems::Center,
                overflow: Overflow::clip(),
                width: style.width,
                height: style.height,
                margin: style.margin,
                ..default()
            },
            background_color: INACTIVE_COLOR.into(),
            ..default()
        });

        commands
            .insert(Interaction::None)
            .insert(TextBox::new(secret))
            .with_children(|builder| {
                builder.spawn(
                    TextBundle::from_section("", text_style).with_text_justify(JustifyText::Left),
                );
            });

        commands
    }
}

#[derive(SystemParam)]
pub struct TextBoxQuery<'w, 's> {
    query: Query<'w, 's, &'static TextBox>,
}

impl<'w, 's> TextBoxQuery<'w, 's> {
    pub fn text(&self, entity: Entity) -> Option<Cow<'_, str>> {
        self.query.get(entity).map(|e| e.text()).ok()
    }
}

#[derive(Component)]
pub struct TextBox {
    text: String,
    secret: bool,
}

impl TextBox {
    fn new(secret: bool) -> Self {
        Self {
            text: String::new(),
            secret,
        }
    }

    fn text(&self) -> Cow<'_, str> {
        Cow::from(&self.text)
    }

    fn ui_text(&self) -> String {
        if self.secret {
            String::from_iter(repeat('\u{25CF}').take(self.text.len()))
        } else {
            self.text.clone()
        }
    }

    fn push(&mut self, input: char) {
        debug_assert!(!input.is_control());
        self.text.push(input);
    }

    fn backspace(&mut self) {
        self.text.pop();
    }
}

fn focus_system(
    mut window_query: Query<&mut Window, With<PrimaryWindow>>,
    mut focused: FocusedQuery<&mut BackgroundColor, With<TextBox>>,
) {
    if focused.is_changed() {
        if let Some(mut color) = focused.get_previous_mut() {
            *color = INACTIVE_COLOR.into();
        }

        let mut window = window_query.single_mut();
        match focused.get_current_mut() {
            Some(mut color) => {
                *color = FOCUSED_COLOR.into();
                window.ime_enabled = true;
            }
            None => window.ime_enabled = false,
        }
    }
}

fn input_system(
    mut focused: FocusedQuery<(&mut TextBox, &Children)>,
    mut texts: Query<&mut Text>,
    mut characters: EventReader<ReceivedCharacter>,
    mut keyboard: EventReader<KeyboardInput>,
) {
    let Some((mut text_box, children)) = focused.get_current_mut() else {
        return;
    };

    let text_id = children
        .iter()
        .cloned()
        .find(|&e| texts.contains(e))
        .expect("Text box without `Text` child component.");
    let mut text = texts.get_mut(text_id).unwrap();

    // FIXME: Fix ordering of multiple event streams once
    // https://github.com/bevyengine/bevy/issues/5984 is fixed.
    for event in characters.read() {
        if let Some(character) = event.char.chars().last() {
            if !character.is_control() {
                text_box.push(character);
            }
        }
    }

    for event in keyboard.read() {
        if event.state != ButtonState::Pressed {
            continue;
        }

        match event.key_code {
            KeyCode::Backspace => text_box.backspace(),
            _ => continue,
        }
    }

    text.sections[0].value = text_box.ui_text();
}