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