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