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