Skip to content

Commit c8d105d

Browse files
emilkhacknus
authored andcommitted
eframe web: ignore keyboard events unless canvas has focus (emilk#4718)
* Fixes rerun-io/rerun#6638 * Related? emilk#4563 This improves how an eframe canvas works inside of a larger web page, and how it works when there are multiple eframe apps in the same page. `eframe` will set `tabindex="0"` on the canvas automatically, making it focusable. It will also set `outline: none` on the CSS, so the focused canvas won't have an ugly outline. ## Breaking changes You may wanna add this to your `index.html` to give the canvas focus on startup: ```js document.getElementById("the_canvas_id").focus(); ``` ## Test setup ```sh ./scripts/build_demo_web.sh ./scripts/start_server.sh open http://localhost:8888/multiple_apps.html ``` Then open the "Input Event History" and "Text Edit" windows ## Tested * Chromium * [x] drag-and-drop of files * Test both when a `TextEdit` is focused and when it is not: * [x] `Event::Key` * [x] `Event::Text` * [x] copy-cut-paste * [x] Wheel scroll * [x] `Event::PointerGone` * [x] Mouse drag * [x] Mouse click * [x] Mouse right-click * [x] Defocus all eframe canvas, and then start typing text * [x] Firefox (all of the above) * [x] Desktop Safari (all of the above) * [x] Mobile Safari ## Future work (pre-existing issues) * emilk#4723 * emilk#4724 * emilk#4725 * emilk#4726
1 parent c5c421f commit c8d105d

File tree

8 files changed

+224
-137
lines changed

8 files changed

+224
-137
lines changed

crates/eframe/src/web/app_runner.rs

+4
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,10 @@ impl AppRunner {
187187
///
188188
/// The result can be painted later with a call to [`Self::run_and_paint`] or [`Self::paint`].
189189
pub fn logic(&mut self) {
190+
// We sometimes miss blur/focus events due to the text agent, so let's just poll each frame:
191+
self.input
192+
.set_focus(super::has_focus(self.canvas()) || self.text_agent.has_focus());
193+
190194
let canvas_size = super::canvas_size_in_points(self.canvas(), self.egui_ctx());
191195
let mut raw_input = self.input.new_frame(canvas_size);
192196

crates/eframe/src/web/backend.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,12 @@ impl WebInput {
3636
raw_input
3737
}
3838

39-
/// On alt-tab and similar.
40-
pub fn on_web_page_focus_change(&mut self, focused: bool) {
39+
/// On alt-tab, or user clicking another HTML element.
40+
pub fn set_focus(&mut self, focused: bool) {
41+
if self.raw.focused == focused {
42+
return;
43+
}
44+
4145
// log::debug!("on_web_page_focus_change: {focused}");
4246
self.raw.modifiers = egui::Modifiers::default(); // Avoid sticky modifier keys on alt-tab:
4347
self.raw.focused = focused;

0 commit comments

Comments
 (0)