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