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