Skip to main content

eframe/web/
mod.rs

1//! [`egui`] bindings for web apps (compiling to WASM).
2
3#![expect(clippy::missing_errors_doc)] // So many `-> Result<_, JsValue>`
4#![expect(clippy::unwrap_used)] // TODO(emilk): remove unwraps
5
6mod app_runner;
7mod backend;
8mod dropped_file;
9mod events;
10mod input;
11mod panic_handler;
12mod text_agent;
13mod web_logger;
14mod web_runner;
15
16/// Access to the browser screen reader.
17#[cfg(feature = "web_screen_reader")]
18pub mod screen_reader;
19
20/// Access to local browser storage.
21pub mod storage;
22
23pub(crate) use app_runner::AppRunner;
24pub use panic_handler::{PanicHandler, PanicSummary};
25pub use web_logger::WebLogger;
26pub use web_runner::WebRunner;
27
28#[cfg(not(any(feature = "glow", feature = "wgpu_no_default_features")))]
29compile_error!("You must enable either the 'glow' or 'wgpu' feature");
30
31mod web_painter;
32
33#[cfg(feature = "glow")]
34mod web_painter_glow;
35
36#[cfg(feature = "wgpu_no_default_features")]
37mod web_painter_wgpu;
38
39pub use backend::*;
40
41use egui::Theme;
42use js_sys::Object;
43use wasm_bindgen::prelude::*;
44use web_sys::{Document, MediaQueryList, Node};
45
46use input::{
47    button_from_mouse_event, modifiers_from_kb_event, modifiers_from_mouse_event,
48    modifiers_from_wheel_event, pos_from_mouse_event, primary_touch_pos, push_touches,
49    text_from_keyboard_event, translate_key,
50};
51
52// ----------------------------------------------------------------------------
53
54/// Debug browser resizing?
55const DEBUG_RESIZE: bool = false;
56
57pub(crate) fn string_from_js_value(value: &JsValue) -> String {
58    value.as_string().unwrap_or_else(|| format!("{value:#?}"))
59}
60
61/// Returns the `Element` with active focus.
62///
63/// Elements can only be focused if they are:
64/// - `<a>`/`<area>` with an `href` attribute
65/// - `<input>`/`<select>`/`<textarea>`/`<button>` which aren't `disabled`
66/// - any other element with a `tabindex` attribute
67pub(crate) fn focused_element(root: &Node) -> Option<web_sys::Element> {
68    if let Some(document) = root.dyn_ref::<Document>() {
69        document.active_element()
70    } else if let Some(shadow) = root.dyn_ref::<web_sys::ShadowRoot>() {
71        shadow.active_element()
72    } else {
73        None
74    }
75}
76
77pub(crate) fn has_focus<T: JsCast>(element: &T) -> bool {
78    fn try_has_focus<T: JsCast>(element: &T) -> Option<bool> {
79        let element = element.dyn_ref::<web_sys::Element>()?;
80        let root = element.get_root_node();
81
82        let focused_element = focused_element(&root)?;
83        Some(element == &focused_element)
84    }
85    try_has_focus(element).unwrap_or(false)
86}
87
88/// Focus the given element without scrolling it into view.
89///
90/// Scrolling the element into view would scroll the whole page when
91/// the app is embedded in a larger scrollable page,
92/// see <https://github.com/emilk/egui/issues/8295>.
93pub(crate) fn focus_without_scroll(element: &web_sys::HtmlElement) -> Result<(), JsValue> {
94    let options = web_sys::FocusOptions::new();
95    options.set_prevent_scroll(true);
96    element.focus_with_options(&options)
97}
98
99/// Current time in seconds (since undefined point in time).
100///
101/// Monotonically increasing.
102pub fn now_sec() -> f64 {
103    web_sys::window()
104        .expect("should have a Window")
105        .performance()
106        .expect("should have a Performance")
107        .now()
108        / 1000.0
109}
110
111/// The native GUI scale factor, taking into account the browser zoom.
112///
113/// Corresponds to [`window.devicePixelRatio`](https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio) in JavaScript.
114pub fn native_pixels_per_point() -> f32 {
115    let pixels_per_point = web_sys::window().unwrap().device_pixel_ratio() as f32;
116    if pixels_per_point > 0.0 && pixels_per_point.is_finite() {
117        pixels_per_point
118    } else {
119        1.0
120    }
121}
122
123/// Ask the browser about the preferred system theme.
124///
125/// `None` means unknown.
126pub fn system_theme() -> Option<egui::Theme> {
127    let window = web_sys::window()?;
128    if does_prefer_color_scheme(&window, Theme::Dark) == Some(true) {
129        Some(Theme::Dark)
130    } else if does_prefer_color_scheme(&window, Theme::Light) == Some(true) {
131        Some(Theme::Light)
132    } else {
133        None
134    }
135}
136
137fn does_prefer_color_scheme(window: &web_sys::Window, theme: Theme) -> Option<bool> {
138    Some(prefers_color_scheme(window, theme).ok()??.matches())
139}
140
141fn prefers_color_scheme(
142    window: &web_sys::Window,
143    theme: Theme,
144) -> Result<Option<MediaQueryList>, JsValue> {
145    let theme = match theme {
146        Theme::Dark => "dark",
147        Theme::Light => "light",
148    };
149    window.match_media(format!("(prefers-color-scheme: {theme})").as_str())
150}
151
152/// Returns the canvas in client coordinates.
153fn canvas_content_rect(canvas: &web_sys::HtmlCanvasElement) -> egui::Rect {
154    let bounding_rect = canvas.get_bounding_client_rect();
155
156    let mut rect = egui::Rect::from_min_max(
157        egui::pos2(bounding_rect.left() as f32, bounding_rect.top() as f32),
158        egui::pos2(bounding_rect.right() as f32, bounding_rect.bottom() as f32),
159    );
160
161    // We need to subtract padding and border:
162    if let Some(window) = web_sys::window()
163        && let Ok(Some(style)) = window.get_computed_style(canvas)
164    {
165        let get_property = |name: &str| -> Option<f32> {
166            let property = style.get_property_value(name).ok()?;
167            property.trim_end_matches("px").parse::<f32>().ok()
168        };
169
170        rect.min.x += get_property("padding-left").unwrap_or_default();
171        rect.min.y += get_property("padding-top").unwrap_or_default();
172        rect.max.x -= get_property("padding-right").unwrap_or_default();
173        rect.max.y -= get_property("padding-bottom").unwrap_or_default();
174    }
175
176    rect
177}
178
179fn canvas_size_in_points(canvas: &web_sys::HtmlCanvasElement, ctx: &egui::Context) -> egui::Vec2 {
180    // ctx.pixels_per_point can be outdated
181
182    let pixels_per_point = ctx.zoom_factor() * native_pixels_per_point();
183
184    egui::vec2(
185        canvas.width() as f32 / pixels_per_point,
186        canvas.height() as f32 / pixels_per_point,
187    )
188}
189
190// ----------------------------------------------------------------------------
191
192/// Set the cursor icon.
193fn set_cursor_icon(canvas: &web_sys::HtmlCanvasElement, cursor: egui::CursorIcon) -> Option<()> {
194    canvas
195        .style()
196        .set_property("cursor", cursor_web_name(cursor))
197        .ok()
198}
199
200/// Set the clipboard text.
201fn set_clipboard_text(s: &str) {
202    if let Some(window) = web_sys::window() {
203        if !window.is_secure_context() {
204            log::error!(
205                "Clipboard is not available because we are not in a secure context. \
206                See https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts"
207            );
208            return;
209        }
210        let promise = window.navigator().clipboard().write_text(s);
211        let future = async move {
212            if let Err(err) = promise.await {
213                log::error!("Copy/cut action failed: {}", string_from_js_value(&err));
214            }
215        };
216        js_sys::futures::spawn_local(future);
217    }
218}
219
220/// Set the clipboard image.
221fn set_clipboard_image(image: &egui::ColorImage) {
222    if let Some(window) = web_sys::window() {
223        if !window.is_secure_context() {
224            log::error!(
225                "Clipboard is not available because we are not in a secure context. \
226                See https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts"
227            );
228            return;
229        }
230
231        let png_bytes = to_image(image).and_then(|image| to_png_bytes(&image));
232        let png_bytes = match png_bytes {
233            Ok(png_bytes) => png_bytes,
234            Err(err) => {
235                log::error!("Failed to encode image to png: {err}");
236                return;
237            }
238        };
239
240        let mime = "image/png";
241
242        let item = match create_clipboard_item(mime, &png_bytes) {
243            Ok(item) => item,
244            Err(err) => {
245                log::error!("Failed to copy image: {}", string_from_js_value(&err));
246                return;
247            }
248        };
249        let items = js_sys::Array::of1(&item);
250        let promise = window.navigator().clipboard().write(&items);
251        let future = async move {
252            if let Err(err) = promise.await {
253                log::error!(
254                    "Copy/cut image action failed: {}",
255                    string_from_js_value(&err)
256                );
257            }
258        };
259        js_sys::futures::spawn_local(future);
260    }
261}
262
263fn to_image(image: &egui::ColorImage) -> Result<image::RgbaImage, String> {
264    profiling::function_scope!();
265    image::RgbaImage::from_raw(
266        image.width() as _,
267        image.height() as _,
268        bytemuck::cast_slice(&image.pixels).to_vec(),
269    )
270    .ok_or_else(|| "Invalid IconData".to_owned())
271}
272
273fn to_png_bytes(image: &image::RgbaImage) -> Result<Vec<u8>, String> {
274    profiling::function_scope!();
275    let mut png_bytes: Vec<u8> = Vec::new();
276    image
277        .write_to(
278            &mut std::io::Cursor::new(&mut png_bytes),
279            image::ImageFormat::Png,
280        )
281        .map_err(|err| err.to_string())?;
282    Ok(png_bytes)
283}
284
285fn create_clipboard_item(mime: &str, bytes: &[u8]) -> Result<web_sys::ClipboardItem, JsValue> {
286    let array = js_sys::Uint8Array::from(bytes);
287    let blob_parts = js_sys::Array::new();
288    blob_parts.push(&array);
289
290    let options = web_sys::BlobPropertyBag::new();
291    options.set_type(mime);
292
293    let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&blob_parts, &options)?;
294
295    let items = js_sys::Object::new();
296
297    #[expect(unsafe_code, unused_unsafe)] // Weird false positive
298    // SAFETY: I hope so
299    unsafe {
300        js_sys::Reflect::set(&items, &JsValue::from_str(mime), &blob)?
301    };
302
303    let clipboard_item = web_sys::ClipboardItem::new_with_record_from_str_to_blob_promise(&items)?;
304
305    Ok(clipboard_item)
306}
307
308fn cursor_web_name(cursor: egui::CursorIcon) -> &'static str {
309    match cursor {
310        egui::CursorIcon::Alias => "alias",
311        egui::CursorIcon::AllScroll => "all-scroll",
312        egui::CursorIcon::Cell => "cell",
313        egui::CursorIcon::ContextMenu => "context-menu",
314        egui::CursorIcon::Copy => "copy",
315        egui::CursorIcon::Crosshair => "crosshair",
316        egui::CursorIcon::Default => "default",
317        egui::CursorIcon::Grab => "grab",
318        egui::CursorIcon::Grabbing => "grabbing",
319        egui::CursorIcon::Help => "help",
320        egui::CursorIcon::Move => "move",
321        egui::CursorIcon::NoDrop => "no-drop",
322        egui::CursorIcon::None => "none",
323        egui::CursorIcon::NotAllowed => "not-allowed",
324        egui::CursorIcon::PointingHand => "pointer",
325        egui::CursorIcon::Progress => "progress",
326        egui::CursorIcon::ResizeHorizontal => "ew-resize",
327        egui::CursorIcon::ResizeNeSw => "nesw-resize",
328        egui::CursorIcon::ResizeNwSe => "nwse-resize",
329        egui::CursorIcon::ResizeVertical => "ns-resize",
330
331        egui::CursorIcon::ResizeEast => "e-resize",
332        egui::CursorIcon::ResizeSouthEast => "se-resize",
333        egui::CursorIcon::ResizeSouth => "s-resize",
334        egui::CursorIcon::ResizeSouthWest => "sw-resize",
335        egui::CursorIcon::ResizeWest => "w-resize",
336        egui::CursorIcon::ResizeNorthWest => "nw-resize",
337        egui::CursorIcon::ResizeNorth => "n-resize",
338        egui::CursorIcon::ResizeNorthEast => "ne-resize",
339        egui::CursorIcon::ResizeColumn => "col-resize",
340        egui::CursorIcon::ResizeRow => "row-resize",
341
342        egui::CursorIcon::Text => "text",
343        egui::CursorIcon::VerticalText => "vertical-text",
344        egui::CursorIcon::Wait => "wait",
345        egui::CursorIcon::ZoomIn => "zoom-in",
346        egui::CursorIcon::ZoomOut => "zoom-out",
347    }
348}
349
350/// Open the given url in the browser.
351pub fn open_url(url: &str, new_tab: bool) -> Option<()> {
352    let name = if new_tab { "_blank" } else { "_self" };
353
354    web_sys::window()?
355        .open_with_url_and_target(url, name)
356        .ok()?;
357    Some(())
358}
359
360/// e.g. "#fragment" part of "www.example.com/index.html#fragment",
361///
362/// Percent decoded
363pub fn location_hash() -> String {
364    percent_decode(
365        &web_sys::window()
366            .unwrap()
367            .location()
368            .hash()
369            .unwrap_or_default(),
370    )
371}
372
373/// Percent-decodes a string.
374pub fn percent_decode(s: &str) -> String {
375    percent_encoding::percent_decode_str(s)
376        .decode_utf8_lossy()
377        .to_string()
378}
379
380/// Are we running inside the Safari browser?
381pub fn is_safari_browser() -> bool {
382    web_sys::window().is_some_and(|window| Object::has_own(&window, &JsValue::from("safari")))
383}