Skip to content

Commit f30d089

Browse files
ValorZardsebcrozet
andauthored
fix text input on wasm (#394)
* add text input to ui example * it works now (but this is a weird hack) * much less hacky way of doing this * handle backspace and other special keys gracefully * update edit text string to make more clear you can edit it * fix: support no ascii characters too --------- Co-authored-by: Sébastien Crozet <sebcrozet@dimforge.com>
1 parent 4a55053 commit f30d089

2 files changed

Lines changed: 14 additions & 0 deletions

File tree

examples/ui.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ async fn main() {
2222

2323
// UI state
2424
let mut rotation_speed = 0.014;
25+
let mut text = String::from("Edit text here!");
2526
let mut opacity = 1.0;
2627
let mut cube_color = [1.0, 0.0, 0.0];
2728

@@ -54,6 +55,9 @@ async fn main() {
5455
ui.label("Opacity:");
5556
ui.add(egui::Slider::new(&mut opacity, 0.0..=1.0));
5657

58+
// Text Input
59+
ui.add(egui::TextEdit::singleline(&mut text));
60+
5761
// Color picker
5862
ui.label("Cube Color:");
5963

src/window/wgpu_canvas.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -611,6 +611,16 @@ impl WgpuCanvas {
611611
Action::Press,
612612
Modifiers::empty(),
613613
));
614+
// Emit a Char event for single-character (printable) keys so
615+
// egui text fields receive text input. Skip when a command
616+
// modifier is held so shortcuts (e.g. Ctrl+A) don't insert text,
617+
// mirroring the native path which relies on winit's `text` field.
618+
let key_string = event.key();
619+
if !event.ctrl_key() && !event.meta_key() && key_string.chars().count() == 1 {
620+
if let Some(ch) = key_string.chars().next() {
621+
pending.borrow_mut().push(WindowEvent::Char(ch));
622+
}
623+
}
614624
});
615625
let _ = web_window
616626
.add_event_listener_with_callback("keydown", closure.as_ref().unchecked_ref());

0 commit comments

Comments
 (0)