Skip to main content

eframe/web/
text_agent.rs

1//! The text agent is a hidden `<input>` element used to capture
2//! IME and mobile keyboard input events.
3
4use core::cell::RefCell;
5use std::rc::Rc;
6
7use wasm_bindgen::prelude::*;
8
9use super::{AppRunner, WebRunner};
10
11pub struct TextAgent {
12    input: web_sys::HtmlInputElement,
13    input_state: Rc<RefCell<InputState>>,
14}
15
16impl TextAgent {
17    /// Attach the agent to the document.
18    pub fn attach(
19        runner_ref: &WebRunner,
20        canvas: &web_sys::HtmlCanvasElement,
21    ) -> Result<Self, JsValue> {
22        let window = web_sys::window().unwrap();
23        let document = window.document().unwrap();
24
25        // create an `<input>` element
26        let input = document
27            .create_element("input")?
28            .dyn_into::<web_sys::HtmlInputElement>()?;
29        input.set_type("text");
30        input.set_attribute("autocapitalize", "off")?;
31        let input_state = Rc::new(RefCell::new(InputState::new(input.clone())));
32
33        // Hide the element, and park it over the top-left corner of the canvas
34        // so that focusing it can never scroll some other part
35        // of the page into view.
36        let style = input.style();
37        style.set_property("background-color", "transparent")?;
38        style.set_property("border", "none")?;
39        style.set_property("outline", "none")?;
40        style.set_property("width", "1px")?;
41        style.set_property("height", "1px")?;
42        style.set_property("caret-color", "transparent")?;
43        style.set_property("position", "absolute")?;
44        style.set_property("top", &format!("{}px", canvas.offset_top()))?;
45        style.set_property("left", &format!("{}px", canvas.offset_left()))?;
46        // Prevent auto-zoom on mobile browsers (requires at least 16px).
47        style.set_property("font-size", "16px")?;
48
49        // Insert the input as a sibling of the canvas, so that its
50        // `position: absolute` resolves against the same containing block
51        // as the canvas' `offset_top`/`offset_left`.
52        // This anchors the input to the canvas regardless of how the page
53        // is scrolled or how the canvas is embedded, and also works when
54        // the canvas is inside a shadow DOM.
55        if let Some(parent) = canvas.parent_node() {
56            parent.insert_before(&input, canvas.next_sibling().as_ref())?;
57        } else if let Some(body) = document.body() {
58            log::warn!("Canvas has no parent element - appending text agent to document body");
59            body.append_child(&input)?;
60        }
61
62        // Focus the app on startup, without scrolling the page.
63        // We do this instead of setting the `autofocus` attribute,
64        // since the browser scrolls the focused element into view when
65        // honoring `autofocus`, and there is no way to prevent that.
66        // See https://github.com/emilk/egui/issues/8295
67        super::focus_without_scroll(&input).ok();
68
69        // attach event listeners
70
71        runner_ref.add_event_listener(
72            &input,
73            "compositionstart",
74            move |_: web_sys::CompositionEvent, runner: &mut AppRunner| {
75                // Repaint moves the text agent into place,
76                // see `AppRunner::handle_platform_output`, which calls
77                // `TextAgent::update`.
78                runner.needs_repaint.repaint_asap();
79            },
80        )?;
81
82        runner_ref.add_event_listener(&input, "input", {
83            let input_state = Rc::clone(&input_state);
84            move |event: web_sys::InputEvent, runner: &mut AppRunner| {
85                input_state.borrow_mut().handle_input_event(&event, runner);
86            }
87        })?;
88        runner_ref.add_event_listener(&input, "compositionend", {
89            let input_state = Rc::clone(&input_state);
90            move |_event: web_sys::CompositionEvent, runner: &mut AppRunner| {
91                input_state
92                    .borrow_mut()
93                    .handle_composition_end_event(runner);
94            }
95        })?;
96
97        runner_ref.add_event_listener(&input, "keydown", {
98            let input_state = Rc::clone(&input_state);
99            move |event: web_sys::KeyboardEvent, runner: &mut AppRunner| {
100                let is_consumed = InputState::handle_keydown_event(&input_state, &event);
101                if !is_consumed {
102                    // The canvas doesn't get keydown/keyup events when the text agent is focused,
103                    // so we need to forward them to the runner:
104                    super::events::on_keydown(event, runner);
105                }
106            }
107        })?;
108        runner_ref.add_event_listener(&input, "keyup", {
109            let input_state = Rc::clone(&input_state);
110            move |event: web_sys::KeyboardEvent, runner: &mut AppRunner| {
111                let is_consumed = InputState::handle_keyup_event(&input_state, &event);
112                if !is_consumed {
113                    // The canvas doesn't get keydown/keyup events when the text agent is focused,
114                    // so we need to forward them to the runner:
115                    super::events::on_keyup(event, runner);
116                }
117            }
118        })?;
119
120        Ok(Self { input, input_state })
121    }
122
123    pub fn update(
124        &self,
125        ime: Option<egui::output::IMEOutput>,
126        canvas: &web_sys::HtmlCanvasElement,
127        zoom_factor: f32,
128    ) -> Result<(), JsValue> {
129        self.input_state
130            .borrow_mut()
131            .update(ime, canvas, zoom_factor)
132    }
133
134    pub fn set_focus(&self, on: bool) {
135        if on {
136            self.focus();
137        } else {
138            self.blur();
139        }
140    }
141
142    pub fn has_focus(&self) -> bool {
143        super::has_focus(&self.input)
144    }
145
146    pub fn focus(&self) {
147        if self.has_focus() {
148            return;
149        }
150
151        log::trace!("Focusing text agent");
152
153        if let Err(err) = super::focus_without_scroll(&self.input) {
154            log::error!("failed to set focus: {}", super::string_from_js_value(&err));
155        }
156    }
157
158    pub fn blur(&self) {
159        if !self.has_focus() {
160            return;
161        }
162
163        log::trace!("Blurring text agent");
164
165        if let Err(err) = self.input.blur() {
166            log::error!("failed to set focus: {}", super::string_from_js_value(&err));
167        }
168        self.input_state.borrow_mut().clear();
169    }
170
171    pub(crate) fn interrupt_ime_composition(&self) {
172        self.input_state.borrow_mut().clear();
173    }
174}
175
176impl Drop for TextAgent {
177    fn drop(&mut self) {
178        self.input.remove();
179    }
180}
181
182struct InputState {
183    input: web_sys::HtmlInputElement,
184    last_text: String,
185    ime_output: Option<egui::output::IMEOutput>,
186    keydown_special_case: KeydownSpecialCase,
187}
188
189#[derive(Clone, Copy)]
190enum KeydownSpecialCase {
191    None,
192
193    /// On Android Gboard 14.7.09, when suggestions remain visible while typing
194    /// letters without IME composition (e.g., Latin or Cyrillic), pressing
195    /// Backspace produces key code 229 instead of the expected Backspace key
196    /// code.
197    /// Without the workaround, users have to press Backspace twice before text
198    /// starts being deleted.
199    ///
200    /// This workaround is also required for Android Gboard corrections and
201    /// completions (e.g., `tex|` -> `Texas`) to work correctly. In these
202    /// cases, a `deleteContentBackward` input event fires first (e.g., to
203    /// delete `tex`), followed by an `insertText` input event (e.g., to insert
204    /// `Texas`).
205    ///
206    /// Since it is difficult to distinguish between a Backspace press and a
207    /// correction or completion (e.g., when the state is `t|`, it is unclear
208    /// whether the user wants to delete `t` or replace it with `Texas`), we
209    /// send a `DeleteSurrounding` IME event in all cases instead of
210    /// synthetically generating Backspace press and release events.
211    AndroidKeycode229,
212
213    /// iOS (18.6)'s built-in Korean keyboard uses `deleteContentBackward` to
214    /// compose Hangul characters. In these cases, the key code is 0.
215    IosKeycode0,
216}
217
218impl InputState {
219    fn new(input: web_sys::HtmlInputElement) -> Self {
220        Self {
221            input,
222            last_text: String::new(),
223            ime_output: None,
224            keydown_special_case: KeydownSpecialCase::None,
225        }
226    }
227
228    fn update(
229        &mut self,
230        ime: Option<egui::output::IMEOutput>,
231        canvas: &web_sys::HtmlCanvasElement,
232        zoom_factor: f32,
233    ) -> Result<(), JsValue> {
234        // Don't move the text agent unless the position actually changed:
235        if self.ime_output == ime {
236            return Ok(());
237        }
238        self.ime_output = ime;
239
240        let Some(ime) = ime else { return Ok(()) };
241
242        // NOTE: we don't set the input's `type` to `password` based on
243        // `ime.purpose`, because that would confuse some password managers.
244        // For example, Chrome's password manager will always think the last
245        // letter typed in the password field is the password.
246
247        let style = self.input.style();
248        let native_ppp = super::native_pixels_per_point();
249
250        // The input is a sibling of the canvas (see `attach`), so we position
251        // it relative to the same containing block using the canvas offset.
252        // Unlike `get_bounding_client_rect`, the offset is unaffected by page
253        // scrolling, and doesn't flap when the virtual keyboard is shown on
254        // mobile Safari.
255
256        // Clamp the input position within the canvas width to prevent unwanted horizontal scrolling.
257        let logical_canvas_width = canvas.width() as f32 / native_ppp;
258        let visible_x = ime.cursor_rect.center().x * zoom_factor;
259        let clamped_x = visible_x.clamp(0.0, logical_canvas_width);
260
261        // Clamp the input position within the canvas height to prevent unwanted vertical scrolling.
262        let logical_canvas_height = canvas.height() as f32 / native_ppp;
263        let visible_y = ime.cursor_rect.center().y * zoom_factor;
264        let clamped_y = visible_y.clamp(0.0, logical_canvas_height);
265
266        // This is where the IME input will point to:
267        style.set_property(
268            "left",
269            &format!("{}px", canvas.offset_left() as f32 + clamped_x),
270        )?;
271        style.set_property(
272            "top",
273            &format!("{}px", canvas.offset_top() as f32 + clamped_y),
274        )?;
275
276        Ok(())
277    }
278
279    fn clear(&mut self) {
280        self.input.set_value("");
281        self.last_text.clear();
282    }
283
284    fn handle_input_event(&mut self, event: &web_sys::InputEvent, runner: &mut AppRunner) {
285        if self
286            .ime_output
287            .as_ref()
288            .is_some_and(|ime| ime.purpose == egui::IMEPurpose::Password)
289        {
290            self.handle_input_event_password(event, runner);
291            return;
292        }
293
294        let input_type = event.input_type();
295
296        if !event.is_composing()
297            && input_type != "insertText"
298            // iOS uses this for corrections and completions (e.g., `tex|` ->
299            // `Texas`).
300            && input_type != "insertReplacementText"
301            && (matches!(self.keydown_special_case, KeydownSpecialCase::None)
302                || input_type != "deleteContentBackward")
303        {
304            self.clear();
305
306            return;
307        }
308
309        let text = self.input.value();
310
311        let prefix_len = longest_common_prefix_length(&text, &self.last_text);
312        let last_text_len = self.last_text.chars().count();
313        if prefix_len < last_text_len {
314            let out_event = egui::Event::Ime(egui::ImeEvent::DeleteSurrounding {
315                before_chars: last_text_len - prefix_len,
316                after_chars: 0,
317            });
318            runner.input.raw.events.push(out_event);
319        }
320
321        let preedit_text: String = text.chars().skip(prefix_len).collect();
322        let out_event = if event.is_composing() {
323            // We handle the composition update here instead of in a
324            // `compositionupdate` event because the selection range
325            // has not yet been updated when `compositionupdate` fires.
326            let active_range_chars = self.active_range_chars(&text, prefix_len);
327            egui::Event::Ime(egui::ImeEvent::Preedit {
328                text: preedit_text,
329                active_range_chars,
330            })
331        } else {
332            egui::Event::Text(preedit_text)
333        };
334        runner.input.raw.events.push(out_event);
335
336        if event.is_composing() {
337            self.last_text = text.chars().take(prefix_len).collect();
338        } else {
339            self.last_text = text;
340        }
341
342        runner.needs_repaint.repaint_asap();
343    }
344
345    fn handle_input_event_password(&mut self, event: &web_sys::InputEvent, runner: &mut AppRunner) {
346        let input_type = event.input_type();
347
348        if input_type != "insertText" {
349            return;
350        }
351
352        let text = self.input.value();
353
354        runner.input.raw.events.push(egui::Event::Text(text));
355        self.clear();
356    }
357
358    /// Compute the active range (cursor or conversion segment) within the
359    /// preedit text, based on the selection in the input element.
360    ///
361    /// `text` is the full `input.value()`, and `prefix_len_chars` is the
362    /// number of chars at the start of `text` that are committed (not part
363    /// of the preedit). `selectionStart`/`selectionEnd` are UTF-16 offsets
364    /// within the full `input.value()`, so they are adjusted to be relative
365    /// to the preedit text.
366    fn active_range_chars(
367        &self,
368        text: &str,
369        prefix_len_chars: usize,
370    ) -> Option<core::ops::Range<usize>> {
371        let selection_start = self.input.selection_start().unwrap_or(None)? as usize;
372        let selection_end = self.input.selection_end().unwrap_or(None)? as usize;
373
374        let text_utf16 = text.encode_utf16().collect::<Vec<u16>>();
375        if selection_start > text_utf16.len() || selection_end > text_utf16.len() {
376            // This can occur on Android Chrome. see discussion in:
377            // <https://github.com/emilk/egui/pull/8045>.
378            return None;
379        }
380
381        let text_before_selection = String::from_utf16_lossy(&text_utf16[..selection_start]);
382        let text_in_selection =
383            String::from_utf16_lossy(&text_utf16[selection_start..selection_end]);
384        let count_before_selection = text_before_selection.chars().count();
385        let count_in_selection = text_in_selection.chars().count();
386
387        // Adjust for the committed prefix to get the range within the preedit text.
388        let start = count_before_selection.saturating_sub(prefix_len_chars);
389        let end = start + count_in_selection;
390        Some(start..end)
391    }
392
393    fn handle_composition_end_event(&mut self, runner: &mut AppRunner) {
394        let text = self.input.value();
395
396        let commit_text = {
397            let prefix_len = self.last_text.chars().count();
398            text.chars().skip(prefix_len).collect::<String>()
399        };
400        let out_event = egui::Event::Ime(egui::ImeEvent::Commit(commit_text));
401        runner.input.raw.events.push(out_event);
402
403        self.last_text = text;
404
405        runner.needs_repaint.repaint_asap();
406    }
407
408    /// ## Returns
409    /// Whether the event is consumed. If `true`, the caller should not do
410    /// further processing for this event.
411    fn handle_keydown_event(input_state: &RefCell<Self>, event: &web_sys::KeyboardEvent) -> bool {
412        // Platform-sniffing methods are unreliable, so they are not used as
413        // guards here.
414        let special_case = match event.key_code() {
415            229 => KeydownSpecialCase::AndroidKeycode229,
416            0 => KeydownSpecialCase::IosKeycode0,
417            _ => KeydownSpecialCase::None,
418        };
419        input_state.borrow_mut().keydown_special_case = special_case;
420
421        // https://web.archive.org/web/20200526195704/https://www.fxsitecompat.dev/en-CA/docs/2018/keydown-and-keyup-events-are-now-fired-during-ime-composition/
422        if event.is_composing() || !matches!(special_case, KeydownSpecialCase::None) {
423            true
424        } else {
425            if event.key().chars().count() > 1
426                || event.ctrl_key()
427                || event.alt_key()
428                || event.meta_key()
429            {
430                input_state.borrow_mut().clear();
431            }
432            false
433        }
434    }
435
436    /// ## Returns
437    /// Whether the event is consumed. If `true`, the caller should not do
438    /// further processing for this event.
439    fn handle_keyup_event(input_state: &RefCell<Self>, event: &web_sys::KeyboardEvent) -> bool {
440        input_state.borrow_mut().keydown_special_case = KeydownSpecialCase::None;
441
442        // https://web.archive.org/web/20200526195704/https://www.fxsitecompat.dev/en-CA/docs/2018/keydown-and-keyup-events-are-now-fired-during-ime-composition/
443        event.is_composing() || event.key_code() == 229
444    }
445}
446
447fn longest_common_prefix_length(a: &str, b: &str) -> usize {
448    core::iter::zip(a.chars(), b.chars())
449        .take_while(|(a, b)| a == b)
450        .count()
451}