Skip to main content

euv_example/app/
fn.rs

1use super::*;
2
3/// Builds an `App` and reactive `ShowcaseState` configured for either native OS or headless mode.
4///
5/// # Arguments
6///
7/// - `bool` - When `true`, uses deterministic `HeadlessPlatform`; otherwise uses the active native OS backend.
8/// - `RenderMode` - Initial rendering pipeline mode.
9///
10/// # Returns
11///
12/// - `Result<(App, ShowcaseState), PlatformError>` - Initialized showcase app and state.
13pub fn create_showcase_app(
14    headless: bool,
15    mode: RenderMode,
16) -> Result<(App, ShowcaseState), PlatformError> {
17    EuvOverlayStack::clear();
18    reset_fullscreen_state();
19    clear_provided_theme();
20    let render_cfg: RenderConfig = match mode {
21        RenderMode::Software => RenderConfig::software(),
22        RenderMode::Hardware => RenderConfig::hardware(),
23        RenderMode::Hybrid => RenderConfig::hybrid(),
24        RenderMode::Auto => RenderConfig::default(),
25    };
26    let mut window_cfg: WindowConfig = WindowConfig::default();
27    window_cfg
28        .set_title(SHOWCASE_WINDOW_TITLE.to_string())
29        .set_size(SHOWCASE_WINDOW_WIDTH, SHOWCASE_WINDOW_HEIGHT)
30        .set_render(render_cfg);
31    let mut app_cfg: AppConfig = AppConfig::default();
32    app_cfg.set_window(window_cfg);
33    let mut app: App = if headless {
34        App::headless(app_cfg)?
35    } else {
36        App::new(app_cfg)?
37    };
38    let mut state: ShowcaseState = ShowcaseState::new();
39    let host_plat_idx: usize = match app.platform_kind() {
40        PlatformKind::Ios => 0,
41        PlatformKind::IpadOs => 1,
42        PlatformKind::Android => 2,
43        PlatformKind::MacOs => 3,
44        PlatformKind::Windows => 4,
45        PlatformKind::Linux => 5,
46        PlatformKind::Web | PlatformKind::Headless => 6,
47    };
48    let _: bool = state
49        .get_os_target_platform_idx()
50        .set_if_changed(host_plat_idx);
51    state.attach_dynamic_hub(app.get_dynamic_hub().clone());
52    app.attach_game_host(state.get_game_host().clone());
53    app.attach_game_host(state.get_game3d_host().clone());
54    let mount_state: ShowcaseState = state.clone();
55    let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
56    Ok((app, state))
57}
58
59/// Builds an `App` and reactive `ShowcaseState` reporting a specific host `PlatformKind` (for native mobile hosts).
60///
61/// # Arguments
62///
63/// - `PlatformKind` - Active native host platform identity (e.g. `PlatformKind::Android`, `PlatformKind::Ios`).
64/// - `RenderMode` - Initial rendering pipeline mode.
65///
66/// # Returns
67///
68/// - `Result<(App, ShowcaseState), PlatformError>` - Initialized showcase app and state.
69pub fn create_showcase_app_for_platform(
70    platform: PlatformKind,
71    mode: RenderMode,
72) -> Result<(App, ShowcaseState), PlatformError> {
73    EuvOverlayStack::clear();
74    reset_fullscreen_state();
75    clear_provided_theme();
76    let render_cfg: RenderConfig = match mode {
77        RenderMode::Software => RenderConfig::software(),
78        RenderMode::Hardware => RenderConfig::hardware(),
79        RenderMode::Hybrid => RenderConfig::hybrid(),
80        RenderMode::Auto => RenderConfig::default(),
81    };
82    let mut window_cfg: WindowConfig = WindowConfig::default();
83    window_cfg
84        .set_title(SHOWCASE_WINDOW_TITLE.to_string())
85        .set_size(SHOWCASE_WINDOW_WIDTH, SHOWCASE_WINDOW_HEIGHT)
86        .set_render(render_cfg);
87    let mut app_cfg: AppConfig = AppConfig::default();
88    app_cfg.set_window(window_cfg);
89    let backend: Box<dyn PlatformBackend> = Box::new(HeadlessPlatform::emulating(
90        platform,
91        1.0,
92        SafeAreaInsets::default(),
93    ));
94    let mut app: App = App::with_platform(app_cfg, backend)?;
95    let mut state: ShowcaseState = ShowcaseState::new();
96    let host_plat_idx: usize = match app.platform_kind() {
97        PlatformKind::Ios => 0,
98        PlatformKind::IpadOs => 1,
99        PlatformKind::Android => 2,
100        PlatformKind::MacOs => 3,
101        PlatformKind::Windows => 4,
102        PlatformKind::Linux => 5,
103        PlatformKind::Web | PlatformKind::Headless => 6,
104    };
105    let _: bool = state
106        .get_os_target_platform_idx()
107        .set_if_changed(host_plat_idx);
108    state.attach_dynamic_hub(app.get_dynamic_hub().clone());
109    app.attach_game_host(state.get_game_host().clone());
110    app.attach_game_host(state.get_game3d_host().clone());
111    let mount_state: ShowcaseState = state.clone();
112    let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
113    Ok((app, state))
114}
115
116/// Runs a complete headless smoke render of the showcase and returns frame telemetry.
117///
118/// # Arguments
119///
120/// - `RenderMode` - Rendering pipeline mode to verify.
121///
122/// # Returns
123///
124/// - `Result<FrameStats, PlatformError>` - Rendered frame statistics and deterministic pixel hash.
125pub fn run_headless_smoke(mode: RenderMode) -> Result<FrameStats, PlatformError> {
126    let (mut app, _): (App, ShowcaseState) = create_showcase_app(true, mode)?;
127    app.step_frame()
128}
129
130/// Steps one frame and writes the rendered RGBA framebuffer to `<out_dir>/<name>.rgba`.
131///
132/// # Arguments
133///
134/// - `&mut App` - Active headless application instance.
135/// - `&Path` - Output directory path.
136/// - `&str` - Frame file basename without extension.
137/// - `&mut String` - Manifest accumulator receiving `<name> <width> <height>` lines.
138/// - `&mut usize` - Running captured frame counter.
139///
140/// # Returns
141///
142/// - `Result<(), PlatformError>` - Success or platform/filesystem error.
143#[cfg(not(target_arch = "wasm32"))]
144fn dump_rgba_frame(
145    app: &mut App,
146    out_dir: &Path,
147    name: &str,
148    manifest: &mut String,
149    count: &mut usize,
150) -> Result<(), PlatformError> {
151    let _: FrameStats = app.step_frame()?;
152    for _ in 0..20 {
153        if !app.has_active_animations() {
154            break;
155        }
156        let _: FrameStats = app.step_game_frame(1.0 / 60.0)?;
157    }
158    if let Some(fb) = app.get_renderer().framebuffer() {
159        let file_name: String = format!("{name}.rgba");
160        let file_path: PathBuf = out_dir.join(&file_name);
161        fs::write(&file_path, fb.get_pixels().as_slice())
162            .map_err(|err: Error| PlatformError::SurfaceError(err.to_string()))?;
163        manifest.push_str(&format!("{name} {} {}\n", fb.get_width(), fb.get_height()));
164        *count += 1;
165    }
166    Ok(())
167}
168
169/// Renders all showcase routes, responsive viewports, dark mode, scroll positions, and overlays to raw RGBA files using native system fonts.
170///
171/// # Arguments
172///
173/// - `&Path` - Destination directory for captured `.rgba` frames and `manifest.txt`.
174///
175/// # Returns
176///
177/// - `Result<usize, PlatformError>` - Total number of captured frames.
178#[cfg(not(target_arch = "wasm32"))]
179pub fn capture_showcase_screenshots(out_dir: &Path) -> Result<usize, PlatformError> {
180    reset_reactive_runtime();
181    EuvOverlayStack::clear();
182    reset_fullscreen_state();
183    clear_provided_theme();
184    fs::create_dir_all(out_dir)
185        .map_err(|err: Error| PlatformError::InitializationFailed(err.to_string()))?;
186    let mut window_cfg: WindowConfig = WindowConfig::default();
187    window_cfg
188        .set_title(SHOWCASE_WINDOW_TITLE.to_string())
189        .set_size(1200, 800)
190        .set_render(RenderConfig::software());
191    let mut app_cfg: AppConfig = AppConfig::default();
192    app_cfg.set_window(window_cfg);
193    let backend: Box<dyn PlatformBackend> = Box::new(HeadlessPlatform::emulating(
194        PlatformKind::Headless,
195        2.0,
196        SafeAreaInsets::default(),
197    ));
198    let mut app: App = App::with_platform(app_cfg, backend)?;
199    let mut state: ShowcaseState = ShowcaseState::new();
200    state.attach_dynamic_hub(app.get_dynamic_hub().clone());
201    app.attach_game_host(state.get_game_host().clone());
202    app.attach_game_host(state.get_game3d_host().clone());
203    let mount_state: ShowcaseState = state.clone();
204    let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
205    app.get_mut_renderer()
206        .get_mut_software()
207        .set_font_provider(NativeSystemFont::system());
208    let wid: WindowId = app.get_window_state().get_id();
209    let mut manifest: String = String::new();
210    let mut count: usize = 0;
211    app.dispatch_window_event(WindowEvent::Resized(wid, 1200, 800, 2.0));
212    let desktop_routes: [(&str, &str); 12] = [
213        (ROUTE_OVERVIEW, "01_overview_desktop"),
214        (ROUTE_REACTIVE, "02_reactive_desktop"),
215        (ROUTE_RENDER, "03_render_desktop"),
216        (ROUTE_WINDOW, "04_window_desktop"),
217        (ROUTE_FORMS, "05_forms_desktop"),
218        (ROUTE_THEMES, "06_themes_desktop"),
219        (ROUTE_DATA, "07_data_desktop"),
220        (ROUTE_GAME, "08_game_desktop"),
221        (ROUTE_GAME_3D, "08b_game3d_desktop"),
222        (ROUTE_MEDIA, "08c_media_desktop"),
223        (ROUTE_OVERLAYS, "09_overlays_desktop"),
224        (ROUTE_DYNAMIC, "10_dynamic_desktop"),
225    ];
226    for (route, label) in desktop_routes.iter() {
227        let _: bool = state.get_route().set_if_changed((*route).to_string());
228        if *route == ROUTE_OVERVIEW {
229            app.dispatch_window_event(WindowEvent::PointerMove(
230                wid,
231                PointerEvent::mouse(100.0, 108.0),
232            ));
233        }
234        dump_rgba_frame(&mut app, out_dir, label, &mut manifest, &mut count)?;
235    }
236    let _: bool = state.get_route().set_if_changed(ROUTE_FORMS.to_string());
237    let _: FrameStats = app.step_frame()?;
238    app.dispatch_window_event(WindowEvent::PointerMove(
239        wid,
240        PointerEvent::mouse(600.0, 400.0),
241    ));
242    app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 420.0)));
243    dump_rgba_frame(
244        &mut app,
245        out_dir,
246        "05b_forms_scrolled",
247        &mut manifest,
248        &mut count,
249    )?;
250    let _: bool = state.get_route().set_if_changed(ROUTE_DATA.to_string());
251    let _: FrameStats = app.step_frame()?;
252    app.dispatch_window_event(WindowEvent::PointerMove(
253        wid,
254        PointerEvent::mouse(600.0, 400.0),
255    ));
256    app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 460.0)));
257    dump_rgba_frame(
258        &mut app,
259        out_dir,
260        "07b_data_vlist_scrolled",
261        &mut manifest,
262        &mut count,
263    )?;
264    app.dispatch_window_event(WindowEvent::PointerMove(
265        wid,
266        PointerEvent::mouse(320.0, 120.0),
267    ));
268    app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 720.0)));
269    dump_rgba_frame(
270        &mut app,
271        out_dir,
272        "07c_data_bottom",
273        &mut manifest,
274        &mut count,
275    )?;
276    let _: bool = state.get_route().set_if_changed(ROUTE_OVERVIEW.to_string());
277    let _: FrameStats = app.step_frame()?;
278    app.dispatch_window_event(WindowEvent::PointerMove(
279        wid,
280        PointerEvent::mouse(100.0, 108.0),
281    ));
282    dump_rgba_frame(
283        &mut app,
284        out_dir,
285        "01b_overview_hovered",
286        &mut manifest,
287        &mut count,
288    )?;
289    let _: bool = state.get_route().set_if_changed(ROUTE_OVERLAYS.to_string());
290    let _: bool = state.get_modal_open().set_if_changed(true);
291    dump_rgba_frame(
292        &mut app,
293        out_dir,
294        "09b_overlays_modal",
295        &mut manifest,
296        &mut count,
297    )?;
298    let _: bool = state.get_modal_open().set_if_changed(false);
299    let _: bool = state.get_alert_dialog_open().set_if_changed(true);
300    dump_rgba_frame(
301        &mut app,
302        out_dir,
303        "09c_overlays_alert",
304        &mut manifest,
305        &mut count,
306    )?;
307    let _: bool = state.get_alert_dialog_open().set_if_changed(false);
308    let _: bool = state.get_hover_card_open().set_if_changed(true);
309    dump_rgba_frame(
310        &mut app,
311        out_dir,
312        "09d_overlays_hovercard",
313        &mut manifest,
314        &mut count,
315    )?;
316    let _: bool = state.get_hover_card_open().set_if_changed(false);
317    let _: bool = state.get_route().set_if_changed(ROUTE_THEMES.to_string());
318    state.toggle_theme_mode();
319    dump_rgba_frame(
320        &mut app,
321        out_dir,
322        "06b_themes_dark",
323        &mut manifest,
324        &mut count,
325    )?;
326    state.toggle_theme_mode();
327    let _: bool = state.get_route().set_if_changed(ROUTE_OVERVIEW.to_string());
328    app.dispatch_window_event(WindowEvent::Resized(wid, 768, 1024, 2.0));
329    dump_rgba_frame(
330        &mut app,
331        out_dir,
332        "11_overview_tablet",
333        &mut manifest,
334        &mut count,
335    )?;
336    app.dispatch_window_event(WindowEvent::Resized(wid, 390, 844, 2.0));
337    dump_rgba_frame(
338        &mut app,
339        out_dir,
340        "12_overview_mobile",
341        &mut manifest,
342        &mut count,
343    )?;
344    app.dispatch_window_event(WindowEvent::PointerDown(
345        wid,
346        PointerEvent::mouse(350.0, 26.0),
347    ));
348    app.dispatch_window_event(WindowEvent::PointerUp(
349        wid,
350        PointerEvent::mouse(350.0, 26.0),
351    ));
352    dump_rgba_frame(
353        &mut app,
354        out_dir,
355        "12b_mobile_menu_open",
356        &mut manifest,
357        &mut count,
358    )?;
359    app.dispatch_window_event(WindowEvent::PointerDown(
360        wid,
361        PointerEvent::mouse(240.0, 26.0),
362    ));
363    app.dispatch_window_event(WindowEvent::PointerUp(
364        wid,
365        PointerEvent::mouse(240.0, 26.0),
366    ));
367    let _: bool = state.get_route().set_if_changed(ROUTE_FORMS.to_string());
368    dump_rgba_frame(
369        &mut app,
370        out_dir,
371        "13_forms_mobile",
372        &mut manifest,
373        &mut count,
374    )?;
375    fs::write(out_dir.join("manifest.txt"), manifest)
376        .map_err(|err: Error| PlatformError::SurfaceError(err.to_string()))?;
377    Ok(count)
378}
379
380/// Automatically boots the WebAssembly showcase and attaches all browser canvas, input, resize, and frame listeners in pure Rust.
381#[cfg(target_arch = "wasm32")]
382#[wasm_bindgen(start)]
383pub fn euv_web_boot() {
384    let _: u64 = euv_example_web_start();
385    let Some(win): Option<Window> = window() else {
386        return;
387    };
388    let Some(doc): Option<Document> = win.document() else {
389        return;
390    };
391    let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS) else {
392        return;
393    };
394    let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>() else {
395        return;
396    };
397    web_attach_ime_proxy(&doc);
398    register_native_action_bridge(web_native_action_bridge);
399    let _: bool = web_sync_exact_viewport(&win, &canvas);
400    let canvas_move: HtmlCanvasElement = canvas.clone();
401    let on_move: Closure<dyn FnMut(web_sys::PointerEvent)> =
402        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
403            let ptr: PointerEvent = web_pointer_from_dom(&ev, &canvas_move, None);
404            web_queue_pointer_move_event(ptr);
405        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
406    drop(canvas.add_event_listener_with_callback(
407        WEB_EVENT_POINTER_MOVE,
408        on_move.as_ref().unchecked_ref(),
409    ));
410    on_move.forget();
411    let canvas_down: HtmlCanvasElement = canvas.clone();
412    let on_down: Closure<dyn FnMut(web_sys::PointerEvent)> =
413        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
414            drop(canvas_down.set_pointer_capture(ev.pointer_id()));
415            let ptr: PointerEvent = web_pointer_from_dom(&ev, &canvas_down, Some(true));
416            web_queue_pointer_down_event(ptr);
417            if !WEB_IME_ACTIVE.with(Cell::get) {
418                drop(canvas_down.focus());
419            }
420        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
421    drop(canvas.add_event_listener_with_callback(
422        WEB_EVENT_POINTER_DOWN,
423        on_down.as_ref().unchecked_ref(),
424    ));
425    on_down.forget();
426    let canvas_up: HtmlCanvasElement = canvas.clone();
427    let on_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
428        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
429            ev.stop_propagation();
430            let ptr: PointerEvent = web_pointer_from_dom(&ev, &canvas_up, Some(false));
431            web_queue_pointer_up_event(ptr);
432            drop(canvas_up.release_pointer_capture(ev.pointer_id()));
433        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
434    drop(
435        canvas
436            .add_event_listener_with_callback(WEB_EVENT_POINTER_UP, on_up.as_ref().unchecked_ref()),
437    );
438    on_up.forget();
439    let on_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
440        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
441            ev.stop_propagation();
442            web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
443        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
444    drop(canvas.add_event_listener_with_callback(
445        WEB_EVENT_POINTER_CANCEL,
446        on_cancel.as_ref().unchecked_ref(),
447    ));
448    drop(canvas.add_event_listener_with_callback(
449        WEB_EVENT_LOST_POINTER_CAPTURE,
450        on_cancel.as_ref().unchecked_ref(),
451    ));
452    on_cancel.forget();
453    let canvas_win_up: HtmlCanvasElement = canvas.clone();
454    let on_win_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
455        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
456            let ptr: PointerEvent = web_pointer_from_dom(&ev, &canvas_win_up, Some(false));
457            web_queue_pointer_up_event(ptr);
458        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
459    drop(win.add_event_listener_with_callback(
460        WEB_EVENT_POINTER_UP,
461        on_win_up.as_ref().unchecked_ref(),
462    ));
463    on_win_up.forget();
464    let on_win_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
465        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
466            web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
467        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
468    drop(win.add_event_listener_with_callback(
469        WEB_EVENT_POINTER_CANCEL,
470        on_win_cancel.as_ref().unchecked_ref(),
471    ));
472    on_win_cancel.forget();
473    let on_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
474        web_queue_pointer_cancel(0);
475        web_dispatch_system_event(SystemEvent::FocusChanged(false));
476    }) as Box<dyn FnMut(Event)>);
477    drop(win.add_event_listener_with_callback(WEB_EVENT_BLUR, on_blur.as_ref().unchecked_ref()));
478    on_blur.forget();
479    web_attach_system_event_listeners(&win, &doc);
480    let canvas_wheel: HtmlCanvasElement = canvas.clone();
481    let on_wheel: Closure<dyn FnMut(WheelEvent)> = Closure::wrap(Box::new(move |ev: WheelEvent| {
482        ev.prevent_default();
483        let rect: DomRect = canvas_wheel.get_bounding_client_rect();
484        let x: f32 = (ev.client_x() as f64 - rect.left()) as f32;
485        let y: f32 = (ev.client_y() as f64 - rect.top()) as f32;
486        let mult: f32 = match ev.delta_mode() {
487            1 => 20.0,
488            2 => 320.0,
489            _ => 1.0,
490        };
491        web_queue_scroll_at(
492            x,
493            y,
494            (ev.delta_x() as f32) * mult,
495            (ev.delta_y() as f32) * mult,
496        );
497    })
498        as Box<dyn FnMut(WheelEvent)>);
499    drop(
500        canvas.add_event_listener_with_callback(WEB_EVENT_WHEEL, on_wheel.as_ref().unchecked_ref()),
501    );
502    on_wheel.forget();
503    let on_key: Closure<dyn FnMut(KeyboardEvent)> =
504        Closure::wrap(Box::new(move |ev: KeyboardEvent| {
505            let key: String = ev.key();
506            let code_str: String = ev.code();
507            let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
508            let should_prevent: bool = if ime_active {
509                matches!(
510                    key.as_str(),
511                    WEB_KEY_ARROW_UP
512                        | WEB_KEY_ARROW_DOWN
513                        | WEB_KEY_ARROW_LEFT
514                        | WEB_KEY_ARROW_RIGHT
515                        | WEB_KEY_BACKSPACE
516                )
517            } else {
518                matches!(
519                    key.as_str(),
520                    WEB_KEY_ARROW_UP
521                        | WEB_KEY_ARROW_DOWN
522                        | WEB_KEY_ARROW_LEFT
523                        | WEB_KEY_ARROW_RIGHT
524                        | WEB_KEY_BACKSPACE
525                        | WEB_KEY_SPACE
526                )
527            };
528            if should_prevent {
529                ev.prevent_default();
530            }
531            web_queue_key_down(&key, &code_str);
532        }) as Box<dyn FnMut(KeyboardEvent)>);
533    drop(win.add_event_listener_with_callback(WEB_EVENT_KEY_DOWN, on_key.as_ref().unchecked_ref()));
534    on_key.forget();
535    let on_key_up: Closure<dyn FnMut(KeyboardEvent)> =
536        Closure::wrap(Box::new(move |ev: KeyboardEvent| {
537            let key: String = ev.key();
538            let code_str: String = ev.code();
539            web_queue_key_up(&key, &code_str);
540        }) as Box<dyn FnMut(KeyboardEvent)>);
541    drop(
542        win.add_event_listener_with_callback(WEB_EVENT_KEY_UP, on_key_up.as_ref().unchecked_ref()),
543    );
544    on_key_up.forget();
545    let win_resize: Window = win.clone();
546    let canvas_resize: HtmlCanvasElement = canvas.clone();
547    let on_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
548        let viewport_changed: bool = web_sync_exact_viewport(&win_resize, &canvas_resize);
549        let safe_changed: bool = web_sync_safe_area();
550        if viewport_changed || safe_changed {
551            web_mark_needs_frame();
552        }
553    }) as Box<dyn FnMut(Event)>);
554    drop(
555        win.add_event_listener_with_callback(WEB_EVENT_RESIZE, on_resize.as_ref().unchecked_ref()),
556    );
557    on_resize.forget();
558    let win_raf: Window = win.clone();
559    let canvas_raf: HtmlCanvasElement = canvas.clone();
560    WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<WebRafCallback>>| {
561        if let Ok(mut guard) = slot.try_borrow_mut() {
562            *guard = Some(Closure::wrap(Box::new(move |ts: f64| {
563                WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(None));
564                if !web_should_pump_frames() {
565                    WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
566                    WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
567                    WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
568                    return;
569                }
570                let prev_ts: f64 = WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.replace(ts));
571                let mut dt: f32 = 1.0 / 60.0;
572                let mut valid_step: bool = false;
573                if prev_ts > 0.0 {
574                    let raw_dt: f32 = ((ts - prev_ts) / 1000.0) as f32;
575                    if (0.001..=0.1).contains(&raw_dt) {
576                        valid_step = true;
577                    }
578                    dt = raw_dt.clamp(0.001, 0.05);
579                }
580                if valid_step {
581                    let next_secs: f32 = WEB_RAF_ACCUM_SECS.with(Cell::get) + dt;
582                    let next_frames: u32 = WEB_RAF_ACCUM_FRAMES.with(Cell::get).saturating_add(1);
583                    if next_secs >= 0.35 && next_frames >= 8 {
584                        let measured_hz: f32 = (next_frames as f32) / next_secs;
585                        WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
586                        WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
587                        web_report_host_refresh_rate(measured_hz);
588                    } else {
589                        WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(next_secs));
590                        WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(next_frames));
591                    }
592                }
593                let resized_or_scaled: bool = web_sync_exact_viewport(&win_raf, &canvas_raf);
594                let cur_route: String = euv_web_current_route();
595                let on_game: bool = cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D;
596                let animating: bool = web_has_active_animations();
597                let dirty: bool = WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.replace(false));
598                let needs_continuous: bool = resized_or_scaled || on_game;
599                let needs_redraw: bool = animating || dirty;
600                if needs_continuous || needs_redraw {
601                    let _: u64 = web_flush_frame(dt);
602                }
603                if web_should_pump_frames() {
604                    web_start_raf_pump(&win_raf);
605                }
606            }) as Box<dyn FnMut(f64)>));
607        }
608    });
609    if doc.hidden() {
610        web_dispatch_system_event(SystemEvent::Background);
611    } else {
612        web_start_raf_pump(&win);
613    }
614}
615
616/// Returns `true` when the active WebAssembly `App` should pump `requestAnimationFrame` frames.
617///
618/// # Returns
619///
620/// - `bool` - `false` while background-frozen or shutting down.
621#[cfg(target_arch = "wasm32")]
622fn web_should_pump_frames() -> bool {
623    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
624        match slot.try_borrow() {
625            Ok(guard) => guard
626                .as_ref()
627                .map(|(app, _): &(App, ShowcaseState)| app.should_pump_frames())
628                .unwrap_or(false),
629            Err(_) => false,
630        }
631    })
632}
633
634/// Schedules the retained browser `requestAnimationFrame` callback if no frame is already pending.
635///
636/// # Arguments
637///
638/// - `&Window` - Active browser `Window`.
639#[cfg(target_arch = "wasm32")]
640fn web_start_raf_pump(win: &Window) {
641    if !web_should_pump_frames() {
642        return;
643    }
644    let already_scheduled: bool =
645        WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_some());
646    if already_scheduled {
647        return;
648    }
649    WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<WebRafCallback>>| {
650        if let Ok(cb_ref) = slot.try_borrow()
651            && let Some(cb) = cb_ref.as_ref()
652        {
653            let func: &Function = cb.as_ref().unchecked_ref();
654            if let Ok(req_id) = win.request_animation_frame(func) {
655                WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(Some(req_id)));
656            }
657        }
658    });
659}
660
661/// Cancels any pending browser `requestAnimationFrame` callback and resets rAF timing accumulators for zero-CPU background sleep.
662#[cfg(target_arch = "wasm32")]
663fn web_stop_raf_pump() {
664    let pending_id: Option<i32> = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.take());
665    if let Some(req_id) = pending_id
666        && let Some(win) = window()
667    {
668        drop(win.cancel_animation_frame(req_id));
669    }
670    WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
671    WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
672    WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
673}
674
675/// Dispatches a browser-originated `SystemEvent` into the active WebAssembly `App` and pauses or restarts the rAF pump accordingly.
676///
677/// # Arguments
678///
679/// - `SystemEvent` - Cross-platform system or lifecycle event to normalize and dispatch.
680#[cfg(target_arch = "wasm32")]
681fn web_dispatch_system_event(event: SystemEvent) {
682    let mut should_pump: bool = false;
683    let mut handled: bool = false;
684    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
685        if let Ok(mut borrow) = slot.try_borrow_mut()
686            && let Some((app, _)) = borrow.as_mut()
687        {
688            app.dispatch_system_event(event);
689            should_pump = app.should_pump_frames();
690            handled = true;
691        }
692    });
693    if !handled {
694        return;
695    }
696    if !should_pump {
697        web_stop_raf_pump();
698    } else {
699        WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
700        web_mark_needs_frame();
701        if let Some(win) = window() {
702            web_start_raf_pump(&win);
703        }
704    }
705}
706
707/// Attaches browser DOM lifecycle, focus, connectivity, color-scheme, deep-link, and soft-keyboard listeners onto `win` and `doc`.
708///
709/// # Arguments
710///
711/// - `&Window` - Active browser `Window`.
712/// - `&Document` - Active browser `Document`.
713#[cfg(target_arch = "wasm32")]
714fn web_attach_system_event_listeners(win: &Window, doc: &Document) {
715    let doc_vis: Document = doc.clone();
716    let on_vis: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
717        if doc_vis.hidden() {
718            web_dispatch_system_event(SystemEvent::Background);
719        } else {
720            web_dispatch_system_event(SystemEvent::Foreground);
721        }
722    }) as Box<dyn FnMut(Event)>);
723    drop(doc.add_event_listener_with_callback(
724        WEB_EVENT_VISIBILITY_CHANGE,
725        on_vis.as_ref().unchecked_ref(),
726    ));
727    on_vis.forget();
728    let on_focus: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
729        web_dispatch_system_event(SystemEvent::FocusChanged(true));
730    }) as Box<dyn FnMut(Event)>);
731    drop(win.add_event_listener_with_callback(WEB_EVENT_FOCUS, on_focus.as_ref().unchecked_ref()));
732    on_focus.forget();
733    let on_pageshow: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
734        web_dispatch_system_event(SystemEvent::Foreground);
735    }) as Box<dyn FnMut(Event)>);
736    drop(win.add_event_listener_with_callback(
737        WEB_EVENT_PAGE_SHOW,
738        on_pageshow.as_ref().unchecked_ref(),
739    ));
740    on_pageshow.forget();
741    let on_pagehide: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
742        web_dispatch_system_event(SystemEvent::Background);
743    }) as Box<dyn FnMut(Event)>);
744    drop(win.add_event_listener_with_callback(
745        WEB_EVENT_PAGE_HIDE,
746        on_pagehide.as_ref().unchecked_ref(),
747    ));
748    on_pagehide.forget();
749    let on_unload: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
750        web_dispatch_system_event(SystemEvent::Terminate);
751    }) as Box<dyn FnMut(Event)>);
752    drop(win.add_event_listener_with_callback(
753        WEB_EVENT_BEFORE_UNLOAD,
754        on_unload.as_ref().unchecked_ref(),
755    ));
756    on_unload.forget();
757    let on_online: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
758        web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Online));
759    }) as Box<dyn FnMut(Event)>);
760    drop(
761        win.add_event_listener_with_callback(WEB_EVENT_ONLINE, on_online.as_ref().unchecked_ref()),
762    );
763    on_online.forget();
764    let on_offline: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
765        web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Offline));
766    }) as Box<dyn FnMut(Event)>);
767    drop(
768        win.add_event_listener_with_callback(
769            WEB_EVENT_OFFLINE,
770            on_offline.as_ref().unchecked_ref(),
771        ),
772    );
773    on_offline.forget();
774    if let Ok(Some(mql)) = win.match_media(WEB_MEDIA_PREFERS_DARK) {
775        let mql_cb: MediaQueryList = mql.clone();
776        let on_theme: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
777            let next_theme: SystemTheme = if mql_cb.matches() {
778                ThemeMode::Dark
779            } else {
780                ThemeMode::Light
781            };
782            web_dispatch_system_event(SystemEvent::ThemeChanged(next_theme));
783        })
784            as Box<dyn FnMut(Event)>);
785        drop(
786            mql.add_event_listener_with_callback(
787                WEB_EVENT_CHANGE,
788                on_theme.as_ref().unchecked_ref(),
789            ),
790        );
791        on_theme.forget();
792    }
793    let win_hash: Window = win.clone();
794    let on_hash: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
795        if let Ok(href) = win_hash.location().href() {
796            web_dispatch_system_event(SystemEvent::DeepLink(href));
797        }
798    }) as Box<dyn FnMut(Event)>);
799    drop(
800        win.add_event_listener_with_callback(
801            WEB_EVENT_HASH_CHANGE,
802            on_hash.as_ref().unchecked_ref(),
803        ),
804    );
805    on_hash.forget();
806    let vv_key: JsValue = JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT);
807    if let Ok(vv_val) = Reflect::get(win.as_ref(), &vv_key)
808        && let Ok(vv_target) = vv_val.clone().dyn_into::<EventTarget>()
809    {
810        let win_vv: Window = win.clone();
811        let vv_obj: JsValue = vv_val;
812        let on_vv_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
813            let inner_h: f32 = win_vv
814                .inner_height()
815                .ok()
816                .and_then(|v: JsValue| v.as_f64())
817                .unwrap_or(0.0) as f32;
818            let h_key: JsValue = JsValue::from_str(WEB_PROP_HEIGHT);
819            let vv_h: f32 = Reflect::get(&vv_obj, &h_key)
820                .ok()
821                .and_then(|v: JsValue| v.as_f64())
822                .unwrap_or(inner_h as f64) as f32;
823            let kb_delta: f32 = (inner_h - vv_h).max(0.0);
824            let visible: bool = kb_delta >= WEB_KEYBOARD_MIN_DELTA_PX;
825            let height: f32 = if visible { kb_delta } else { 0.0 };
826            web_dispatch_system_event(SystemEvent::KeyboardVisibilityChanged { visible, height });
827            if web_sync_safe_area() {
828                web_mark_needs_frame();
829            }
830        })
831            as Box<dyn FnMut(Event)>);
832        drop(vv_target.add_event_listener_with_callback(
833            WEB_EVENT_RESIZE,
834            on_vv_resize.as_ref().unchecked_ref(),
835        ));
836        on_vv_resize.forget();
837    }
838}
839
840/// Maps a browser `KeyboardEvent.key` and physical `KeyboardEvent.code` into a cross-platform `KeyCode`.
841///
842/// # Arguments
843///
844/// - `&str` - Browser DOM `KeyboardEvent.key` string.
845/// - `&str` - Browser DOM physical `KeyboardEvent.code` string (IME-independent).
846///
847/// # Returns
848///
849/// - `KeyCode` - Normalized `euv` key code.
850#[cfg(target_arch = "wasm32")]
851fn web_map_key(key: &str, code_str: &str) -> KeyCode {
852    match code_str {
853        "KeyW" => return KeyCode::Character('w'),
854        "KeyA" => return KeyCode::Character('a'),
855        "KeyS" => return KeyCode::Character('s'),
856        "KeyD" => return KeyCode::Character('d'),
857        "KeyE" => return KeyCode::Character('e'),
858        "KeyR" => return KeyCode::Character('r'),
859        "KeyP" => return KeyCode::Character('p'),
860        "KeyJ" => return KeyCode::Character('j'),
861        "Space" => return KeyCode::Space,
862        "ArrowLeft" => return KeyCode::ArrowLeft,
863        "ArrowRight" => return KeyCode::ArrowRight,
864        "ArrowUp" => return KeyCode::ArrowUp,
865        "ArrowDown" => return KeyCode::ArrowDown,
866        _ => {}
867    }
868    match key {
869        WEB_KEY_ENTER => KeyCode::Enter,
870        WEB_KEY_BACKSPACE => KeyCode::Backspace,
871        WEB_KEY_DELETE => KeyCode::Delete,
872        WEB_KEY_ESCAPE => KeyCode::Escape,
873        WEB_KEY_TAB => KeyCode::Tab,
874        WEB_KEY_SPACE => KeyCode::Space,
875        WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
876        WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
877        WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
878        WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
879        other => other
880            .chars()
881            .next()
882            .map(KeyCode::Character)
883            .unwrap_or(KeyCode::Unknown),
884    }
885}
886
887/// Returns `true` when the active WebAssembly app has running UI transition animations.
888///
889/// # Returns
890///
891/// - `bool` - Whether animation frames must continue ticking.
892#[cfg(target_arch = "wasm32")]
893fn web_has_active_animations() -> bool {
894    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
895        match slot.try_borrow() {
896            Ok(guard) => guard
897                .as_ref()
898                .map(|(app, _): &(App, ShowcaseState)| app.has_active_animations())
899                .unwrap_or(false),
900            Err(_) => false,
901        }
902    })
903}
904
905/// Marks the coalesced Web animation-frame render flag so the next `requestAnimationFrame` flushes visual changes.
906#[cfg(target_arch = "wasm32")]
907fn web_mark_needs_frame() {
908    WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.set(true));
909}
910
911/// Normalizes a browser `PointerEvent.pointerId` into a non-zero cross-platform pointer identifier.
912///
913/// # Arguments
914///
915/// - `&web_sys::PointerEvent` - Browser DOM pointer event.
916///
917/// # Returns
918///
919/// - `u64` - Stable non-zero pointer identifier.
920#[cfg(target_arch = "wasm32")]
921fn web_pointer_id_from_dom(ev: &web_sys::PointerEvent) -> u64 {
922    (ev.pointer_id() as i64).unsigned_abs().saturating_add(1)
923}
924
925/// Converts a browser DOM `PointerEvent` into an `euv::PointerEvent` preserving pointer ID, touch/pen/mouse device, and button state.
926///
927/// # Arguments
928///
929/// - `&web_sys::PointerEvent` - Browser DOM pointer event.
930/// - `&HtmlCanvasElement` - Target canvas element for local coordinate conversion.
931/// - `Option<bool>` - Optional explicit pressed override (`Some(true)` on down, `Some(false)` on up, `None` to inspect `buttons()`).
932///
933/// # Returns
934///
935/// - `PointerEvent` - Cross-platform pointer event.
936#[cfg(target_arch = "wasm32")]
937fn web_pointer_from_dom(
938    ev: &web_sys::PointerEvent,
939    canvas: &HtmlCanvasElement,
940    force_pressed: Option<bool>,
941) -> PointerEvent {
942    let rect: DomRect = canvas.get_bounding_client_rect();
943    let x: f32 = (ev.client_x() as f64 - rect.left()) as f32;
944    let y: f32 = (ev.client_y() as f64 - rect.top()) as f32;
945    let pid: u64 = web_pointer_id_from_dom(ev);
946    let ptype: String = ev.pointer_type();
947    let device: PointerDevice = if ptype == WEB_PTR_TYPE_TOUCH {
948        PointerDevice::Touch
949    } else if ptype == WEB_PTR_TYPE_PEN {
950        PointerDevice::Stylus
951    } else {
952        PointerDevice::Mouse
953    };
954    let is_pressed: bool =
955        force_pressed.unwrap_or_else(|| ev.buttons() != 0 || device == PointerDevice::Touch);
956    let pressure: f32 = if is_pressed { 1.0 } else { 0.0 };
957    PointerEvent::new(
958        pid,
959        device,
960        Point::new(x, y),
961        PointerButton::Primary,
962        pressure,
963        Modifiers::default(),
964    )
965}
966
967/// Enqueues a browser pointer move into the active WebAssembly runtime without synchronous full-frame rasterization.
968///
969/// # Arguments
970///
971/// - `PointerEvent` - Normalized pointer move event.
972#[cfg(target_arch = "wasm32")]
973fn web_queue_pointer_move_event(ptr: PointerEvent) {
974    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
975        if let Ok(mut borrow) = slot.try_borrow_mut()
976            && let Some((app, _)) = borrow.as_mut()
977        {
978            let wid: WindowId = app.get_window_state().get_id();
979            app.dispatch_window_event(WindowEvent::PointerMove(wid, ptr));
980            web_mark_needs_frame();
981        }
982    });
983}
984
985/// Enqueues a browser pointer press into the active WebAssembly runtime for the next animation frame.
986///
987/// # Arguments
988///
989/// - `PointerEvent` - Normalized pointer press event.
990#[cfg(target_arch = "wasm32")]
991fn web_queue_pointer_down_event(ptr: PointerEvent) {
992    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
993        if let Ok(mut borrow) = slot.try_borrow_mut()
994            && let Some((app, _)) = borrow.as_mut()
995        {
996            let wid: WindowId = app.get_window_state().get_id();
997            app.dispatch_window_event(WindowEvent::PointerDown(wid, ptr));
998            web_mark_needs_frame();
999        }
1000    });
1001}
1002
1003/// Enqueues a browser pointer release into the active WebAssembly runtime for the next animation frame.
1004///
1005/// # Arguments
1006///
1007/// - `PointerEvent` - Normalized pointer release event.
1008#[cfg(target_arch = "wasm32")]
1009fn web_queue_pointer_up_event(ptr: PointerEvent) {
1010    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1011        if let Ok(mut borrow) = slot.try_borrow_mut()
1012            && let Some((app, _)) = borrow.as_mut()
1013        {
1014            let wid: WindowId = app.get_window_state().get_id();
1015            app.dispatch_window_event(WindowEvent::PointerUp(wid, ptr));
1016            web_mark_needs_frame();
1017        }
1018    });
1019}
1020
1021/// Enqueues a browser pointer cancel (`0` cancels all active contacts) into the active WebAssembly runtime.
1022///
1023/// # Arguments
1024///
1025/// - `u64` - Cancelled pointer identifier (`0` cancels all active pointers).
1026#[cfg(target_arch = "wasm32")]
1027fn web_queue_pointer_cancel(pointer_id: u64) {
1028    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1029        if let Ok(mut borrow) = slot.try_borrow_mut()
1030            && let Some((app, _)) = borrow.as_mut()
1031        {
1032            let wid: WindowId = app.get_window_state().get_id();
1033            app.dispatch_window_event(WindowEvent::PointerCancel(wid, pointer_id));
1034            web_mark_needs_frame();
1035        }
1036    });
1037}
1038
1039/// Enqueues a normalized browser wheel scroll delta at `(x, y)` for coalesced VSync rendering.
1040///
1041/// # Arguments
1042///
1043/// - `f32` - Pointer X coordinate inside the canvas.
1044/// - `f32` - Pointer Y coordinate inside the canvas.
1045/// - `f32` - Horizontal scroll delta.
1046/// - `f32` - Vertical scroll delta.
1047#[cfg(target_arch = "wasm32")]
1048fn web_queue_scroll_at(x: f32, y: f32, dx: f32, dy: f32) {
1049    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1050        if let Ok(mut borrow) = slot.try_borrow_mut()
1051            && let Some((app, _)) = borrow.as_mut()
1052        {
1053            let wid: WindowId = app.get_window_state().get_id();
1054            app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
1055            app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
1056            web_mark_needs_frame();
1057        }
1058    });
1059}
1060
1061/// Enqueues a browser key-down and optional printable text event for the next animation frame.
1062///
1063/// # Arguments
1064///
1065/// - `&str` - DOM `KeyboardEvent.key` string.
1066/// - `&str` - DOM physical `KeyboardEvent.code` string.
1067#[cfg(target_arch = "wasm32")]
1068fn web_queue_key_down(key: &str, code_str: &str) {
1069    if WEB_IME_COMPOSING.with(Cell::get) {
1070        return;
1071    }
1072    let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
1073    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1074        if let Ok(mut borrow) = slot.try_borrow_mut()
1075            && let Some((app, _)) = borrow.as_mut()
1076        {
1077            let wid: WindowId = app.get_window_state().get_id();
1078            let code: KeyCode = web_map_key(key, code_str);
1079            let key_ev: WindowEvent =
1080                WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
1081            app.dispatch_window_event(key_ev);
1082            if !ime_active && key.chars().count() == 1 {
1083                app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
1084            }
1085            web_mark_needs_frame();
1086        }
1087    });
1088}
1089
1090/// Dispatches committed browser IME or virtual keyboard text into the active WebAssembly runtime.
1091///
1092/// # Arguments
1093///
1094/// - `String` - Committed UTF-8 text from the hidden IME proxy input.
1095#[cfg(target_arch = "wasm32")]
1096fn web_queue_text_input(text: String) {
1097    if text.is_empty() {
1098        return;
1099    }
1100    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1101        if let Ok(mut borrow) = slot.try_borrow_mut()
1102            && let Some((app, _)) = borrow.as_mut()
1103        {
1104            let wid: WindowId = app.get_window_state().get_id();
1105            app.dispatch_window_event(WindowEvent::TextInput(wid, text));
1106            web_mark_needs_frame();
1107        }
1108    });
1109}
1110
1111/// Reads and clears the hidden browser IME proxy `<input>` value, dispatching any pending text into `euv`.
1112///
1113/// # Arguments
1114///
1115/// - `&HtmlElement` - Hidden browser IME proxy element.
1116#[cfg(target_arch = "wasm32")]
1117fn web_flush_ime_element(el: &HtmlElement) {
1118    let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
1119    if let Ok(val) = Reflect::get(el.as_ref(), &key)
1120        && let Some(text) = val.as_string()
1121        && !text.is_empty()
1122    {
1123        let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
1124        web_queue_text_input(text);
1125    }
1126}
1127
1128/// Attaches a visually hidden DOM `<input>` element so mobile browsers and CJK IMEs open native keyboards on input focus.
1129///
1130/// # Arguments
1131///
1132/// - `&Document` - Active browser DOM document.
1133#[cfg(target_arch = "wasm32")]
1134fn web_attach_ime_proxy(doc: &Document) {
1135    let Ok(raw_el) = doc.create_element(WEB_IME_INPUT_TAG) else {
1136        return;
1137    };
1138    let el: Element = raw_el;
1139    drop(el.set_attribute(WEB_IME_ATTR_ID, WEB_IME_INPUT_ID));
1140    drop(el.set_attribute(WEB_IME_ATTR_TYPE, WEB_IME_ATTR_TEXT));
1141    drop(el.set_attribute(WEB_IME_ATTR_AUTOCOMPLETE, WEB_IME_ATTR_OFF));
1142    drop(el.set_attribute(WEB_IME_ATTR_AUTOCORRECT, WEB_IME_ATTR_OFF));
1143    drop(el.set_attribute(WEB_IME_ATTR_AUTOCAPITALIZE, WEB_IME_ATTR_OFF));
1144    drop(el.set_attribute(WEB_IME_ATTR_SPELLCHECK, WEB_IME_ATTR_FALSE));
1145    drop(el.set_attribute(WEB_IME_ATTR_ARIA_LABEL, WEB_IME_ARIA_LABEL));
1146    drop(el.set_attribute(WEB_IME_ATTR_STYLE, WEB_IME_STYLE));
1147    let Ok(html_el) = el.dyn_into::<HtmlElement>() else {
1148        return;
1149    };
1150    if let Some(body) = doc.body() {
1151        drop(body.append_child(&html_el));
1152    }
1153    let comp_start: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1154        WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(true));
1155    }) as Box<dyn FnMut(Event)>);
1156    drop(html_el.add_event_listener_with_callback(
1157        WEB_EVENT_COMPOSITION_START,
1158        comp_start.as_ref().unchecked_ref(),
1159    ));
1160    comp_start.forget();
1161    let comp_el: HtmlElement = html_el.clone();
1162    let comp_end: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1163        WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1164        web_flush_ime_element(&comp_el);
1165    }) as Box<dyn FnMut(Event)>);
1166    drop(html_el.add_event_listener_with_callback(
1167        WEB_EVENT_COMPOSITION_END,
1168        comp_end.as_ref().unchecked_ref(),
1169    ));
1170    comp_end.forget();
1171    let inp_el: HtmlElement = html_el.clone();
1172    let on_input: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1173        if !WEB_IME_COMPOSING.with(Cell::get) {
1174            web_flush_ime_element(&inp_el);
1175        }
1176    }) as Box<dyn FnMut(Event)>);
1177    drop(
1178        html_el
1179            .add_event_listener_with_callback(WEB_EVENT_INPUT, on_input.as_ref().unchecked_ref()),
1180    );
1181    on_input.forget();
1182    let on_ime_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1183        WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
1184        WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1185        WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1186            if let Ok(mut borrow) = slot.try_borrow_mut()
1187                && let Some((app, _)) = borrow.as_mut()
1188            {
1189                let wid: WindowId = app.get_window_state().get_id();
1190                app.dispatch_window_event(WindowEvent::Ime(wid, ImeEvent::Disabled));
1191            }
1192        });
1193    }) as Box<dyn FnMut(Event)>);
1194    drop(
1195        html_el
1196            .add_event_listener_with_callback(WEB_EVENT_BLUR, on_ime_blur.as_ref().unchecked_ref()),
1197    );
1198    on_ime_blur.forget();
1199    WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
1200        if let Ok(mut guard) = slot.try_borrow_mut() {
1201            *guard = Some(html_el);
1202        }
1203    });
1204}
1205
1206/// Handles `euv` native action requests in the browser, focusing or blurring the hidden IME proxy input.
1207///
1208/// # Arguments
1209///
1210/// - `&str` - Action category (e.g. `NATIVE_ACTION_IME`).
1211/// - `&str` - Action subcommand (`"show"` or `"hide"`).
1212/// - `&str` - Secondary payload argument.
1213///
1214/// # Returns
1215///
1216/// - `bool` - `true` when handled by the browser bridge.
1217#[cfg(target_arch = "wasm32")]
1218fn web_native_action_bridge(kind: &str, arg1: &str, _arg2: &str) -> bool {
1219    if kind == NATIVE_ACTION_FULLSCREEN {
1220        if arg1 == WEB_FS_ACTION_ON {
1221            web_set_fullscreen(true);
1222            return true;
1223        }
1224        if arg1 == WEB_FS_ACTION_OFF {
1225            web_set_fullscreen(false);
1226            return true;
1227        }
1228        return false;
1229    }
1230    if kind != NATIVE_ACTION_IME {
1231        return false;
1232    }
1233    WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
1234        let Ok(guard) = slot.try_borrow() else {
1235            return false;
1236        };
1237        let Some(el) = guard.as_ref() else {
1238            return false;
1239        };
1240        if arg1 == WEB_IME_ACTION_SHOW {
1241            WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(true));
1242            if let Some(win) = window()
1243                && let Some(doc) = win.document()
1244                && let Some(active_el) = doc.active_element()
1245                && active_el.id() == WEB_IME_INPUT_ID
1246            {
1247                drop(el.blur());
1248            }
1249            drop(el.focus());
1250            true
1251        } else if arg1 == WEB_IME_ACTION_HIDE {
1252            WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
1253            WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1254            let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
1255            let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
1256            drop(el.blur());
1257            true
1258        } else {
1259            false
1260        }
1261    })
1262}
1263
1264/// Enqueues a browser key-up event into the active WebAssembly runtime and game host.
1265///
1266/// # Arguments
1267///
1268/// - `&str` - DOM `KeyboardEvent.key` string.
1269/// - `&str` - DOM physical `KeyboardEvent.code` string.
1270#[cfg(target_arch = "wasm32")]
1271fn web_queue_key_up(key: &str, code_str: &str) {
1272    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1273        if let Ok(mut borrow) = slot.try_borrow_mut()
1274            && let Some((app, _)) = borrow.as_mut()
1275        {
1276            let wid: WindowId = app.get_window_state().get_id();
1277            let code: KeyCode = web_map_key(key, code_str);
1278            app.dispatch_window_event(WindowEvent::KeyUp(
1279                wid,
1280                KeyEvent::new(code, Modifiers::default(), false),
1281            ));
1282        }
1283    });
1284}
1285
1286/// Synchronizes the WebAssembly `<canvas>` backing pixels and `App` viewport with exact 1:1 physical device pixels.
1287///
1288/// # Arguments
1289///
1290/// - `&Window` - Browser window object.
1291/// - `&HtmlCanvasElement` - Target full-viewport canvas element.
1292///
1293/// # Returns
1294///
1295/// - `bool` - `true` when physical dimensions or DPI scale changed and the viewport was updated.
1296#[cfg(target_arch = "wasm32")]
1297fn web_sync_exact_viewport(win: &Window, canvas: &HtmlCanvasElement) -> bool {
1298    let rect: DomRect = canvas.get_bounding_client_rect();
1299    let css_w: f64 = if rect.width() >= 320.0 {
1300        rect.width()
1301    } else {
1302        win.inner_width()
1303            .ok()
1304            .and_then(|v: JsValue| v.as_f64())
1305            .filter(|w: &f64| *w >= 320.0)
1306            .unwrap_or(1200.0)
1307    };
1308    let css_h: f64 = if rect.height() >= 320.0 {
1309        rect.height()
1310    } else {
1311        win.inner_height()
1312            .ok()
1313            .and_then(|v: JsValue| v.as_f64())
1314            .filter(|h: &f64| *h >= 320.0)
1315            .unwrap_or(800.0)
1316    };
1317    let dpr_raw: f64 = win.device_pixel_ratio();
1318    let dpr_f64: f64 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
1319        dpr_raw.clamp(0.5, 4.5)
1320    } else {
1321        1.0
1322    };
1323    let dpr: f32 = dpr_f64 as f32;
1324    let phys_w: u32 = (css_w * dpr_f64).round().max(1.0) as u32;
1325    let phys_h: u32 = (css_h * dpr_f64).round().max(1.0) as u32;
1326    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1327        let Ok(mut borrow) = slot.try_borrow_mut() else {
1328            return false;
1329        };
1330        let Some((app, _)) = borrow.as_mut() else {
1331            return false;
1332        };
1333        let ws: WindowState = app.get_window_state();
1334        let size_diff: bool = ws.get_physical_width() != phys_w
1335            || ws.get_physical_height() != phys_h
1336            || (ws.get_scale_factor() - dpr).abs() > 0.005
1337            || canvas.width() != phys_w
1338            || canvas.height() != phys_h;
1339        if !size_diff {
1340            return false;
1341        }
1342        if canvas.width() != phys_w {
1343            canvas.set_width(phys_w);
1344        }
1345        if canvas.height() != phys_h {
1346            canvas.set_height(phys_h);
1347        }
1348        app.set_exact_physical_viewport(phys_w, phys_h, dpr);
1349        true
1350    })
1351}
1352
1353/// Re-queries browser CSS `env(safe-area-inset-*)` values and dispatches `WindowEvent::SafeAreaChanged` when changed.
1354///
1355/// # Returns
1356///
1357/// - `bool` - `true` when effective safe-area insets changed and require a relayout frame.
1358#[cfg(target_arch = "wasm32")]
1359fn web_sync_safe_area() -> bool {
1360    let measured: SafeAreaInsets = web_query_safe_area_insets();
1361    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1362        let Ok(mut borrow) = slot.try_borrow_mut() else {
1363            return false;
1364        };
1365        let Some((app, _)) = borrow.as_mut() else {
1366            return false;
1367        };
1368        let effective: SafeAreaInsets = if app.is_immersive_fullscreen() {
1369            SafeAreaInsets::default()
1370        } else {
1371            measured
1372        };
1373        let current: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
1374        if current == effective {
1375            return false;
1376        }
1377        let wid: WindowId = app.get_window_state().get_id();
1378        app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective));
1379        true
1380    })
1381}
1382
1383/// Reports measured browser `requestAnimationFrame` refresh cadence into the active `App` runtime.
1384///
1385/// # Arguments
1386///
1387/// - `f32` - Measured browser presentation cadence in Hertz.
1388#[cfg(target_arch = "wasm32")]
1389fn web_report_host_refresh_rate(measured_hz: f32) {
1390    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1391        if let Ok(mut borrow) = slot.try_borrow_mut()
1392            && let Some((app, _)) = borrow.as_mut()
1393        {
1394            let prev_fps: f32 = app.get_context().get_live_fps().get_untracked();
1395            app.report_host_refresh_rate(measured_hz);
1396            let next_fps: f32 = app.get_context().get_live_fps().get_untracked();
1397            if (next_fps - prev_fps).abs() >= 1.0 {
1398                web_mark_needs_frame();
1399            }
1400        }
1401    });
1402}
1403
1404/// Steps one coalesced WebAssembly frame during `requestAnimationFrame` with accurate real-time `dt_secs`.
1405///
1406/// # Arguments
1407///
1408/// - `f32` - Elapsed seconds since the previous animation frame.
1409///
1410/// # Returns
1411///
1412/// - `u64` - Rendered frame hash.
1413#[cfg(target_arch = "wasm32")]
1414fn web_flush_frame(dt_secs: f32) -> u64 {
1415    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1416        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1417            Ok(guard) => guard,
1418            Err(_) => return 0,
1419        };
1420        let Some((app, _)) = borrow.as_mut() else {
1421            return 0;
1422        };
1423        app.step_game_frame(dt_secs)
1424            .map(|stats: FrameStats| stats.get_frame_hash())
1425            .unwrap_or(0)
1426    })
1427}
1428
1429/// Initializes the persistent WebAssembly showcase on the browser `<canvas>` and renders the first frame.
1430///
1431/// # Returns
1432///
1433/// - `u64` - Deterministic frame hash produced by the initial render, or `0` on startup failure.
1434#[cfg(target_arch = "wasm32")]
1435#[wasm_bindgen]
1436pub fn euv_example_web_start() -> u64 {
1437    reset_reactive_runtime();
1438    match create_showcase_app(false, RenderMode::Software) {
1439        Ok((mut app, state)) => {
1440            if let Some(win) = window()
1441                && let Ok(hash_str) = win.location().hash()
1442            {
1443                let cleaned: &str = hash_str.trim_start_matches('#');
1444                if cleaned.starts_with('/') {
1445                    let _: bool = state.get_route().set_if_changed(cleaned.to_string());
1446                }
1447            }
1448            let route_watch: Signal<String> = state.get_route();
1449            let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1450                Effect::new(move || {
1451                    let r: String = route_watch.get();
1452                    if let Some(win) = window() {
1453                        let target_hash: String = format!("#{r}");
1454                        if win.location().hash().ok().as_deref() != Some(target_hash.as_str()) {
1455                            let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
1456                        }
1457                    }
1458                })
1459            });
1460            let root_id: NodeId = app
1461                .get_scene()
1462                .with_read(SceneTree::get_root, NodeId::default());
1463            app.get_scene().with_write(
1464                |tree: &mut SceneTree| {
1465                    tree.attach_scope(root_id, hash_scope);
1466                },
1467                (),
1468            );
1469            let hash: u64 = app
1470                .step_frame()
1471                .map(|stats: FrameStats| stats.get_frame_hash())
1472                .unwrap_or(0);
1473            WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1474                if let Ok(mut borrow) = slot.try_borrow_mut() {
1475                    *borrow = Some((app, state));
1476                }
1477            });
1478            hash
1479        }
1480        Err(_) => 0,
1481    }
1482}
1483
1484/// Switches the active route in the persistent WebAssembly showcase and renders immediately.
1485///
1486/// # Arguments
1487///
1488/// - `&str` - Route path to navigate to.
1489///
1490/// # Returns
1491///
1492/// - `u64` - Deterministic frame hash after route navigation.
1493#[cfg(target_arch = "wasm32")]
1494#[wasm_bindgen]
1495pub fn euv_example_render_route(route: &str) -> u64 {
1496    let has_runtime: bool = WEB_SHOWCASE_RUNTIME.with(
1497        |slot: &RefCell<Option<(App, ShowcaseState)>>| matches!(slot.try_borrow(), Ok(guard) if guard.is_some()),
1498    );
1499    if !has_runtime {
1500        let _: u64 = euv_example_web_start();
1501    }
1502    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1503        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1504            Ok(guard) => guard,
1505            Err(_) => return 0,
1506        };
1507        let Some((app, state)) = borrow.as_mut() else {
1508            return 0;
1509        };
1510        let _: bool = state.get_route().set_if_changed(route.to_string());
1511        app.step_frame()
1512            .map(|stats: FrameStats| stats.get_frame_hash())
1513            .unwrap_or(0)
1514    })
1515}
1516
1517/// Dispatches a browser pointer move event into the persistent WebAssembly showcase and re-renders.
1518///
1519/// # Arguments
1520///
1521/// - `f32` - Logical X coordinate inside the canvas.
1522/// - `f32` - Logical Y coordinate inside the canvas.
1523///
1524/// # Returns
1525///
1526/// - `u64` - Rendered frame hash.
1527#[cfg(target_arch = "wasm32")]
1528#[wasm_bindgen]
1529pub fn euv_web_pointer_move(x: f32, y: f32) -> u64 {
1530    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1531        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1532            Ok(guard) => guard,
1533            Err(_) => return 0,
1534        };
1535        let Some((app, _)) = borrow.as_mut() else {
1536            return 0;
1537        };
1538        let wid: WindowId = app.get_window_state().get_id();
1539        app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
1540        app.step_frame()
1541            .map(|stats: FrameStats| stats.get_frame_hash())
1542            .unwrap_or(0)
1543    })
1544}
1545
1546/// Dispatches a browser pointer press event into the persistent WebAssembly showcase and re-renders.
1547///
1548/// # Arguments
1549///
1550/// - `f32` - Logical X coordinate inside the canvas.
1551/// - `f32` - Logical Y coordinate inside the canvas.
1552///
1553/// # Returns
1554///
1555/// - `u64` - Rendered frame hash.
1556#[cfg(target_arch = "wasm32")]
1557#[wasm_bindgen]
1558pub fn euv_web_pointer_down(x: f32, y: f32) -> u64 {
1559    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1560        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1561            Ok(guard) => guard,
1562            Err(_) => return 0,
1563        };
1564        let Some((app, _)) = borrow.as_mut() else {
1565            return 0;
1566        };
1567        let wid: WindowId = app.get_window_state().get_id();
1568        app.dispatch_window_event(WindowEvent::PointerDown(wid, PointerEvent::mouse(x, y)));
1569        app.step_frame()
1570            .map(|stats: FrameStats| stats.get_frame_hash())
1571            .unwrap_or(0)
1572    })
1573}
1574
1575/// Dispatches a browser pointer release (and click) event into the persistent WebAssembly showcase and re-renders.
1576///
1577/// # Arguments
1578///
1579/// - `f32` - Logical X coordinate inside the canvas.
1580/// - `f32` - Logical Y coordinate inside the canvas.
1581///
1582/// # Returns
1583///
1584/// - `u64` - Rendered frame hash.
1585#[cfg(target_arch = "wasm32")]
1586#[wasm_bindgen]
1587pub fn euv_web_pointer_up(x: f32, y: f32) -> u64 {
1588    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1589        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1590            Ok(guard) => guard,
1591            Err(_) => return 0,
1592        };
1593        let Some((app, _)) = borrow.as_mut() else {
1594            return 0;
1595        };
1596        let wid: WindowId = app.get_window_state().get_id();
1597        app.dispatch_window_event(WindowEvent::PointerUp(wid, PointerEvent::mouse(x, y)));
1598        app.step_frame()
1599            .map(|stats: FrameStats| stats.get_frame_hash())
1600            .unwrap_or(0)
1601    })
1602}
1603
1604/// Dispatches a browser wheel scroll delta into the persistent WebAssembly showcase and re-renders.
1605///
1606/// # Arguments
1607///
1608/// - `f32` - Horizontal scroll delta.
1609/// - `f32` - Vertical scroll delta.
1610///
1611/// # Returns
1612///
1613/// - `u64` - Rendered frame hash.
1614#[cfg(target_arch = "wasm32")]
1615#[wasm_bindgen]
1616pub fn euv_web_scroll(dx: f32, dy: f32) -> u64 {
1617    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1618        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1619            Ok(guard) => guard,
1620            Err(_) => return 0,
1621        };
1622        let Some((app, _)) = borrow.as_mut() else {
1623            return 0;
1624        };
1625        let wid: WindowId = app.get_window_state().get_id();
1626        app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
1627        app.step_frame()
1628            .map(|stats: FrameStats| stats.get_frame_hash())
1629            .unwrap_or(0)
1630    })
1631}
1632
1633/// Dispatches a browser keyboard press and optional text input into the persistent WebAssembly showcase.
1634///
1635/// # Arguments
1636///
1637/// - `&str` - DOM `KeyboardEvent.key` string (e.g. `"Backspace"`, `"ArrowRight"`, `"a"`).
1638///
1639/// # Returns
1640///
1641/// - `u64` - Rendered frame hash.
1642#[cfg(target_arch = "wasm32")]
1643#[wasm_bindgen]
1644pub fn euv_web_key_down(key: &str) -> u64 {
1645    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1646        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1647            Ok(guard) => guard,
1648            Err(_) => return 0,
1649        };
1650        let Some((app, state)) = borrow.as_mut() else {
1651            return 0;
1652        };
1653        let wid: WindowId = app.get_window_state().get_id();
1654        let code: KeyCode = match key {
1655            WEB_KEY_ENTER => KeyCode::Enter,
1656            WEB_KEY_BACKSPACE => KeyCode::Backspace,
1657            WEB_KEY_DELETE => KeyCode::Delete,
1658            WEB_KEY_ESCAPE => KeyCode::Escape,
1659            WEB_KEY_TAB => KeyCode::Tab,
1660            WEB_KEY_SPACE => KeyCode::Space,
1661            WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
1662            WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
1663            WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
1664            WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
1665            other => other
1666                .chars()
1667                .next()
1668                .map(KeyCode::Character)
1669                .unwrap_or(KeyCode::Unknown),
1670        };
1671        let key_ev: WindowEvent =
1672            WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
1673        state.get_game_host().ingest_event(&key_ev);
1674        app.dispatch_window_event(key_ev);
1675        if key.chars().count() == 1 {
1676            app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
1677        }
1678        app.step_frame()
1679            .map(|stats: FrameStats| stats.get_frame_hash())
1680            .unwrap_or(0)
1681    })
1682}
1683
1684/// Advances the game physics clock by `dt_secs` when viewing the Game Engine route and renders a frame.
1685///
1686/// # Arguments
1687///
1688/// - `f32` - Elapsed seconds since the previous animation frame.
1689///
1690/// # Returns
1691///
1692/// - `u64` - Rendered frame hash.
1693#[cfg(target_arch = "wasm32")]
1694#[wasm_bindgen]
1695pub fn euv_web_tick(dt_secs: f32) -> u64 {
1696    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1697        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1698            Ok(guard) => guard,
1699            Err(_) => return 0,
1700        };
1701        let Some((app, state)) = borrow.as_mut() else {
1702            return 0;
1703        };
1704        if !app.should_pump_frames() {
1705            return app.get_renderer().get_last_stats().get_frame_hash();
1706        }
1707        let cur_route: String = state.get_route().get_untracked();
1708        let on_game: bool = cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D;
1709        if on_game || app.has_active_animations() {
1710            return app
1711                .step_game_frame(dt_secs)
1712                .map(|stats: FrameStats| stats.get_frame_hash())
1713                .unwrap_or(0);
1714        }
1715        app.get_renderer().get_last_stats().get_frame_hash()
1716    })
1717}
1718
1719/// Resizes the persistent WebAssembly showcase canvas and viewport immediately and re-renders.
1720///
1721/// # Arguments
1722///
1723/// - `u32` - New logical viewport width in CSS pixels.
1724/// - `u32` - New logical viewport height in CSS pixels.
1725/// - `f32` - Active browser `window.devicePixelRatio`.
1726///
1727/// # Returns
1728///
1729/// - `u64` - Deterministic frame hash produced by the resized render.
1730#[cfg(target_arch = "wasm32")]
1731#[wasm_bindgen]
1732pub fn euv_web_resize(width: u32, height: u32, dpr: f32) -> u64 {
1733    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1734        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1735            Ok(guard) => guard,
1736            Err(_) => return 0,
1737        };
1738        let Some((app, _)) = borrow.as_mut() else {
1739            return 0;
1740        };
1741        let w: u32 = width.max(320);
1742        let h: u32 = height.max(320);
1743        let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
1744            dpr.clamp(0.5, 4.5)
1745        } else {
1746            1.0
1747        };
1748        let phys_w: u32 = ((w as f64) * (scale as f64)).round().max(1.0) as u32;
1749        let phys_h: u32 = ((h as f64) * (scale as f64)).round().max(1.0) as u32;
1750        if let Some(win) = window()
1751            && let Some(doc) = win.document()
1752            && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
1753            && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
1754        {
1755            if canvas.width() != phys_w {
1756                canvas.set_width(phys_w);
1757            }
1758            if canvas.height() != phys_h {
1759                canvas.set_height(phys_h);
1760            }
1761        }
1762        app.set_exact_physical_viewport(phys_w, phys_h, scale);
1763        app.step_frame()
1764            .map(|stats: FrameStats| stats.get_frame_hash())
1765            .unwrap_or(0)
1766    })
1767}
1768
1769/// Executes an AI Schema v1 JSON query against the live WebAssembly showcase in dev builds only (stripped in release).
1770///
1771/// # Arguments
1772///
1773/// - `&str` - Serialized `AiSchemaRequest` JSON string.
1774///
1775/// # Returns
1776///
1777/// - `String` - Serialized `AiSchemaResponse` JSON string.
1778#[cfg(all(debug_assertions, target_arch = "wasm32"))]
1779#[wasm_bindgen]
1780pub fn euv_dev_ai_schema(request_json: &str) -> String {
1781    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1782        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1783            Ok(guard) => guard,
1784            Err(_) => return String::new(),
1785        };
1786        let Some((app, state)) = borrow.as_mut() else {
1787            return String::new();
1788        };
1789        let hooks: AiAppHooks = state.build_ai_hooks();
1790        AiSchemaProtocol::handle_json_with_hooks(app, request_json, Some(&hooks))
1791    })
1792}
1793
1794/// Returns the active route string of the persistent WebAssembly showcase for telemetry.
1795///
1796/// # Returns
1797///
1798/// - `String` - Current active route path.
1799#[cfg(target_arch = "wasm32")]
1800#[wasm_bindgen]
1801pub fn euv_web_current_route() -> String {
1802    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1803        match slot.try_borrow() {
1804            Ok(guard) => guard
1805                .as_ref()
1806                .map(|(_, state): &(App, ShowcaseState)| state.get_route().get_untracked())
1807                .unwrap_or_default(),
1808            Err(_) => String::new(),
1809        }
1810    })
1811}