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    }) as Box<dyn FnMut(Event)>);
467    drop(win.add_event_listener_with_callback(WEB_EVENT_BLUR, on_blur.as_ref().unchecked_ref()));
468    on_blur.forget();
469    let canvas_wheel: HtmlCanvasElement = canvas.clone();
470    let on_wheel: Closure<dyn FnMut(WheelEvent)> = Closure::wrap(Box::new(move |ev: WheelEvent| {
471        ev.prevent_default();
472        let rect: DomRect = canvas_wheel.get_bounding_client_rect();
473        let x: f32 = (ev.client_x() as f64 - rect.left()) as f32;
474        let y: f32 = (ev.client_y() as f64 - rect.top()) as f32;
475        let mult: f32 = match ev.delta_mode() {
476            1 => 20.0,
477            2 => 320.0,
478            _ => 1.0,
479        };
480        web_queue_scroll_at(
481            x,
482            y,
483            (ev.delta_x() as f32) * mult,
484            (ev.delta_y() as f32) * mult,
485        );
486    })
487        as Box<dyn FnMut(WheelEvent)>);
488    drop(
489        canvas.add_event_listener_with_callback(WEB_EVENT_WHEEL, on_wheel.as_ref().unchecked_ref()),
490    );
491    on_wheel.forget();
492    let on_key: Closure<dyn FnMut(KeyboardEvent)> =
493        Closure::wrap(Box::new(move |ev: KeyboardEvent| {
494            let key: String = ev.key();
495            let code_str: String = ev.code();
496            let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
497            let should_prevent: bool = if ime_active {
498                matches!(
499                    key.as_str(),
500                    WEB_KEY_ARROW_UP
501                        | WEB_KEY_ARROW_DOWN
502                        | WEB_KEY_ARROW_LEFT
503                        | WEB_KEY_ARROW_RIGHT
504                        | WEB_KEY_BACKSPACE
505                )
506            } else {
507                matches!(
508                    key.as_str(),
509                    WEB_KEY_ARROW_UP
510                        | WEB_KEY_ARROW_DOWN
511                        | WEB_KEY_ARROW_LEFT
512                        | WEB_KEY_ARROW_RIGHT
513                        | WEB_KEY_BACKSPACE
514                        | WEB_KEY_SPACE
515                )
516            };
517            if should_prevent {
518                ev.prevent_default();
519            }
520            web_queue_key_down(&key, &code_str);
521        }) as Box<dyn FnMut(KeyboardEvent)>);
522    drop(win.add_event_listener_with_callback(WEB_EVENT_KEY_DOWN, on_key.as_ref().unchecked_ref()));
523    on_key.forget();
524    let on_key_up: Closure<dyn FnMut(KeyboardEvent)> =
525        Closure::wrap(Box::new(move |ev: KeyboardEvent| {
526            let key: String = ev.key();
527            let code_str: String = ev.code();
528            web_queue_key_up(&key, &code_str);
529        }) as Box<dyn FnMut(KeyboardEvent)>);
530    drop(
531        win.add_event_listener_with_callback(WEB_EVENT_KEY_UP, on_key_up.as_ref().unchecked_ref()),
532    );
533    on_key_up.forget();
534    let win_resize: Window = win.clone();
535    let canvas_resize: HtmlCanvasElement = canvas.clone();
536    let on_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
537        if web_sync_exact_viewport(&win_resize, &canvas_resize) {
538            web_mark_needs_frame();
539        }
540    }) as Box<dyn FnMut(Event)>);
541    drop(
542        win.add_event_listener_with_callback(WEB_EVENT_RESIZE, on_resize.as_ref().unchecked_ref()),
543    );
544    on_resize.forget();
545    let raf_cell: WebRafSlot = Rc::new(RefCell::new(None));
546    let raf_loop: WebRafSlot = raf_cell.clone();
547    let win_raf: Window = win.clone();
548    let canvas_raf: HtmlCanvasElement = canvas.clone();
549    let last_ts: Rc<RefCell<f64>> = Rc::new(RefCell::new(0.0));
550    let raf_accum_secs: Rc<Cell<f32>> = Rc::new(Cell::new(0.0));
551    let raf_accum_frames: Rc<Cell<u32>> = Rc::new(Cell::new(0));
552    if let Ok(mut slot) = raf_cell.try_borrow_mut() {
553        *slot = Some(Closure::wrap(Box::new(move |ts: f64| {
554            let mut dt: f32 = 1.0 / 60.0;
555            let mut valid_step: bool = false;
556            if let Ok(mut prev) = last_ts.try_borrow_mut() {
557                if *prev > 0.0 {
558                    let raw_dt: f32 = ((ts - *prev) / 1000.0) as f32;
559                    if (0.001..=0.1).contains(&raw_dt) {
560                        valid_step = true;
561                    }
562                    dt = raw_dt.clamp(0.001, 0.05);
563                }
564                *prev = ts;
565            }
566            if valid_step {
567                let next_secs: f32 = raf_accum_secs.get() + dt;
568                let next_frames: u32 = raf_accum_frames.get().saturating_add(1);
569                if next_secs >= 0.35 && next_frames >= 8 {
570                    let measured_hz: f32 = (next_frames as f32) / next_secs;
571                    raf_accum_secs.set(0.0);
572                    raf_accum_frames.set(0);
573                    web_report_host_refresh_rate(measured_hz);
574                } else {
575                    raf_accum_secs.set(next_secs);
576                    raf_accum_frames.set(next_frames);
577                }
578            }
579            let resized_or_scaled: bool = web_sync_exact_viewport(&win_raf, &canvas_raf);
580            let cur_route: String = euv_web_current_route();
581            let on_game: bool = cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D;
582            let animating: bool = web_has_active_animations();
583            let dirty: bool = WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.replace(false));
584            if resized_or_scaled || on_game {
585                let _: u64 = web_flush_frame(dt);
586            } else if animating || dirty {
587                let _: u64 = web_flush_frame(dt);
588            }
589            if let Ok(cb_ref) = raf_loop.try_borrow()
590                && let Some(cb) = cb_ref.as_ref()
591            {
592                let func: &Function = cb.as_ref().unchecked_ref();
593                drop(win_raf.request_animation_frame(func));
594            }
595        }) as Box<dyn FnMut(f64)>));
596    }
597    if let Ok(cb_ref) = raf_cell.try_borrow()
598        && let Some(cb) = cb_ref.as_ref()
599    {
600        let func: &Function = cb.as_ref().unchecked_ref();
601        drop(win.request_animation_frame(func));
602    }
603}
604
605/// Maps a browser `KeyboardEvent.key` and physical `KeyboardEvent.code` into a cross-platform `KeyCode`.
606///
607/// # Arguments
608///
609/// - `&str` - Browser DOM `KeyboardEvent.key` string.
610/// - `&str` - Browser DOM physical `KeyboardEvent.code` string (IME-independent).
611///
612/// # Returns
613///
614/// - `KeyCode` - Normalized `euv` key code.
615#[cfg(target_arch = "wasm32")]
616fn web_map_key(key: &str, code_str: &str) -> KeyCode {
617    match code_str {
618        "KeyW" => return KeyCode::Character('w'),
619        "KeyA" => return KeyCode::Character('a'),
620        "KeyS" => return KeyCode::Character('s'),
621        "KeyD" => return KeyCode::Character('d'),
622        "KeyE" => return KeyCode::Character('e'),
623        "KeyR" => return KeyCode::Character('r'),
624        "KeyP" => return KeyCode::Character('p'),
625        "KeyJ" => return KeyCode::Character('j'),
626        "Space" => return KeyCode::Space,
627        "ArrowLeft" => return KeyCode::ArrowLeft,
628        "ArrowRight" => return KeyCode::ArrowRight,
629        "ArrowUp" => return KeyCode::ArrowUp,
630        "ArrowDown" => return KeyCode::ArrowDown,
631        _ => {}
632    }
633    match key {
634        WEB_KEY_ENTER => KeyCode::Enter,
635        WEB_KEY_BACKSPACE => KeyCode::Backspace,
636        WEB_KEY_DELETE => KeyCode::Delete,
637        WEB_KEY_ESCAPE => KeyCode::Escape,
638        WEB_KEY_TAB => KeyCode::Tab,
639        WEB_KEY_SPACE => KeyCode::Space,
640        WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
641        WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
642        WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
643        WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
644        other => other
645            .chars()
646            .next()
647            .map(KeyCode::Character)
648            .unwrap_or(KeyCode::Unknown),
649    }
650}
651
652/// Returns `true` when the active WebAssembly app has running UI transition animations.
653///
654/// # Returns
655///
656/// - `bool` - Whether animation frames must continue ticking.
657#[cfg(target_arch = "wasm32")]
658fn web_has_active_animations() -> bool {
659    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
660        match slot.try_borrow() {
661            Ok(guard) => guard
662                .as_ref()
663                .map(|(app, _): &(App, ShowcaseState)| app.has_active_animations())
664                .unwrap_or(false),
665            Err(_) => false,
666        }
667    })
668}
669
670/// Marks the coalesced Web animation-frame render flag so the next `requestAnimationFrame` flushes visual changes.
671#[cfg(target_arch = "wasm32")]
672fn web_mark_needs_frame() {
673    WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.set(true));
674}
675
676/// Normalizes a browser `PointerEvent.pointerId` into a non-zero cross-platform pointer identifier.
677///
678/// # Arguments
679///
680/// - `&web_sys::PointerEvent` - Browser DOM pointer event.
681///
682/// # Returns
683///
684/// - `u64` - Stable non-zero pointer identifier.
685#[cfg(target_arch = "wasm32")]
686fn web_pointer_id_from_dom(ev: &web_sys::PointerEvent) -> u64 {
687    (ev.pointer_id() as i64).unsigned_abs().saturating_add(1)
688}
689
690/// Converts a browser DOM `PointerEvent` into an `euv::PointerEvent` preserving pointer ID, touch/pen/mouse device, and button state.
691///
692/// # Arguments
693///
694/// - `&web_sys::PointerEvent` - Browser DOM pointer event.
695/// - `&HtmlCanvasElement` - Target canvas element for local coordinate conversion.
696/// - `Option<bool>` - Optional explicit pressed override (`Some(true)` on down, `Some(false)` on up, `None` to inspect `buttons()`).
697///
698/// # Returns
699///
700/// - `PointerEvent` - Cross-platform pointer event.
701#[cfg(target_arch = "wasm32")]
702fn web_pointer_from_dom(
703    ev: &web_sys::PointerEvent,
704    canvas: &HtmlCanvasElement,
705    force_pressed: Option<bool>,
706) -> PointerEvent {
707    let rect: DomRect = canvas.get_bounding_client_rect();
708    let x: f32 = (ev.client_x() as f64 - rect.left()) as f32;
709    let y: f32 = (ev.client_y() as f64 - rect.top()) as f32;
710    let pid: u64 = web_pointer_id_from_dom(ev);
711    let ptype: String = ev.pointer_type();
712    let device: PointerDevice = if ptype == WEB_PTR_TYPE_TOUCH {
713        PointerDevice::Touch
714    } else if ptype == WEB_PTR_TYPE_PEN {
715        PointerDevice::Stylus
716    } else {
717        PointerDevice::Mouse
718    };
719    let is_pressed: bool =
720        force_pressed.unwrap_or_else(|| ev.buttons() != 0 || device == PointerDevice::Touch);
721    let pressure: f32 = if is_pressed { 1.0 } else { 0.0 };
722    PointerEvent::new(
723        pid,
724        device,
725        Point::new(x, y),
726        PointerButton::Primary,
727        pressure,
728        Modifiers::default(),
729    )
730}
731
732/// Enqueues a browser pointer move into the active WebAssembly runtime without synchronous full-frame rasterization.
733///
734/// # Arguments
735///
736/// - `PointerEvent` - Normalized pointer move event.
737#[cfg(target_arch = "wasm32")]
738fn web_queue_pointer_move_event(ptr: PointerEvent) {
739    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
740        if let Ok(mut borrow) = slot.try_borrow_mut()
741            && let Some((app, _)) = borrow.as_mut()
742        {
743            let wid: WindowId = app.get_window_state().get_id();
744            app.dispatch_window_event(WindowEvent::PointerMove(wid, ptr));
745            web_mark_needs_frame();
746        }
747    });
748}
749
750/// Enqueues a browser pointer press into the active WebAssembly runtime for the next animation frame.
751///
752/// # Arguments
753///
754/// - `PointerEvent` - Normalized pointer press event.
755#[cfg(target_arch = "wasm32")]
756fn web_queue_pointer_down_event(ptr: PointerEvent) {
757    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
758        if let Ok(mut borrow) = slot.try_borrow_mut()
759            && let Some((app, _)) = borrow.as_mut()
760        {
761            let wid: WindowId = app.get_window_state().get_id();
762            app.dispatch_window_event(WindowEvent::PointerDown(wid, ptr));
763            web_mark_needs_frame();
764        }
765    });
766}
767
768/// Enqueues a browser pointer release into the active WebAssembly runtime for the next animation frame.
769///
770/// # Arguments
771///
772/// - `PointerEvent` - Normalized pointer release event.
773#[cfg(target_arch = "wasm32")]
774fn web_queue_pointer_up_event(ptr: PointerEvent) {
775    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
776        if let Ok(mut borrow) = slot.try_borrow_mut()
777            && let Some((app, _)) = borrow.as_mut()
778        {
779            let wid: WindowId = app.get_window_state().get_id();
780            app.dispatch_window_event(WindowEvent::PointerUp(wid, ptr));
781            web_mark_needs_frame();
782        }
783    });
784}
785
786/// Enqueues a browser pointer cancel (`0` cancels all active contacts) into the active WebAssembly runtime.
787///
788/// # Arguments
789///
790/// - `u64` - Cancelled pointer identifier (`0` cancels all active pointers).
791#[cfg(target_arch = "wasm32")]
792fn web_queue_pointer_cancel(pointer_id: u64) {
793    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
794        if let Ok(mut borrow) = slot.try_borrow_mut()
795            && let Some((app, _)) = borrow.as_mut()
796        {
797            let wid: WindowId = app.get_window_state().get_id();
798            app.dispatch_window_event(WindowEvent::PointerCancel(wid, pointer_id));
799            web_mark_needs_frame();
800        }
801    });
802}
803
804/// Enqueues a normalized browser wheel scroll delta at `(x, y)` for coalesced VSync rendering.
805///
806/// # Arguments
807///
808/// - `f32` - Pointer X coordinate inside the canvas.
809/// - `f32` - Pointer Y coordinate inside the canvas.
810/// - `f32` - Horizontal scroll delta.
811/// - `f32` - Vertical scroll delta.
812#[cfg(target_arch = "wasm32")]
813fn web_queue_scroll_at(x: f32, y: f32, dx: f32, dy: f32) {
814    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
815        if let Ok(mut borrow) = slot.try_borrow_mut()
816            && let Some((app, _)) = borrow.as_mut()
817        {
818            let wid: WindowId = app.get_window_state().get_id();
819            app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
820            app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
821            web_mark_needs_frame();
822        }
823    });
824}
825
826/// Enqueues a browser key-down and optional printable text event for the next animation frame.
827///
828/// # Arguments
829///
830/// - `&str` - DOM `KeyboardEvent.key` string.
831/// - `&str` - DOM physical `KeyboardEvent.code` string.
832#[cfg(target_arch = "wasm32")]
833fn web_queue_key_down(key: &str, code_str: &str) {
834    if WEB_IME_COMPOSING.with(Cell::get) {
835        return;
836    }
837    let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
838    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
839        if let Ok(mut borrow) = slot.try_borrow_mut()
840            && let Some((app, _)) = borrow.as_mut()
841        {
842            let wid: WindowId = app.get_window_state().get_id();
843            let code: KeyCode = web_map_key(key, code_str);
844            let key_ev: WindowEvent =
845                WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
846            app.dispatch_window_event(key_ev);
847            if !ime_active && key.chars().count() == 1 {
848                app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
849            }
850            web_mark_needs_frame();
851        }
852    });
853}
854
855/// Dispatches committed browser IME or virtual keyboard text into the active WebAssembly runtime.
856///
857/// # Arguments
858///
859/// - `String` - Committed UTF-8 text from the hidden IME proxy input.
860#[cfg(target_arch = "wasm32")]
861fn web_queue_text_input(text: String) {
862    if text.is_empty() {
863        return;
864    }
865    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
866        if let Ok(mut borrow) = slot.try_borrow_mut()
867            && let Some((app, _)) = borrow.as_mut()
868        {
869            let wid: WindowId = app.get_window_state().get_id();
870            app.dispatch_window_event(WindowEvent::TextInput(wid, text));
871            web_mark_needs_frame();
872        }
873    });
874}
875
876/// Reads and clears the hidden browser IME proxy `<input>` value, dispatching any pending text into `euv`.
877///
878/// # Arguments
879///
880/// - `&HtmlElement` - Hidden browser IME proxy element.
881#[cfg(target_arch = "wasm32")]
882fn web_flush_ime_element(el: &HtmlElement) {
883    let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
884    if let Ok(val) = Reflect::get(el.as_ref(), &key)
885        && let Some(text) = val.as_string()
886        && !text.is_empty()
887    {
888        let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
889        web_queue_text_input(text);
890    }
891}
892
893/// Attaches a visually hidden DOM `<input>` element so mobile browsers and CJK IMEs open native keyboards on input focus.
894///
895/// # Arguments
896///
897/// - `&Document` - Active browser DOM document.
898#[cfg(target_arch = "wasm32")]
899fn web_attach_ime_proxy(doc: &Document) {
900    let Ok(raw_el) = doc.create_element(WEB_IME_INPUT_TAG) else {
901        return;
902    };
903    let el: Element = raw_el;
904    drop(el.set_attribute(WEB_IME_ATTR_ID, WEB_IME_INPUT_ID));
905    drop(el.set_attribute(WEB_IME_ATTR_TYPE, WEB_IME_ATTR_TEXT));
906    drop(el.set_attribute(WEB_IME_ATTR_AUTOCOMPLETE, WEB_IME_ATTR_OFF));
907    drop(el.set_attribute(WEB_IME_ATTR_AUTOCORRECT, WEB_IME_ATTR_OFF));
908    drop(el.set_attribute(WEB_IME_ATTR_AUTOCAPITALIZE, WEB_IME_ATTR_OFF));
909    drop(el.set_attribute(WEB_IME_ATTR_SPELLCHECK, WEB_IME_ATTR_FALSE));
910    drop(el.set_attribute(WEB_IME_ATTR_ARIA_LABEL, WEB_IME_ARIA_LABEL));
911    drop(el.set_attribute(WEB_IME_ATTR_STYLE, WEB_IME_STYLE));
912    let Ok(html_el) = el.dyn_into::<HtmlElement>() else {
913        return;
914    };
915    if let Some(body) = doc.body() {
916        drop(body.append_child(&html_el));
917    }
918    let comp_start: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
919        WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(true));
920    }) as Box<dyn FnMut(Event)>);
921    drop(html_el.add_event_listener_with_callback(
922        WEB_EVENT_COMPOSITION_START,
923        comp_start.as_ref().unchecked_ref(),
924    ));
925    comp_start.forget();
926    let comp_el: HtmlElement = html_el.clone();
927    let comp_end: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
928        WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
929        web_flush_ime_element(&comp_el);
930    }) as Box<dyn FnMut(Event)>);
931    drop(html_el.add_event_listener_with_callback(
932        WEB_EVENT_COMPOSITION_END,
933        comp_end.as_ref().unchecked_ref(),
934    ));
935    comp_end.forget();
936    let inp_el: HtmlElement = html_el.clone();
937    let on_input: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
938        if !WEB_IME_COMPOSING.with(Cell::get) {
939            web_flush_ime_element(&inp_el);
940        }
941    }) as Box<dyn FnMut(Event)>);
942    drop(
943        html_el
944            .add_event_listener_with_callback(WEB_EVENT_INPUT, on_input.as_ref().unchecked_ref()),
945    );
946    on_input.forget();
947    let on_ime_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
948        WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
949        WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
950        WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
951            if let Ok(mut borrow) = slot.try_borrow_mut()
952                && let Some((app, _)) = borrow.as_mut()
953            {
954                let wid: WindowId = app.get_window_state().get_id();
955                app.dispatch_window_event(WindowEvent::Ime(wid, ImeEvent::Disabled));
956            }
957        });
958    }) as Box<dyn FnMut(Event)>);
959    drop(
960        html_el
961            .add_event_listener_with_callback(WEB_EVENT_BLUR, on_ime_blur.as_ref().unchecked_ref()),
962    );
963    on_ime_blur.forget();
964    WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
965        if let Ok(mut guard) = slot.try_borrow_mut() {
966            *guard = Some(html_el);
967        }
968    });
969}
970
971/// Handles `euv` native action requests in the browser, focusing or blurring the hidden IME proxy input.
972///
973/// # Arguments
974///
975/// - `&str` - Action category (e.g. `NATIVE_ACTION_IME`).
976/// - `&str` - Action subcommand (`"show"` or `"hide"`).
977/// - `&str` - Secondary payload argument.
978///
979/// # Returns
980///
981/// - `bool` - `true` when handled by the browser bridge.
982#[cfg(target_arch = "wasm32")]
983fn web_native_action_bridge(kind: &str, arg1: &str, _arg2: &str) -> bool {
984    if kind != NATIVE_ACTION_IME {
985        return false;
986    }
987    WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
988        let Ok(guard) = slot.try_borrow() else {
989            return false;
990        };
991        let Some(el) = guard.as_ref() else {
992            return false;
993        };
994        if arg1 == WEB_IME_ACTION_SHOW {
995            WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(true));
996            if let Some(win) = window()
997                && let Some(doc) = win.document()
998                && let Some(active_el) = doc.active_element()
999                && active_el.id() == WEB_IME_INPUT_ID
1000            {
1001                drop(el.blur());
1002            }
1003            drop(el.focus());
1004            true
1005        } else if arg1 == WEB_IME_ACTION_HIDE {
1006            WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
1007            WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1008            let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
1009            let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
1010            drop(el.blur());
1011            true
1012        } else {
1013            false
1014        }
1015    })
1016}
1017
1018/// Enqueues a browser key-up event into the active WebAssembly runtime and game host.
1019///
1020/// # Arguments
1021///
1022/// - `&str` - DOM `KeyboardEvent.key` string.
1023/// - `&str` - DOM physical `KeyboardEvent.code` string.
1024#[cfg(target_arch = "wasm32")]
1025fn web_queue_key_up(key: &str, code_str: &str) {
1026    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1027        if let Ok(mut borrow) = slot.try_borrow_mut()
1028            && let Some((app, _)) = borrow.as_mut()
1029        {
1030            let wid: WindowId = app.get_window_state().get_id();
1031            let code: KeyCode = web_map_key(key, code_str);
1032            app.dispatch_window_event(WindowEvent::KeyUp(
1033                wid,
1034                KeyEvent::new(code, Modifiers::default(), false),
1035            ));
1036        }
1037    });
1038}
1039
1040/// Synchronizes the WebAssembly `<canvas>` backing pixels and `App` viewport with exact 1:1 physical device pixels.
1041///
1042/// # Arguments
1043///
1044/// - `&Window` - Browser window object.
1045/// - `&HtmlCanvasElement` - Target full-viewport canvas element.
1046///
1047/// # Returns
1048///
1049/// - `bool` - `true` when physical dimensions or DPI scale changed and the viewport was updated.
1050#[cfg(target_arch = "wasm32")]
1051fn web_sync_exact_viewport(win: &Window, canvas: &HtmlCanvasElement) -> bool {
1052    let rect: DomRect = canvas.get_bounding_client_rect();
1053    let css_w: f64 = if rect.width() >= 320.0 {
1054        rect.width()
1055    } else {
1056        win.inner_width()
1057            .ok()
1058            .and_then(|v: JsValue| v.as_f64())
1059            .filter(|w: &f64| *w >= 320.0)
1060            .unwrap_or(1200.0)
1061    };
1062    let css_h: f64 = if rect.height() >= 320.0 {
1063        rect.height()
1064    } else {
1065        win.inner_height()
1066            .ok()
1067            .and_then(|v: JsValue| v.as_f64())
1068            .filter(|h: &f64| *h >= 320.0)
1069            .unwrap_or(800.0)
1070    };
1071    let dpr_raw: f64 = win.device_pixel_ratio();
1072    let dpr_f64: f64 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
1073        dpr_raw.clamp(0.5, 4.5)
1074    } else {
1075        1.0
1076    };
1077    let dpr: f32 = dpr_f64 as f32;
1078    let phys_w: u32 = (css_w * dpr_f64).round().max(1.0) as u32;
1079    let phys_h: u32 = (css_h * dpr_f64).round().max(1.0) as u32;
1080    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1081        let Ok(mut borrow) = slot.try_borrow_mut() else {
1082            return false;
1083        };
1084        let Some((app, _)) = borrow.as_mut() else {
1085            return false;
1086        };
1087        let ws: WindowState = app.get_window_state();
1088        let size_diff: bool = ws.get_physical_width() != phys_w
1089            || ws.get_physical_height() != phys_h
1090            || (ws.get_scale_factor() - dpr).abs() > 0.005
1091            || canvas.width() != phys_w
1092            || canvas.height() != phys_h;
1093        if !size_diff {
1094            return false;
1095        }
1096        if canvas.width() != phys_w {
1097            canvas.set_width(phys_w);
1098        }
1099        if canvas.height() != phys_h {
1100            canvas.set_height(phys_h);
1101        }
1102        app.set_exact_physical_viewport(phys_w, phys_h, dpr);
1103        true
1104    })
1105}
1106
1107/// Reports measured browser `requestAnimationFrame` refresh cadence into the active `App` runtime.
1108///
1109/// # Arguments
1110///
1111/// - `f32` - Measured browser presentation cadence in Hertz.
1112#[cfg(target_arch = "wasm32")]
1113fn web_report_host_refresh_rate(measured_hz: f32) {
1114    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1115        if let Ok(mut borrow) = slot.try_borrow_mut()
1116            && let Some((app, _)) = borrow.as_mut()
1117        {
1118            let prev_fps: f32 = app.get_context().get_live_fps().get_untracked();
1119            app.report_host_refresh_rate(measured_hz);
1120            let next_fps: f32 = app.get_context().get_live_fps().get_untracked();
1121            if (next_fps - prev_fps).abs() >= 1.0 {
1122                web_mark_needs_frame();
1123            }
1124        }
1125    });
1126}
1127
1128/// Steps one coalesced WebAssembly frame during `requestAnimationFrame` with accurate real-time `dt_secs`.
1129///
1130/// # Arguments
1131///
1132/// - `f32` - Elapsed seconds since the previous animation frame.
1133///
1134/// # Returns
1135///
1136/// - `u64` - Rendered frame hash.
1137#[cfg(target_arch = "wasm32")]
1138fn web_flush_frame(dt_secs: f32) -> u64 {
1139    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1140        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1141            Ok(guard) => guard,
1142            Err(_) => return 0,
1143        };
1144        let Some((app, _)) = borrow.as_mut() else {
1145            return 0;
1146        };
1147        app.step_game_frame(dt_secs)
1148            .map(|stats: FrameStats| stats.get_frame_hash())
1149            .unwrap_or(0)
1150    })
1151}
1152
1153/// Initializes the persistent WebAssembly showcase on the browser `<canvas>` and renders the first frame.
1154///
1155/// # Returns
1156///
1157/// - `u64` - Deterministic frame hash produced by the initial render, or `0` on startup failure.
1158#[cfg(target_arch = "wasm32")]
1159#[wasm_bindgen]
1160pub fn euv_example_web_start() -> u64 {
1161    reset_reactive_runtime();
1162    match create_showcase_app(false, RenderMode::Software) {
1163        Ok((mut app, state)) => {
1164            if let Some(win) = window()
1165                && let Ok(hash_str) = win.location().hash()
1166            {
1167                let cleaned: &str = hash_str.trim_start_matches('#');
1168                if cleaned.starts_with('/') {
1169                    let _: bool = state.get_route().set_if_changed(cleaned.to_string());
1170                }
1171            }
1172            let route_watch: Signal<String> = state.get_route();
1173            let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1174                Effect::new(move || {
1175                    let r: String = route_watch.get();
1176                    if let Some(win) = window() {
1177                        let target_hash: String = format!("#{r}");
1178                        if win.location().hash().ok().as_deref() != Some(target_hash.as_str()) {
1179                            let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
1180                        }
1181                    }
1182                })
1183            });
1184            let root_id: NodeId = app
1185                .get_scene()
1186                .with_read(SceneTree::get_root, NodeId::default());
1187            app.get_scene().with_write(
1188                |tree: &mut SceneTree| {
1189                    tree.attach_scope(root_id, hash_scope);
1190                },
1191                (),
1192            );
1193            let hash: u64 = app
1194                .step_frame()
1195                .map(|stats: FrameStats| stats.get_frame_hash())
1196                .unwrap_or(0);
1197            WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1198                if let Ok(mut borrow) = slot.try_borrow_mut() {
1199                    *borrow = Some((app, state));
1200                }
1201            });
1202            hash
1203        }
1204        Err(_) => 0,
1205    }
1206}
1207
1208/// Switches the active route in the persistent WebAssembly showcase and renders immediately.
1209///
1210/// # Arguments
1211///
1212/// - `&str` - Route path to navigate to.
1213///
1214/// # Returns
1215///
1216/// - `u64` - Deterministic frame hash after route navigation.
1217#[cfg(target_arch = "wasm32")]
1218#[wasm_bindgen]
1219pub fn euv_example_render_route(route: &str) -> u64 {
1220    let has_runtime: bool = WEB_SHOWCASE_RUNTIME.with(
1221        |slot: &RefCell<Option<(App, ShowcaseState)>>| matches!(slot.try_borrow(), Ok(guard) if guard.is_some()),
1222    );
1223    if !has_runtime {
1224        let _: u64 = euv_example_web_start();
1225    }
1226    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1227        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1228            Ok(guard) => guard,
1229            Err(_) => return 0,
1230        };
1231        let Some((app, state)) = borrow.as_mut() else {
1232            return 0;
1233        };
1234        let _: bool = state.get_route().set_if_changed(route.to_string());
1235        app.step_frame()
1236            .map(|stats: FrameStats| stats.get_frame_hash())
1237            .unwrap_or(0)
1238    })
1239}
1240
1241/// Dispatches a browser pointer move event into the persistent WebAssembly showcase and re-renders.
1242///
1243/// # Arguments
1244///
1245/// - `f32` - Logical X coordinate inside the canvas.
1246/// - `f32` - Logical Y coordinate inside the canvas.
1247///
1248/// # Returns
1249///
1250/// - `u64` - Rendered frame hash.
1251#[cfg(target_arch = "wasm32")]
1252#[wasm_bindgen]
1253pub fn euv_web_pointer_move(x: f32, y: f32) -> u64 {
1254    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1255        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1256            Ok(guard) => guard,
1257            Err(_) => return 0,
1258        };
1259        let Some((app, _)) = borrow.as_mut() else {
1260            return 0;
1261        };
1262        let wid: WindowId = app.get_window_state().get_id();
1263        app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
1264        app.step_frame()
1265            .map(|stats: FrameStats| stats.get_frame_hash())
1266            .unwrap_or(0)
1267    })
1268}
1269
1270/// Dispatches a browser pointer press event into the persistent WebAssembly showcase and re-renders.
1271///
1272/// # Arguments
1273///
1274/// - `f32` - Logical X coordinate inside the canvas.
1275/// - `f32` - Logical Y coordinate inside the canvas.
1276///
1277/// # Returns
1278///
1279/// - `u64` - Rendered frame hash.
1280#[cfg(target_arch = "wasm32")]
1281#[wasm_bindgen]
1282pub fn euv_web_pointer_down(x: f32, y: f32) -> u64 {
1283    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1284        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1285            Ok(guard) => guard,
1286            Err(_) => return 0,
1287        };
1288        let Some((app, _)) = borrow.as_mut() else {
1289            return 0;
1290        };
1291        let wid: WindowId = app.get_window_state().get_id();
1292        app.dispatch_window_event(WindowEvent::PointerDown(wid, PointerEvent::mouse(x, y)));
1293        app.step_frame()
1294            .map(|stats: FrameStats| stats.get_frame_hash())
1295            .unwrap_or(0)
1296    })
1297}
1298
1299/// Dispatches a browser pointer release (and click) event into the persistent WebAssembly showcase and re-renders.
1300///
1301/// # Arguments
1302///
1303/// - `f32` - Logical X coordinate inside the canvas.
1304/// - `f32` - Logical Y coordinate inside the canvas.
1305///
1306/// # Returns
1307///
1308/// - `u64` - Rendered frame hash.
1309#[cfg(target_arch = "wasm32")]
1310#[wasm_bindgen]
1311pub fn euv_web_pointer_up(x: f32, y: f32) -> u64 {
1312    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1313        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1314            Ok(guard) => guard,
1315            Err(_) => return 0,
1316        };
1317        let Some((app, _)) = borrow.as_mut() else {
1318            return 0;
1319        };
1320        let wid: WindowId = app.get_window_state().get_id();
1321        app.dispatch_window_event(WindowEvent::PointerUp(wid, PointerEvent::mouse(x, y)));
1322        app.step_frame()
1323            .map(|stats: FrameStats| stats.get_frame_hash())
1324            .unwrap_or(0)
1325    })
1326}
1327
1328/// Dispatches a browser wheel scroll delta into the persistent WebAssembly showcase and re-renders.
1329///
1330/// # Arguments
1331///
1332/// - `f32` - Horizontal scroll delta.
1333/// - `f32` - Vertical scroll delta.
1334///
1335/// # Returns
1336///
1337/// - `u64` - Rendered frame hash.
1338#[cfg(target_arch = "wasm32")]
1339#[wasm_bindgen]
1340pub fn euv_web_scroll(dx: f32, dy: f32) -> u64 {
1341    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1342        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1343            Ok(guard) => guard,
1344            Err(_) => return 0,
1345        };
1346        let Some((app, _)) = borrow.as_mut() else {
1347            return 0;
1348        };
1349        let wid: WindowId = app.get_window_state().get_id();
1350        app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
1351        app.step_frame()
1352            .map(|stats: FrameStats| stats.get_frame_hash())
1353            .unwrap_or(0)
1354    })
1355}
1356
1357/// Dispatches a browser keyboard press and optional text input into the persistent WebAssembly showcase.
1358///
1359/// # Arguments
1360///
1361/// - `&str` - DOM `KeyboardEvent.key` string (e.g. `"Backspace"`, `"ArrowRight"`, `"a"`).
1362///
1363/// # Returns
1364///
1365/// - `u64` - Rendered frame hash.
1366#[cfg(target_arch = "wasm32")]
1367#[wasm_bindgen]
1368pub fn euv_web_key_down(key: &str) -> u64 {
1369    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1370        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1371            Ok(guard) => guard,
1372            Err(_) => return 0,
1373        };
1374        let Some((app, state)) = borrow.as_mut() else {
1375            return 0;
1376        };
1377        let wid: WindowId = app.get_window_state().get_id();
1378        let code: KeyCode = match key {
1379            WEB_KEY_ENTER => KeyCode::Enter,
1380            WEB_KEY_BACKSPACE => KeyCode::Backspace,
1381            WEB_KEY_DELETE => KeyCode::Delete,
1382            WEB_KEY_ESCAPE => KeyCode::Escape,
1383            WEB_KEY_TAB => KeyCode::Tab,
1384            WEB_KEY_SPACE => KeyCode::Space,
1385            WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
1386            WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
1387            WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
1388            WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
1389            other => other
1390                .chars()
1391                .next()
1392                .map(KeyCode::Character)
1393                .unwrap_or(KeyCode::Unknown),
1394        };
1395        let key_ev: WindowEvent =
1396            WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
1397        state.get_game_host().ingest_event(&key_ev);
1398        app.dispatch_window_event(key_ev);
1399        if key.chars().count() == 1 {
1400            app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
1401        }
1402        app.step_frame()
1403            .map(|stats: FrameStats| stats.get_frame_hash())
1404            .unwrap_or(0)
1405    })
1406}
1407
1408/// Advances the game physics clock by `dt_secs` when viewing the Game Engine route and renders a frame.
1409///
1410/// # Arguments
1411///
1412/// - `f32` - Elapsed seconds since the previous animation frame.
1413///
1414/// # Returns
1415///
1416/// - `u64` - Rendered frame hash.
1417#[cfg(target_arch = "wasm32")]
1418#[wasm_bindgen]
1419pub fn euv_web_tick(dt_secs: f32) -> u64 {
1420    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1421        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1422            Ok(guard) => guard,
1423            Err(_) => return 0,
1424        };
1425        let Some((app, state)) = borrow.as_mut() else {
1426            return 0;
1427        };
1428        let cur_route: String = state.get_route().get_untracked();
1429        let on_game: bool = cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D;
1430        if on_game || app.has_active_animations() {
1431            return app
1432                .step_game_frame(dt_secs)
1433                .map(|stats: FrameStats| stats.get_frame_hash())
1434                .unwrap_or(0);
1435        }
1436        app.get_renderer().get_last_stats().get_frame_hash()
1437    })
1438}
1439
1440/// Resizes the persistent WebAssembly showcase canvas and viewport immediately and re-renders.
1441///
1442/// # Arguments
1443///
1444/// - `u32` - New logical viewport width in CSS pixels.
1445/// - `u32` - New logical viewport height in CSS pixels.
1446/// - `f32` - Active browser `window.devicePixelRatio`.
1447///
1448/// # Returns
1449///
1450/// - `u64` - Deterministic frame hash produced by the resized render.
1451#[cfg(target_arch = "wasm32")]
1452#[wasm_bindgen]
1453pub fn euv_web_resize(width: u32, height: u32, dpr: f32) -> u64 {
1454    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1455        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1456            Ok(guard) => guard,
1457            Err(_) => return 0,
1458        };
1459        let Some((app, _)) = borrow.as_mut() else {
1460            return 0;
1461        };
1462        let w: u32 = width.max(320);
1463        let h: u32 = height.max(320);
1464        let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
1465            dpr.clamp(0.5, 4.5)
1466        } else {
1467            1.0
1468        };
1469        let phys_w: u32 = ((w as f64) * (scale as f64)).round().max(1.0) as u32;
1470        let phys_h: u32 = ((h as f64) * (scale as f64)).round().max(1.0) as u32;
1471        if let Some(win) = window()
1472            && let Some(doc) = win.document()
1473            && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
1474            && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
1475        {
1476            if canvas.width() != phys_w {
1477                canvas.set_width(phys_w);
1478            }
1479            if canvas.height() != phys_h {
1480                canvas.set_height(phys_h);
1481            }
1482        }
1483        app.set_exact_physical_viewport(phys_w, phys_h, scale);
1484        app.step_frame()
1485            .map(|stats: FrameStats| stats.get_frame_hash())
1486            .unwrap_or(0)
1487    })
1488}
1489
1490/// Executes an AI Schema v1 JSON query against the live WebAssembly showcase in dev builds only (stripped in release).
1491///
1492/// # Arguments
1493///
1494/// - `&str` - Serialized `AiSchemaRequest` JSON string.
1495///
1496/// # Returns
1497///
1498/// - `String` - Serialized `AiSchemaResponse` JSON string.
1499#[cfg(all(debug_assertions, target_arch = "wasm32"))]
1500#[wasm_bindgen]
1501pub fn euv_dev_ai_schema(request_json: &str) -> String {
1502    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1503        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1504            Ok(guard) => guard,
1505            Err(_) => return String::new(),
1506        };
1507        let Some((app, state)) = borrow.as_mut() else {
1508            return String::new();
1509        };
1510        let hooks: AiAppHooks = state.build_ai_hooks();
1511        AiSchemaProtocol::handle_json_with_hooks(app, request_json, Some(&hooks))
1512    })
1513}
1514
1515/// Returns the active route string of the persistent WebAssembly showcase for telemetry.
1516///
1517/// # Returns
1518///
1519/// - `String` - Current active route path.
1520#[cfg(target_arch = "wasm32")]
1521#[wasm_bindgen]
1522pub fn euv_web_current_route() -> String {
1523    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1524        match slot.try_borrow() {
1525            Ok(guard) => guard
1526                .as_ref()
1527                .map(|(_, state): &(App, ShowcaseState)| state.get_route().get_untracked())
1528                .unwrap_or_default(),
1529            Err(_) => String::new(),
1530        }
1531    })
1532}