Skip to main content

euv_example/app/
fn.rs

1use super::*;
2
3/// Builds the default highest-performance `RenderConfig` for `mode` (hardware-first, dirty rects enabled, uncapped refresh).
4///
5/// # Arguments
6///
7/// - `RenderMode` - Requested pipeline mode.
8/// - `bool` - When `true`, enables zero-readback GPU direct-draw on explicit `RenderMode::Hardware`.
9///
10/// # Returns
11///
12/// - `RenderConfig` - Maximum-performance rendering configuration.
13#[must_use]
14pub fn default_showcase_render_config(mode: RenderMode, prefer_direct_gpu: bool) -> RenderConfig {
15    match mode {
16        RenderMode::Software => RenderConfig::software(),
17        RenderMode::Hardware => {
18            if prefer_direct_gpu {
19                RenderConfig::hardware_direct()
20            } else {
21                RenderConfig::hardware()
22            }
23        }
24        RenderMode::Hybrid => RenderConfig::hybrid(),
25        RenderMode::Auto => RenderConfig::default(),
26    }
27}
28
29/// Builds an `App` and reactive `ShowcaseState` using the default max-performance configuration (`RenderMode::Auto`).
30///
31/// # Arguments
32///
33/// - `bool` - When `true`, uses deterministic `HeadlessPlatform`; otherwise uses the active native OS backend.
34///
35/// # Returns
36///
37/// - `Result<(App, ShowcaseState), PlatformError>` - Initialized showcase app and state.
38pub fn create_showcase_app_default(headless: bool) -> Result<(App, ShowcaseState), PlatformError> {
39    create_showcase_app(headless, RenderMode::Auto)
40}
41
42/// Maps an active `PlatformKind` to its selector index in the `/window` platform matrix.
43///
44/// # Arguments
45///
46/// - `PlatformKind` - Active host platform kind.
47///
48/// # Returns
49///
50/// - `usize` - Index in `0..7`.
51fn host_platform_matrix_index(platform: PlatformKind) -> usize {
52    match platform {
53        PlatformKind::Ios => 0,
54        PlatformKind::IpadOs => 1,
55        PlatformKind::Android | PlatformKind::HarmonyOs | PlatformKind::Wearable => 2,
56        PlatformKind::MacOs => 3,
57        PlatformKind::Windows => 4,
58        PlatformKind::Linux | PlatformKind::Terminal | PlatformKind::TerminalCli => 5,
59        PlatformKind::Web
60        | PlatformKind::MiniApp
61        | PlatformKind::QuickApp
62        | PlatformKind::Headless => 6,
63    }
64}
65
66/// Builds an `App` and reactive `ShowcaseState` configured with explicit initial logical viewport dimensions and DPR scale.
67///
68/// # Arguments
69///
70/// - `bool` - When `true`, uses deterministic `HeadlessPlatform`; otherwise uses the active native OS backend.
71/// - `RenderMode` - Initial rendering pipeline mode.
72/// - `u32` - Initial logical viewport width in pixels.
73/// - `u32` - Initial logical viewport height in pixels.
74/// - `f32` - Initial device pixel ratio (`>= 0.5`).
75///
76/// # Returns
77///
78/// - `Result<(App, ShowcaseState), PlatformError>` - Initialized showcase app and state.
79pub fn create_showcase_app_with_viewport(
80    headless: bool,
81    mode: RenderMode,
82    logical_width: u32,
83    logical_height: u32,
84    initial_scale: f32,
85) -> Result<(App, ShowcaseState), PlatformError> {
86    EuvOverlayStack::clear();
87    reset_fullscreen_state();
88    clear_provided_theme();
89    let init_w: u32 = logical_width.max(320);
90    let init_h: u32 = logical_height.max(320);
91    let init_scale: f32 = if initial_scale.is_finite() && initial_scale > 0.0 {
92        initial_scale.clamp(0.5, 4.5)
93    } else {
94        1.0
95    };
96    let render_cfg: RenderConfig = default_showcase_render_config(mode, headless);
97    let mut window_cfg: WindowConfig = WindowConfig::default();
98    window_cfg
99        .set_title(SHOWCASE_WINDOW_TITLE.to_string())
100        .set_size(init_w, init_h)
101        .set_render(render_cfg)
102        .set_icon(Some(euv_brand_logo_image()));
103    let mut app_cfg: AppConfig = AppConfig::default();
104    app_cfg.set_window(window_cfg);
105    let mut app: App = if headless {
106        App::headless(app_cfg)?
107    } else {
108        App::new(app_cfg)?
109    };
110    if (init_scale - 1.0).abs() > 0.005 {
111        let phys_w: u32 = ((init_w as f64) * (init_scale as f64)).round().max(1.0) as u32;
112        let phys_h: u32 = ((init_h as f64) * (init_scale as f64)).round().max(1.0) as u32;
113        app.set_exact_physical_viewport(phys_w, phys_h, init_scale);
114    }
115    let enable_bg_workers: bool = !headless && cfg!(not(target_arch = "wasm32"));
116    let state: ShowcaseState =
117        ShowcaseState::new_with_hub(app.get_dynamic_hub().clone(), enable_bg_workers);
118    state.set_default_host_platform_idx(host_platform_matrix_index(app.platform_kind()));
119    app.attach_game_host(state.get_game_host().clone());
120    app.attach_game_host(state.get_game3d_host().clone());
121    app.attach_game_host(state.get_water_host().clone());
122    let mount_state: ShowcaseState = state.clone();
123    let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
124    Ok((app, state))
125}
126
127/// Builds an `App` and reactive `ShowcaseState` configured for either native OS or headless mode.
128///
129/// # Arguments
130///
131/// - `bool` - When `true`, uses deterministic `HeadlessPlatform`; otherwise uses the active native OS backend.
132/// - `RenderMode` - Initial rendering pipeline mode.
133///
134/// # Returns
135///
136/// - `Result<(App, ShowcaseState), PlatformError>` - Initialized showcase app and state.
137pub fn create_showcase_app(
138    headless: bool,
139    mode: RenderMode,
140) -> Result<(App, ShowcaseState), PlatformError> {
141    create_showcase_app_with_viewport(
142        headless,
143        mode,
144        SHOWCASE_WINDOW_WIDTH,
145        SHOWCASE_WINDOW_HEIGHT,
146        1.0,
147    )
148}
149
150/// Builds an `App` and reactive `ShowcaseState` reporting a specific host `PlatformKind` (for native mobile hosts).
151///
152/// # Arguments
153///
154/// - `PlatformKind` - Active native host platform identity (e.g. `PlatformKind::Android`, `PlatformKind::Ios`).
155/// - `RenderMode` - Initial rendering pipeline mode.
156///
157/// # Returns
158///
159/// - `Result<(App, ShowcaseState), PlatformError>` - Initialized showcase app and state.
160pub fn create_showcase_app_for_platform(
161    platform: PlatformKind,
162    mode: RenderMode,
163) -> Result<(App, ShowcaseState), PlatformError> {
164    EuvOverlayStack::clear();
165    reset_fullscreen_state();
166    clear_provided_theme();
167    let render_cfg: RenderConfig = default_showcase_render_config(mode, false);
168    let mut window_cfg: WindowConfig = WindowConfig::default();
169    window_cfg
170        .set_title(SHOWCASE_WINDOW_TITLE.to_string())
171        .set_size(SHOWCASE_WINDOW_WIDTH, SHOWCASE_WINDOW_HEIGHT)
172        .set_render(render_cfg)
173        .set_icon(Some(euv_brand_logo_image()));
174    let mut app_cfg: AppConfig = AppConfig::default();
175    app_cfg.set_window(window_cfg);
176    let backend: Box<dyn PlatformBackend> = Box::new(HeadlessPlatform::emulating(
177        platform,
178        1.0,
179        SafeAreaInsets::default(),
180    ));
181    let mut app: App = App::with_platform(app_cfg, backend)?;
182    let state: ShowcaseState = ShowcaseState::new_with_hub(app.get_dynamic_hub().clone(), false);
183    state.set_default_host_platform_idx(host_platform_matrix_index(app.platform_kind()));
184    app.attach_game_host(state.get_game_host().clone());
185    app.attach_game_host(state.get_game3d_host().clone());
186    app.attach_game_host(state.get_water_host().clone());
187    let mount_state: ShowcaseState = state.clone();
188    let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
189    Ok((app, state))
190}
191
192/// Runs a complete headless smoke render of the showcase and returns frame telemetry.
193///
194/// # Arguments
195///
196/// - `RenderMode` - Rendering pipeline mode to verify.
197///
198/// # Returns
199///
200/// - `Result<FrameStats, PlatformError>` - Rendered frame statistics and deterministic pixel hash.
201pub fn run_headless_smoke(mode: RenderMode) -> Result<FrameStats, PlatformError> {
202    let (mut app, _): (App, ShowcaseState) = create_showcase_app(true, mode)?;
203    app.step_frame()
204}
205
206/// Steps one frame and writes the rendered RGBA framebuffer to `<out_dir>/<name>.rgba`.
207///
208/// # Arguments
209///
210/// - `&mut App` - Active headless application instance.
211/// - `&Path` - Output directory path.
212/// - `&str` - Frame file basename without extension.
213/// - `&mut String` - Manifest accumulator receiving `<name> <width> <height>` lines.
214/// - `&mut usize` - Running captured frame counter.
215///
216/// # Returns
217///
218/// - `Result<(), PlatformError>` - Success or platform/filesystem error.
219#[cfg(not(target_arch = "wasm32"))]
220fn dump_rgba_frame(
221    app: &mut App,
222    out_dir: &Path,
223    name: &str,
224    manifest: &mut String,
225    count: &mut usize,
226) -> Result<(), PlatformError> {
227    let _: FrameStats = app.step_frame()?;
228    for _ in 0..20 {
229        if !app.has_active_animations() {
230            break;
231        }
232        let _: FrameStats = app.step_game_frame(1.0 / 60.0)?;
233    }
234    if let Some(fb) = app.get_renderer().framebuffer() {
235        let file_name: String = format!("{name}.rgba");
236        let file_path: PathBuf = out_dir.join(&file_name);
237        fs::write(&file_path, fb.get_pixels().as_slice())
238            .map_err(|err: Error| PlatformError::SurfaceError(err.to_string()))?;
239        manifest.push_str(&format!("{name} {} {}\n", fb.get_width(), fb.get_height()));
240        *count += 1;
241    }
242    Ok(())
243}
244
245/// Renders all showcase routes, responsive viewports, dark mode, scroll positions, and overlays to raw RGBA files using native system fonts.
246///
247/// # Arguments
248///
249/// - `&Path` - Destination directory for captured `.rgba` frames and `manifest.txt`.
250///
251/// # Returns
252///
253/// - `Result<usize, PlatformError>` - Total number of captured frames.
254#[cfg(not(target_arch = "wasm32"))]
255pub fn capture_showcase_screenshots(out_dir: &Path) -> Result<usize, PlatformError> {
256    reset_reactive_runtime();
257    EuvOverlayStack::clear();
258    reset_fullscreen_state();
259    clear_provided_theme();
260    fs::create_dir_all(out_dir)
261        .map_err(|err: Error| PlatformError::InitializationFailed(err.to_string()))?;
262    let mut window_cfg: WindowConfig = WindowConfig::default();
263    window_cfg
264        .set_title(SHOWCASE_WINDOW_TITLE.to_string())
265        .set_size(1200, 800)
266        .set_render(RenderConfig::software())
267        .set_icon(Some(euv_brand_logo_image()));
268    let mut app_cfg: AppConfig = AppConfig::default();
269    app_cfg.set_window(window_cfg);
270    let backend: Box<dyn PlatformBackend> = Box::new(HeadlessPlatform::emulating(
271        PlatformKind::Headless,
272        2.0,
273        SafeAreaInsets::default(),
274    ));
275    let mut app: App = App::with_platform(app_cfg, backend)?;
276    let state: ShowcaseState = ShowcaseState::new_with_hub(app.get_dynamic_hub().clone(), false);
277    app.attach_game_host(state.get_game_host().clone());
278    app.attach_game_host(state.get_game3d_host().clone());
279    app.attach_game_host(state.get_water_host().clone());
280    let mount_state: ShowcaseState = state.clone();
281    let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
282    app.get_mut_renderer()
283        .get_mut_software()
284        .set_font_provider(NativeSystemFont::system());
285    let wid: WindowId = app.get_window_state().get_id();
286    let mut manifest: String = String::new();
287    let mut count: usize = 0;
288    app.dispatch_window_event(WindowEvent::Resized(wid, 1200, 800, 2.0));
289    let desktop_routes: [(&str, &str); 12] = [
290        (ROUTE_OVERVIEW, "01_overview_desktop"),
291        (ROUTE_REACTIVE, "02_reactive_desktop"),
292        (ROUTE_RENDER, "03_render_desktop"),
293        (ROUTE_WINDOW, "04_window_desktop"),
294        (ROUTE_FORMS, "05_forms_desktop"),
295        (ROUTE_THEMES, "06_themes_desktop"),
296        (ROUTE_DATA, "07_data_desktop"),
297        (ROUTE_GAME, "08_game_desktop"),
298        (ROUTE_GAME_3D, "08b_game3d_desktop"),
299        (ROUTE_MEDIA, "08c_media_desktop"),
300        (ROUTE_OVERLAYS, "09_overlays_desktop"),
301        (ROUTE_DYNAMIC, "10_dynamic_desktop"),
302    ];
303    for (route, label) in desktop_routes.iter() {
304        let _: bool = state.get_route().set_if_changed((*route).to_string());
305        if *route == ROUTE_OVERVIEW {
306            app.dispatch_window_event(WindowEvent::PointerMove(
307                wid,
308                PointerEvent::mouse(100.0, 108.0),
309            ));
310        }
311        dump_rgba_frame(&mut app, out_dir, label, &mut manifest, &mut count)?;
312    }
313    let _: bool = state.get_route().set_if_changed(ROUTE_FORMS.to_string());
314    let _: FrameStats = app.step_frame()?;
315    app.dispatch_window_event(WindowEvent::PointerMove(
316        wid,
317        PointerEvent::mouse(600.0, 400.0),
318    ));
319    app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 420.0)));
320    dump_rgba_frame(
321        &mut app,
322        out_dir,
323        "05b_forms_scrolled",
324        &mut manifest,
325        &mut count,
326    )?;
327    let _: bool = state.get_route().set_if_changed(ROUTE_DATA.to_string());
328    let _: FrameStats = app.step_frame()?;
329    app.dispatch_window_event(WindowEvent::PointerMove(
330        wid,
331        PointerEvent::mouse(600.0, 400.0),
332    ));
333    app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 460.0)));
334    dump_rgba_frame(
335        &mut app,
336        out_dir,
337        "07b_data_vlist_scrolled",
338        &mut manifest,
339        &mut count,
340    )?;
341    app.dispatch_window_event(WindowEvent::PointerMove(
342        wid,
343        PointerEvent::mouse(320.0, 120.0),
344    ));
345    app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 720.0)));
346    dump_rgba_frame(
347        &mut app,
348        out_dir,
349        "07c_data_bottom",
350        &mut manifest,
351        &mut count,
352    )?;
353    let _: bool = state.get_route().set_if_changed(ROUTE_OVERVIEW.to_string());
354    let _: FrameStats = app.step_frame()?;
355    app.dispatch_window_event(WindowEvent::PointerMove(
356        wid,
357        PointerEvent::mouse(100.0, 108.0),
358    ));
359    dump_rgba_frame(
360        &mut app,
361        out_dir,
362        "01b_overview_hovered",
363        &mut manifest,
364        &mut count,
365    )?;
366    let _: bool = state.get_route().set_if_changed(ROUTE_OVERLAYS.to_string());
367    let _: bool = state.get_modal_open().set_if_changed(true);
368    dump_rgba_frame(
369        &mut app,
370        out_dir,
371        "09b_overlays_modal",
372        &mut manifest,
373        &mut count,
374    )?;
375    let _: bool = state.get_modal_open().set_if_changed(false);
376    let _: bool = state.get_alert_dialog_open().set_if_changed(true);
377    dump_rgba_frame(
378        &mut app,
379        out_dir,
380        "09c_overlays_alert",
381        &mut manifest,
382        &mut count,
383    )?;
384    let _: bool = state.get_alert_dialog_open().set_if_changed(false);
385    let _: bool = state.get_hover_card_open().set_if_changed(true);
386    dump_rgba_frame(
387        &mut app,
388        out_dir,
389        "09d_overlays_hovercard",
390        &mut manifest,
391        &mut count,
392    )?;
393    let _: bool = state.get_hover_card_open().set_if_changed(false);
394    let _: bool = state.get_route().set_if_changed(ROUTE_THEMES.to_string());
395    state.toggle_theme_mode();
396    dump_rgba_frame(
397        &mut app,
398        out_dir,
399        "06b_themes_dark",
400        &mut manifest,
401        &mut count,
402    )?;
403    state.toggle_theme_mode();
404    let _: bool = state.get_route().set_if_changed(ROUTE_OVERVIEW.to_string());
405    app.dispatch_window_event(WindowEvent::Resized(wid, 768, 1024, 2.0));
406    dump_rgba_frame(
407        &mut app,
408        out_dir,
409        "11_overview_tablet",
410        &mut manifest,
411        &mut count,
412    )?;
413    app.dispatch_window_event(WindowEvent::Resized(wid, 390, 844, 2.0));
414    dump_rgba_frame(
415        &mut app,
416        out_dir,
417        "12_overview_mobile",
418        &mut manifest,
419        &mut count,
420    )?;
421    app.dispatch_window_event(WindowEvent::PointerDown(
422        wid,
423        PointerEvent::mouse(350.0, 26.0),
424    ));
425    app.dispatch_window_event(WindowEvent::PointerUp(
426        wid,
427        PointerEvent::mouse(350.0, 26.0),
428    ));
429    dump_rgba_frame(
430        &mut app,
431        out_dir,
432        "12b_mobile_menu_open",
433        &mut manifest,
434        &mut count,
435    )?;
436    app.dispatch_window_event(WindowEvent::PointerDown(
437        wid,
438        PointerEvent::mouse(240.0, 26.0),
439    ));
440    app.dispatch_window_event(WindowEvent::PointerUp(
441        wid,
442        PointerEvent::mouse(240.0, 26.0),
443    ));
444    let _: bool = state.get_route().set_if_changed(ROUTE_FORMS.to_string());
445    dump_rgba_frame(
446        &mut app,
447        out_dir,
448        "13_forms_mobile",
449        &mut manifest,
450        &mut count,
451    )?;
452    fs::write(out_dir.join("manifest.txt"), manifest)
453        .map_err(|err: Error| PlatformError::SurfaceError(err.to_string()))?;
454    Ok(count)
455}
456
457/// Normalizes a raw browser URL hash into a valid showcase route, falling back to `"/"` for unknown routes.
458///
459/// # Arguments
460///
461/// - `&str` - Raw `window.location.hash` string (for example `""`, `"#"`, `"#/charts?x=1"`, or `"#//unknown"`).
462///
463/// # Returns
464///
465/// - `String` - Canonical known showcase route path.
466#[must_use]
467pub fn normalize_web_hash_route(raw_hash: &str) -> String {
468    resolve_web_hash_route(raw_hash, None)
469}
470
471/// Normalizes a raw browser URL hash against both static `SHOWCASE_ROUTES` and optional dynamic `DynamicUpdateHub` routes.
472///
473/// # Arguments
474///
475/// - `&str` - Raw `window.location.hash` string.
476/// - `Option<&DynamicUpdateHub>` - Optional live dynamic hub holding OTA-registered routes.
477///
478/// # Returns
479///
480/// - `String` - Canonical known route path, or `"/"` when the target is empty or unknown.
481#[must_use]
482pub fn resolve_web_hash_route(raw_hash: &str, hub: Option<&DynamicUpdateHub>) -> String {
483    let trimmed: &str = raw_hash.trim().trim_start_matches('#');
484    let without_query: &str = trimmed.split(['?', '#']).next().unwrap_or("").trim();
485    let segments: Vec<&str> = without_query
486        .split('/')
487        .filter(|seg: &&str| !seg.is_empty())
488        .collect();
489    if segments.is_empty() {
490        return ROUTE_OVERVIEW.to_string();
491    }
492    let candidate: String = format!("/{}", segments.join("/"));
493    let is_static: bool = SHOWCASE_ROUTES
494        .iter()
495        .any(|spec: &ShowcaseRouteSpec| spec.get_path() == candidate.as_str());
496    let is_dynamic: bool = hub
497        .map(|h: &DynamicUpdateHub| h.has_dynamic_page(&candidate))
498        .unwrap_or(false);
499    if is_static || is_dynamic {
500        candidate
501    } else {
502        ROUTE_OVERVIEW.to_string()
503    }
504}
505
506/// Applies an incoming browser history route (`popstate` / `hashchange`) to `app` and `state`, dismissing overlays and exiting fullscreen first.
507///
508/// # Arguments
509///
510/// - `&mut App` - Live showcase application instance.
511/// - `&ShowcaseState` - Shared reactive showcase state.
512/// - `&str` - Raw `window.location.hash` string from the browser history entry.
513///
514/// # Returns
515///
516/// - `String` - Normalized route path applied to `state`.
517pub fn apply_showcase_history_route(
518    app: &mut App,
519    state: &ShowcaseState,
520    raw_hash: &str,
521) -> String {
522    let next: String = resolve_web_hash_route(raw_hash, Some(state.get_dynamic_hub()));
523    let _: usize = EuvOverlayStack::dismiss_all();
524    let _: bool = state.get_cmd_palette_open().set_if_changed(false);
525    if app.is_immersive_fullscreen() || is_fullscreen_active() {
526        app.set_immersive_fullscreen(false);
527        while is_fullscreen_active() {
528            exit_fullscreen();
529        }
530    }
531    let _: bool = state.get_route().set_if_changed(next.clone());
532    next
533}
534
535/// Returns `true` when a browser `keydown` event should also emit a printable `WindowEvent::TextInput`.
536///
537/// # Arguments
538///
539/// - `bool` - Whether the hidden browser IME proxy `<input>` is currently active.
540/// - `Modifiers` - Active keyboard modifiers on the DOM `KeyboardEvent`.
541/// - `&str` - DOM `KeyboardEvent.key` string.
542///
543/// # Returns
544///
545/// - `bool` - `true` only for unmodified printable single-character keys while IME proxy is inactive.
546#[must_use]
547pub fn web_should_dispatch_text_input(ime_active: bool, mods: Modifiers, key: &str) -> bool {
548    !ime_active && !mods.get_ctrl() && !mods.get_meta() && key.chars().count() == 1
549}
550
551/// Automatically boots the WebAssembly showcase and attaches all browser canvas, input, resize, and frame listeners in pure Rust.
552#[cfg(target_arch = "wasm32")]
553#[wasm_bindgen(start)]
554pub fn euv_web_boot() {
555    let _: u64 = euv_example_web_start();
556    let Some(win): Option<Window> = window() else {
557        return;
558    };
559    let Some(doc): Option<Document> = win.document() else {
560        return;
561    };
562    let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS) else {
563        return;
564    };
565    let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>() else {
566        return;
567    };
568    web_attach_ime_proxy(&doc);
569    register_native_action_bridge(web_native_action_bridge);
570    register_frame_wakeup(web_mark_needs_frame);
571    let _: bool = web_refresh_cached_viewport(&win, &canvas);
572    let _: bool = web_apply_cached_viewport(&canvas);
573    let on_move: Closure<dyn FnMut(web_sys::PointerEvent)> =
574        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
575            let ptr: PointerEvent = web_pointer_from_dom(&ev, None);
576            web_queue_pointer_move_event(ptr);
577        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
578    drop(canvas.add_event_listener_with_callback(
579        WEB_EVENT_POINTER_MOVE,
580        on_move.as_ref().unchecked_ref(),
581    ));
582    on_move.forget();
583    let canvas_down: HtmlCanvasElement = canvas.clone();
584    let on_down: Closure<dyn FnMut(web_sys::PointerEvent)> =
585        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
586            drop(canvas_down.set_pointer_capture(ev.pointer_id()));
587            let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(true));
588            web_queue_pointer_down_event(ptr);
589            if !WEB_IME_ACTIVE.with(Cell::get) {
590                drop(canvas_down.focus());
591            }
592        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
593    drop(canvas.add_event_listener_with_callback(
594        WEB_EVENT_POINTER_DOWN,
595        on_down.as_ref().unchecked_ref(),
596    ));
597    on_down.forget();
598    let canvas_up: HtmlCanvasElement = canvas.clone();
599    let on_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
600        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
601            ev.stop_propagation();
602            let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(false));
603            web_queue_pointer_up_event(ptr);
604            drop(canvas_up.release_pointer_capture(ev.pointer_id()));
605        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
606    drop(
607        canvas
608            .add_event_listener_with_callback(WEB_EVENT_POINTER_UP, on_up.as_ref().unchecked_ref()),
609    );
610    on_up.forget();
611    let on_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
612        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
613            ev.stop_propagation();
614            web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
615        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
616    drop(canvas.add_event_listener_with_callback(
617        WEB_EVENT_POINTER_CANCEL,
618        on_cancel.as_ref().unchecked_ref(),
619    ));
620    drop(canvas.add_event_listener_with_callback(
621        WEB_EVENT_LOST_POINTER_CAPTURE,
622        on_cancel.as_ref().unchecked_ref(),
623    ));
624    on_cancel.forget();
625    let on_win_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
626        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
627            let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(false));
628            web_queue_pointer_up_event(ptr);
629        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
630    drop(win.add_event_listener_with_callback(
631        WEB_EVENT_POINTER_UP,
632        on_win_up.as_ref().unchecked_ref(),
633    ));
634    on_win_up.forget();
635    let on_win_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
636        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
637            web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
638        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
639    drop(win.add_event_listener_with_callback(
640        WEB_EVENT_POINTER_CANCEL,
641        on_win_cancel.as_ref().unchecked_ref(),
642    ));
643    on_win_cancel.forget();
644    let on_touch_cancel: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
645        web_queue_pointer_cancel(0);
646    }) as Box<dyn FnMut(Event)>);
647    drop(canvas.add_event_listener_with_callback(
648        WEB_EVENT_TOUCH_CANCEL,
649        on_touch_cancel.as_ref().unchecked_ref(),
650    ));
651    drop(win.add_event_listener_with_callback(
652        WEB_EVENT_TOUCH_CANCEL,
653        on_touch_cancel.as_ref().unchecked_ref(),
654    ));
655    on_touch_cancel.forget();
656    let on_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
657        web_queue_pointer_cancel(0);
658        web_dispatch_system_event(SystemEvent::FocusChanged(false));
659        web_dispatch_system_event(SystemEvent::Background);
660    }) as Box<dyn FnMut(Event)>);
661    drop(win.add_event_listener_with_callback(WEB_EVENT_BLUR, on_blur.as_ref().unchecked_ref()));
662    on_blur.forget();
663    web_attach_system_event_listeners(&win, &doc, &canvas);
664    let on_wheel: Closure<dyn FnMut(WheelEvent)> = Closure::wrap(Box::new(move |ev: WheelEvent| {
665        ev.prevent_default();
666        let (left, top, _, _, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
667        let x: f32 = (ev.client_x() as f64 - left) as f32;
668        let y: f32 = (ev.client_y() as f64 - top) as f32;
669        let mult: f32 = match ev.delta_mode() {
670            1 => 20.0,
671            2 => 320.0,
672            _ => 1.0,
673        };
674        web_queue_scroll_at(
675            x,
676            y,
677            (ev.delta_x() as f32) * mult,
678            (ev.delta_y() as f32) * mult,
679        );
680    })
681        as Box<dyn FnMut(WheelEvent)>);
682    drop(
683        canvas.add_event_listener_with_callback(WEB_EVENT_WHEEL, on_wheel.as_ref().unchecked_ref()),
684    );
685    on_wheel.forget();
686    let on_key: Closure<dyn FnMut(KeyboardEvent)> =
687        Closure::wrap(Box::new(move |ev: KeyboardEvent| {
688            let key: String = ev.key();
689            let code_str: String = ev.code();
690            let mods: Modifiers =
691                Modifiers::new(ev.shift_key(), ev.ctrl_key(), ev.alt_key(), ev.meta_key());
692            let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
693            let cmd_or_ctrl: bool = mods.get_ctrl() || mods.get_meta();
694            let should_prevent: bool = if cmd_or_ctrl {
695                matches!(code_str.as_str(), WEB_CODE_KEY_K | WEB_CODE_KEY_A)
696            } else if ime_active {
697                matches!(
698                    key.as_str(),
699                    WEB_KEY_ARROW_UP
700                        | WEB_KEY_ARROW_DOWN
701                        | WEB_KEY_ARROW_LEFT
702                        | WEB_KEY_ARROW_RIGHT
703                        | WEB_KEY_BACKSPACE
704                )
705            } else {
706                matches!(
707                    key.as_str(),
708                    WEB_KEY_ARROW_UP
709                        | WEB_KEY_ARROW_DOWN
710                        | WEB_KEY_ARROW_LEFT
711                        | WEB_KEY_ARROW_RIGHT
712                        | WEB_KEY_BACKSPACE
713                        | WEB_KEY_SPACE
714                )
715            };
716            if should_prevent {
717                ev.prevent_default();
718            }
719            web_queue_key_down(&key, &code_str, mods, ev.repeat());
720        }) as Box<dyn FnMut(KeyboardEvent)>);
721    drop(win.add_event_listener_with_callback(WEB_EVENT_KEY_DOWN, on_key.as_ref().unchecked_ref()));
722    on_key.forget();
723    let on_key_up: Closure<dyn FnMut(KeyboardEvent)> =
724        Closure::wrap(Box::new(move |ev: KeyboardEvent| {
725            let key: String = ev.key();
726            let code_str: String = ev.code();
727            let mods: Modifiers =
728                Modifiers::new(ev.shift_key(), ev.ctrl_key(), ev.alt_key(), ev.meta_key());
729            web_queue_key_up(&key, &code_str, mods);
730        }) as Box<dyn FnMut(KeyboardEvent)>);
731    drop(
732        win.add_event_listener_with_callback(WEB_EVENT_KEY_UP, on_key_up.as_ref().unchecked_ref()),
733    );
734    on_key_up.forget();
735    let on_paste: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
736        if let Some(pasted) = web_extract_paste_text(&ev)
737            && !pasted.is_empty()
738        {
739            ev.prevent_default();
740            web_queue_text_input(pasted);
741        }
742    }) as Box<dyn FnMut(Event)>);
743    drop(win.add_event_listener_with_callback(WEB_EVENT_PASTE, on_paste.as_ref().unchecked_ref()));
744    on_paste.forget();
745    let win_resize: Window = win.clone();
746    let canvas_resize: HtmlCanvasElement = canvas.clone();
747    let on_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
748        let viewport_changed: bool = web_refresh_cached_viewport(&win_resize, &canvas_resize);
749        let safe_changed: bool = web_sync_safe_area();
750        if viewport_changed || safe_changed {
751            web_mark_needs_frame();
752        }
753    }) as Box<dyn FnMut(Event)>);
754    drop(
755        win.add_event_listener_with_callback(WEB_EVENT_RESIZE, on_resize.as_ref().unchecked_ref()),
756    );
757    if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
758        && let Ok(vv_target) = vv.dyn_into::<EventTarget>()
759    {
760        drop(vv_target.add_event_listener_with_callback(
761            WEB_EVENT_RESIZE,
762            on_resize.as_ref().unchecked_ref(),
763        ));
764    }
765    on_resize.forget();
766    let win_ro: Window = win.clone();
767    let canvas_ro: HtmlCanvasElement = canvas.clone();
768    let on_ro: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
769        if web_refresh_cached_viewport(&win_ro, &canvas_ro) {
770            web_mark_needs_frame();
771        }
772    }) as Box<dyn FnMut()>);
773    let attach_ro_fn: Function =
774        Function::new_with_args(WEB_JS_ATTACH_RESIZE_ARGS, WEB_JS_ATTACH_RESIZE_OBSERVER);
775    drop(attach_ro_fn.call2(
776        &JsValue::NULL,
777        canvas.as_ref(),
778        on_ro.as_ref().unchecked_ref(),
779    ));
780    on_ro.forget();
781    let win_dpr: Window = win.clone();
782    let canvas_dpr: HtmlCanvasElement = canvas.clone();
783    let on_dpr: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
784        if web_refresh_cached_viewport(&win_dpr, &canvas_dpr) {
785            web_mark_needs_frame();
786        }
787    }) as Box<dyn FnMut()>);
788    let attach_dpr_fn: Function =
789        Function::new_with_args(WEB_JS_WATCH_DPR_ARGS, WEB_JS_WATCH_DPR_BODY);
790    drop(attach_dpr_fn.call1(&JsValue::NULL, on_dpr.as_ref().unchecked_ref()));
791    on_dpr.forget();
792    let win_raf: Window = win.clone();
793    let canvas_raf: HtmlCanvasElement = canvas.clone();
794    WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<Closure<dyn FnMut(f64)>>>| {
795        if let Ok(mut guard) = slot.try_borrow_mut() {
796            *guard = Some(Closure::wrap(Box::new(move |ts: f64| {
797                WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(None));
798                if !web_should_pump_frames() {
799                    WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
800                    WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
801                    WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
802                    return;
803                }
804                let prev_ts: f64 = WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.replace(ts));
805                let mut dt: f32 = 1.0 / 60.0;
806                let mut valid_step: bool = false;
807                if prev_ts > 0.0 {
808                    let raw_dt: f32 = ((ts - prev_ts) / 1000.0) as f32;
809                    if (0.001..=0.1).contains(&raw_dt) {
810                        valid_step = true;
811                    }
812                    dt = raw_dt.clamp(0.001, 0.05);
813                }
814                if valid_step {
815                    let next_secs: f32 = WEB_RAF_ACCUM_SECS.with(Cell::get) + dt;
816                    let next_frames: u32 = WEB_RAF_ACCUM_FRAMES.with(Cell::get).saturating_add(1);
817                    if next_secs >= 0.35 && next_frames >= 8 {
818                        let measured_hz: f32 = (next_frames as f32) / next_secs;
819                        WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
820                        WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
821                        WEB_RAF_CALIBRATED.with(|c: &Cell<bool>| c.set(true));
822                        web_report_host_refresh_rate(measured_hz);
823                    } else {
824                        WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(next_secs));
825                        WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(next_frames));
826                    }
827                }
828                let resized_or_scaled: bool =
829                    if WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.replace(false)) {
830                        web_apply_cached_viewport(&canvas_raf)
831                    } else {
832                        false
833                    };
834                let cur_route: String = euv_web_current_route();
835                let on_game: bool = cur_route == ROUTE_GAME
836                    || cur_route == ROUTE_GAME_3D
837                    || cur_route == ROUTE_WATER;
838                let animating: bool = web_has_active_animations();
839                let dirty: bool = WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.replace(false))
840                    || is_frame_needed();
841                let needs_continuous: bool = resized_or_scaled || on_game;
842                let needs_redraw: bool = animating || dirty;
843                if needs_continuous || needs_redraw {
844                    let _: u64 = web_flush_frame(dt);
845                }
846                let calibrated: bool = WEB_RAF_CALIBRATED.with(Cell::get);
847                let still_active: bool = on_game
848                    || web_has_active_animations()
849                    || WEB_NEEDS_FRAME.with(Cell::get)
850                    || is_frame_needed()
851                    || !calibrated;
852                if still_active && web_should_pump_frames() {
853                    web_start_raf_pump(&win_raf);
854                } else {
855                    WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
856                }
857            }) as Box<dyn FnMut(f64)>));
858        }
859    });
860    if doc.hidden() {
861        web_dispatch_system_event(SystemEvent::Background);
862    } else {
863        web_start_raf_pump(&win);
864    }
865}
866
867/// Returns `true` when the active WebAssembly `App` should pump `requestAnimationFrame` frames.
868///
869/// # Returns
870///
871/// - `bool` - `false` while background-frozen or shutting down.
872#[cfg(target_arch = "wasm32")]
873fn web_should_pump_frames() -> bool {
874    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
875        match slot.try_borrow() {
876            Ok(guard) => {
877                let pump: bool = guard
878                    .as_ref()
879                    .map(|(app, _): &(App, ShowcaseState)| app.should_pump_frames())
880                    .unwrap_or(false);
881                WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
882                pump
883            }
884            Err(_) => WEB_SHOULD_PUMP.with(Cell::get),
885        }
886    })
887}
888
889/// Schedules the retained browser `requestAnimationFrame` callback if no frame is already pending.
890///
891/// # Arguments
892///
893/// - `&Window` - Active browser `Window`.
894#[cfg(target_arch = "wasm32")]
895fn web_start_raf_pump(win: &Window) {
896    if !web_should_pump_frames() {
897        return;
898    }
899    let already_scheduled: bool =
900        WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_some());
901    if already_scheduled {
902        return;
903    }
904    WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<Closure<dyn FnMut(f64)>>>| {
905        if let Ok(cb_ref) = slot.try_borrow()
906            && let Some(cb) = cb_ref.as_ref()
907        {
908            let func: &Function = cb.as_ref().unchecked_ref();
909            if let Ok(req_id) = win.request_animation_frame(func) {
910                WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(Some(req_id)));
911            }
912        }
913    });
914}
915
916/// Cancels any pending browser `requestAnimationFrame` callback and resets rAF timing accumulators for zero-CPU background sleep.
917#[cfg(target_arch = "wasm32")]
918fn web_stop_raf_pump() {
919    let pending_id: Option<i32> = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.take());
920    if let Some(req_id) = pending_id
921        && let Some(win) = window()
922    {
923        drop(win.cancel_animation_frame(req_id));
924    }
925    WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
926    WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
927    WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
928}
929
930/// Dispatches a browser-originated `SystemEvent` into the active WebAssembly `App` and pauses or restarts the rAF pump accordingly.
931///
932/// # Arguments
933///
934/// - `SystemEvent` - Cross-platform system or lifecycle event to normalize and dispatch.
935#[cfg(target_arch = "wasm32")]
936fn web_dispatch_system_event(event: SystemEvent) {
937    let mut should_pump: bool = false;
938    let mut handled: bool = false;
939    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
940        if let Ok(mut borrow) = slot.try_borrow_mut()
941            && let Some((app, _)) = borrow.as_mut()
942        {
943            app.dispatch_system_event(event);
944            should_pump = app.should_pump_frames();
945            handled = true;
946        }
947    });
948    if !handled {
949        return;
950    }
951    WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(should_pump));
952    if !should_pump {
953        web_stop_raf_pump();
954    } else {
955        WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
956        web_mark_needs_frame();
957        if let Some(win) = window() {
958            web_start_raf_pump(&win);
959        }
960    }
961}
962
963/// Extracts plain UTF-8 text from a DOM `paste` event's `clipboardData.getData("text/plain")`.
964///
965/// # Arguments
966///
967/// - `&Event` - Browser DOM `paste` event.
968///
969/// # Returns
970///
971/// - `Option<String>` - Plain text payload when available and non-empty.
972#[cfg(target_arch = "wasm32")]
973fn web_extract_paste_text(ev: &Event) -> Option<String> {
974    let data: JsValue =
975        Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_CLIPBOARD_DATA)).ok()?;
976    if data.is_null() || data.is_undefined() {
977        return None;
978    }
979    let get_fn_val: JsValue = Reflect::get(&data, &JsValue::from_str(WEB_PROP_GET_DATA)).ok()?;
980    let get_fn: Function = get_fn_val.dyn_into::<Function>().ok()?;
981    let result: JsValue = get_fn
982        .call1(&data, &JsValue::from_str(WEB_MIME_TEXT_PLAIN))
983        .ok()?;
984    result.as_string().filter(|s: &String| !s.is_empty())
985}
986
987/// Synchronizes showcase route state from browser `popstate` or `hashchange` without mutating the browser forward stack.
988///
989/// # Arguments
990///
991/// - `&Window` - Active browser `Window`.
992#[cfg(target_arch = "wasm32")]
993fn web_sync_route_from_browser_history(win: &Window) {
994    let raw_hash: String = win.location().hash().unwrap_or_default();
995    let prev_guard: bool = WEB_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
996    let mut updated: bool = false;
997    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
998        if let Ok(mut borrow) = slot.try_borrow_mut()
999            && let Some((app, state)) = borrow.as_mut()
1000        {
1001            let _: String = apply_showcase_history_route(app, state, &raw_hash);
1002            updated = true;
1003        }
1004    });
1005    WEB_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev_guard));
1006    if updated {
1007        let _: bool = web_sync_safe_area();
1008        web_mark_needs_frame();
1009        web_start_raf_pump(win);
1010    }
1011    if let Ok(href) = win.location().href() {
1012        web_dispatch_system_event(SystemEvent::DeepLink(href));
1013    }
1014}
1015
1016/// Returns `true` when the browser document currently has an active fullscreen element (standard or WebKit-prefixed).
1017///
1018/// # Arguments
1019///
1020/// - `&Document` - Active browser `Document`.
1021///
1022/// # Returns
1023///
1024/// - `bool` - `true` when browser fullscreen mode is currently active.
1025#[cfg(target_arch = "wasm32")]
1026fn web_doc_is_fullscreen(doc: &Document) -> bool {
1027    if doc.fullscreen_element().is_some() {
1028        return true;
1029    }
1030    Reflect::get(
1031        doc.as_ref(),
1032        &JsValue::from_str(WEB_PROP_WEBKIT_FULLSCREEN_ELEMENT),
1033    )
1034    .ok()
1035    .map(|v: JsValue| !v.is_null() && !v.is_undefined())
1036    .unwrap_or(false)
1037}
1038
1039/// Reconciles `euv` immersive fullscreen state after a browser `fullscreenchange` event (including user `Escape` exit).
1040///
1041/// # Arguments
1042///
1043/// - `&Window` - Active browser `Window`.
1044/// - `&Document` - Active browser `Document`.
1045/// - `&HtmlCanvasElement` - Mounted showcase canvas element.
1046#[cfg(target_arch = "wasm32")]
1047fn web_sync_fullscreen_from_dom(win: &Window, doc: &Document, canvas: &HtmlCanvasElement) {
1048    let dom_fs: bool = web_doc_is_fullscreen(doc);
1049    if !dom_fs {
1050        WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1051            if let Ok(mut borrow) = slot.try_borrow_mut()
1052                && let Some((app, _)) = borrow.as_mut()
1053                && (app.is_immersive_fullscreen() || is_fullscreen_active())
1054            {
1055                app.set_immersive_fullscreen(false);
1056                while is_fullscreen_active() {
1057                    exit_fullscreen();
1058                }
1059            }
1060        });
1061    }
1062    let _: bool = web_refresh_cached_viewport(win, canvas);
1063    let _: bool = web_sync_safe_area();
1064    web_mark_needs_frame();
1065    web_start_raf_pump(win);
1066}
1067
1068/// Dispatches a `WindowEvent::ThemeChanged` immediately into the active WebAssembly runtime and schedules a repaint.
1069///
1070/// # Arguments
1071///
1072/// - `ThemeMode` - Newly active browser color-scheme preference.
1073#[cfg(target_arch = "wasm32")]
1074fn web_dispatch_theme_changed(mode: ThemeMode) {
1075    let mut dispatched: bool = false;
1076    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1077        if let Ok(mut borrow) = slot.try_borrow_mut()
1078            && let Some((app, _)) = borrow.as_mut()
1079        {
1080            let wid: WindowId = app.get_window_state().get_id();
1081            app.dispatch_window_event(WindowEvent::ThemeChanged(wid, mode));
1082            dispatched = true;
1083        }
1084    });
1085    if dispatched {
1086        web_mark_needs_frame();
1087    }
1088}
1089
1090/// Refreshes viewport, DPR, safe area, and screen orientation after a browser `orientationchange` event.
1091///
1092/// # Arguments
1093///
1094/// - `&Window` - Active browser `Window`.
1095/// - `&HtmlCanvasElement` - Mounted showcase canvas element.
1096#[cfg(target_arch = "wasm32")]
1097fn web_handle_orientation_change(win: &Window, canvas: &HtmlCanvasElement) {
1098    let _: bool = web_refresh_cached_viewport(win, canvas);
1099    let _: bool = web_sync_safe_area();
1100    let (_, _, css_w, css_h, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1101    let orient: ScreenOrientation = if css_w > css_h {
1102        ScreenOrientation::Landscape
1103    } else {
1104        ScreenOrientation::Portrait
1105    };
1106    web_dispatch_system_event(SystemEvent::OrientationChanged(orient));
1107    web_mark_needs_frame();
1108    web_start_raf_pump(win);
1109}
1110
1111/// Attaches browser DOM lifecycle, focus, connectivity, color-scheme, history, fullscreen, orientation, and soft-keyboard listeners onto `win`, `doc`, and `canvas`.
1112///
1113/// # Arguments
1114///
1115/// - `&Window` - Active browser `Window`.
1116/// - `&Document` - Active browser `Document`.
1117/// - `&HtmlCanvasElement` - Mounted showcase canvas element.
1118#[cfg(target_arch = "wasm32")]
1119fn web_attach_system_event_listeners(win: &Window, doc: &Document, canvas: &HtmlCanvasElement) {
1120    let doc_vis: Document = doc.clone();
1121    let win_vis: Window = win.clone();
1122    let canvas_vis: HtmlCanvasElement = canvas.clone();
1123    let on_vis: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1124        if doc_vis.hidden() {
1125            web_queue_pointer_cancel(0);
1126            web_dispatch_system_event(SystemEvent::Background);
1127        } else {
1128            let _: bool = web_refresh_cached_viewport(&win_vis, &canvas_vis);
1129            let _: bool = web_sync_safe_area();
1130            web_dispatch_system_event(SystemEvent::Foreground);
1131        }
1132    }) as Box<dyn FnMut(Event)>);
1133    drop(doc.add_event_listener_with_callback(
1134        WEB_EVENT_VISIBILITY_CHANGE,
1135        on_vis.as_ref().unchecked_ref(),
1136    ));
1137    on_vis.forget();
1138    let win_focus: Window = win.clone();
1139    let canvas_focus: HtmlCanvasElement = canvas.clone();
1140    let on_focus: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1141        let _: bool = web_refresh_cached_viewport(&win_focus, &canvas_focus);
1142        let _: bool = web_sync_safe_area();
1143        web_dispatch_system_event(SystemEvent::Foreground);
1144        web_dispatch_system_event(SystemEvent::FocusChanged(true));
1145    }) as Box<dyn FnMut(Event)>);
1146    drop(win.add_event_listener_with_callback(WEB_EVENT_FOCUS, on_focus.as_ref().unchecked_ref()));
1147    on_focus.forget();
1148    let win_ps: Window = win.clone();
1149    let canvas_ps: HtmlCanvasElement = canvas.clone();
1150    let on_pageshow: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1151        let _: bool = web_refresh_cached_viewport(&win_ps, &canvas_ps);
1152        let _: bool = web_sync_safe_area();
1153        web_sync_route_from_browser_history(&win_ps);
1154        web_dispatch_system_event(SystemEvent::Foreground);
1155    }) as Box<dyn FnMut(Event)>);
1156    drop(win.add_event_listener_with_callback(
1157        WEB_EVENT_PAGE_SHOW,
1158        on_pageshow.as_ref().unchecked_ref(),
1159    ));
1160    on_pageshow.forget();
1161    let on_pagehide: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1162        web_queue_pointer_cancel(0);
1163        web_dispatch_system_event(SystemEvent::Background);
1164    }) as Box<dyn FnMut(Event)>);
1165    drop(win.add_event_listener_with_callback(
1166        WEB_EVENT_PAGE_HIDE,
1167        on_pagehide.as_ref().unchecked_ref(),
1168    ));
1169    on_pagehide.forget();
1170    let on_unload: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1171        web_dispatch_system_event(SystemEvent::Terminate);
1172    }) as Box<dyn FnMut(Event)>);
1173    drop(win.add_event_listener_with_callback(
1174        WEB_EVENT_BEFORE_UNLOAD,
1175        on_unload.as_ref().unchecked_ref(),
1176    ));
1177    on_unload.forget();
1178    let on_online: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1179        web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Online));
1180    }) as Box<dyn FnMut(Event)>);
1181    drop(
1182        win.add_event_listener_with_callback(WEB_EVENT_ONLINE, on_online.as_ref().unchecked_ref()),
1183    );
1184    on_online.forget();
1185    let on_offline: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1186        web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Offline));
1187    }) as Box<dyn FnMut(Event)>);
1188    drop(
1189        win.add_event_listener_with_callback(
1190            WEB_EVENT_OFFLINE,
1191            on_offline.as_ref().unchecked_ref(),
1192        ),
1193    );
1194    on_offline.forget();
1195    if let Ok(Some(mql)) = win.match_media(WEB_MEDIA_PREFERS_DARK) {
1196        let mql_cb: MediaQueryList = mql.clone();
1197        let on_theme: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1198            let next_theme: ThemeMode = if mql_cb.matches() {
1199                ThemeMode::Dark
1200            } else {
1201                ThemeMode::Light
1202            };
1203            web_dispatch_theme_changed(next_theme);
1204        })
1205            as Box<dyn FnMut(Event)>);
1206        drop(
1207            mql.add_event_listener_with_callback(
1208                WEB_EVENT_CHANGE,
1209                on_theme.as_ref().unchecked_ref(),
1210            ),
1211        );
1212        on_theme.forget();
1213    }
1214    let win_hist: Window = win.clone();
1215    let on_history: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1216        web_sync_route_from_browser_history(&win_hist);
1217    }) as Box<dyn FnMut(Event)>);
1218    drop(win.add_event_listener_with_callback(
1219        WEB_EVENT_HASH_CHANGE,
1220        on_history.as_ref().unchecked_ref(),
1221    ));
1222    drop(win.add_event_listener_with_callback(
1223        WEB_EVENT_POP_STATE,
1224        on_history.as_ref().unchecked_ref(),
1225    ));
1226    on_history.forget();
1227    let win_fs: Window = win.clone();
1228    let doc_fs: Document = doc.clone();
1229    let canvas_fs: HtmlCanvasElement = canvas.clone();
1230    let on_fs_change: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1231        web_sync_fullscreen_from_dom(&win_fs, &doc_fs, &canvas_fs);
1232    }) as Box<dyn FnMut(Event)>);
1233    drop(doc.add_event_listener_with_callback(
1234        WEB_EVENT_FULLSCREEN_CHANGE,
1235        on_fs_change.as_ref().unchecked_ref(),
1236    ));
1237    drop(doc.add_event_listener_with_callback(
1238        WEB_EVENT_WEBKIT_FULLSCREEN_CHANGE,
1239        on_fs_change.as_ref().unchecked_ref(),
1240    ));
1241    on_fs_change.forget();
1242    let win_orient: Window = win.clone();
1243    let canvas_orient: HtmlCanvasElement = canvas.clone();
1244    let on_orient: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1245        web_handle_orientation_change(&win_orient, &canvas_orient);
1246    }) as Box<dyn FnMut(Event)>);
1247    drop(win.add_event_listener_with_callback(
1248        WEB_EVENT_ORIENTATION_CHANGE,
1249        on_orient.as_ref().unchecked_ref(),
1250    ));
1251    if let Ok(screen_val) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_SCREEN))
1252        && !screen_val.is_null()
1253        && !screen_val.is_undefined()
1254        && let Ok(orient_val) = Reflect::get(&screen_val, &JsValue::from_str(WEB_PROP_ORIENTATION))
1255        && let Ok(orient_target) = orient_val.dyn_into::<EventTarget>()
1256    {
1257        drop(orient_target.add_event_listener_with_callback(
1258            WEB_EVENT_CHANGE,
1259            on_orient.as_ref().unchecked_ref(),
1260        ));
1261    }
1262    on_orient.forget();
1263    let vv_key: JsValue = JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT);
1264    if let Ok(vv_val) = Reflect::get(win.as_ref(), &vv_key)
1265        && let Ok(vv_target) = vv_val.clone().dyn_into::<EventTarget>()
1266    {
1267        let win_vv: Window = win.clone();
1268        let vv_obj: JsValue = vv_val;
1269        let on_vv_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1270            let inner_h: f32 = win_vv
1271                .inner_height()
1272                .ok()
1273                .and_then(|v: JsValue| v.as_f64())
1274                .unwrap_or(0.0) as f32;
1275            let h_key: JsValue = JsValue::from_str(WEB_PROP_HEIGHT);
1276            let vv_h: f32 = Reflect::get(&vv_obj, &h_key)
1277                .ok()
1278                .and_then(|v: JsValue| v.as_f64())
1279                .unwrap_or(inner_h as f64) as f32;
1280            let kb_delta: f32 = (inner_h - vv_h).max(0.0);
1281            let visible: bool = kb_delta >= WEB_KEYBOARD_MIN_DELTA_PX;
1282            let height: f32 = if visible { kb_delta } else { 0.0 };
1283            web_dispatch_system_event(SystemEvent::KeyboardVisibilityChanged { visible, height });
1284            if web_sync_safe_area() {
1285                web_mark_needs_frame();
1286            }
1287        })
1288            as Box<dyn FnMut(Event)>);
1289        drop(vv_target.add_event_listener_with_callback(
1290            WEB_EVENT_RESIZE,
1291            on_vv_resize.as_ref().unchecked_ref(),
1292        ));
1293        on_vv_resize.forget();
1294    }
1295}
1296
1297/// Maps a browser `KeyboardEvent.key` and physical `KeyboardEvent.code` into a cross-platform `KeyCode`.
1298///
1299/// # Arguments
1300///
1301/// - `&str` - Browser DOM `KeyboardEvent.key` string.
1302/// - `&str` - Browser DOM physical `KeyboardEvent.code` string (IME-independent).
1303///
1304/// # Returns
1305///
1306/// - `KeyCode` - Normalized `euv` key code.
1307#[cfg(target_arch = "wasm32")]
1308fn web_map_key(key: &str, code_str: &str) -> KeyCode {
1309    match code_str {
1310        WEB_CODE_KEY_W => return KeyCode::Character('w'),
1311        WEB_CODE_KEY_A => return KeyCode::Character('a'),
1312        WEB_CODE_KEY_S => return KeyCode::Character('s'),
1313        WEB_CODE_KEY_D => return KeyCode::Character('d'),
1314        WEB_CODE_KEY_E => return KeyCode::Character('e'),
1315        WEB_CODE_KEY_R => return KeyCode::Character('r'),
1316        WEB_CODE_KEY_P => return KeyCode::Character('p'),
1317        WEB_CODE_KEY_J => return KeyCode::Character('j'),
1318        WEB_CODE_KEY_C => return KeyCode::Character('c'),
1319        WEB_CODE_KEY_V => return KeyCode::Character('v'),
1320        WEB_CODE_KEY_X => return KeyCode::Character('x'),
1321        WEB_CODE_KEY_Z => return KeyCode::Character('z'),
1322        WEB_CODE_KEY_K => return KeyCode::Character('k'),
1323        WEB_CODE_SPACE => return KeyCode::Space,
1324        WEB_KEY_ARROW_LEFT => return KeyCode::ArrowLeft,
1325        WEB_KEY_ARROW_RIGHT => return KeyCode::ArrowRight,
1326        WEB_KEY_ARROW_UP => return KeyCode::ArrowUp,
1327        WEB_KEY_ARROW_DOWN => return KeyCode::ArrowDown,
1328        WEB_KEY_HOME => return KeyCode::Home,
1329        WEB_KEY_END => return KeyCode::End,
1330        WEB_KEY_PAGE_UP => return KeyCode::PageUp,
1331        WEB_KEY_PAGE_DOWN => return KeyCode::PageDown,
1332        _ => {}
1333    }
1334    match key {
1335        WEB_KEY_ENTER => KeyCode::Enter,
1336        WEB_KEY_BACKSPACE => KeyCode::Backspace,
1337        WEB_KEY_DELETE => KeyCode::Delete,
1338        WEB_KEY_ESCAPE => KeyCode::Escape,
1339        WEB_KEY_TAB => KeyCode::Tab,
1340        WEB_KEY_SPACE => KeyCode::Space,
1341        WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
1342        WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
1343        WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
1344        WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
1345        WEB_KEY_HOME => KeyCode::Home,
1346        WEB_KEY_END => KeyCode::End,
1347        WEB_KEY_PAGE_UP => KeyCode::PageUp,
1348        WEB_KEY_PAGE_DOWN => KeyCode::PageDown,
1349        other => other
1350            .chars()
1351            .next()
1352            .map(KeyCode::Character)
1353            .unwrap_or(KeyCode::Unknown),
1354    }
1355}
1356
1357/// Returns `true` when the active WebAssembly app has running UI transition animations.
1358///
1359/// # Returns
1360///
1361/// - `bool` - Whether animation frames must continue ticking.
1362#[cfg(target_arch = "wasm32")]
1363fn web_has_active_animations() -> bool {
1364    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1365        match slot.try_borrow() {
1366            Ok(guard) => guard
1367                .as_ref()
1368                .map(|(app, _): &(App, ShowcaseState)| app.has_active_animations())
1369                .unwrap_or(false),
1370            Err(_) => false,
1371        }
1372    })
1373}
1374
1375/// Marks the coalesced Web animation-frame render flag and wakes the demand-driven `requestAnimationFrame` pump if parked.
1376#[cfg(target_arch = "wasm32")]
1377fn web_mark_needs_frame() {
1378    WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.set(true));
1379    let idle: bool = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_none());
1380    if idle && let Some(win) = window() {
1381        web_start_raf_pump(&win);
1382    }
1383}
1384
1385/// Normalizes a browser `PointerEvent.pointerId` into a non-zero cross-platform pointer identifier.
1386///
1387/// # Arguments
1388///
1389/// - `&web_sys::PointerEvent` - Browser DOM pointer event.
1390///
1391/// # Returns
1392///
1393/// - `u64` - Stable non-zero pointer identifier.
1394#[cfg(target_arch = "wasm32")]
1395fn web_pointer_id_from_dom(ev: &web_sys::PointerEvent) -> u64 {
1396    (ev.pointer_id() as i64).unsigned_abs().saturating_add(1)
1397}
1398
1399/// Converts a browser DOM `PointerEvent` into an `euv::PointerEvent` using cached canvas coordinates without triggering DOM layout reflow.
1400///
1401/// # Arguments
1402///
1403/// - `&web_sys::PointerEvent` - Browser DOM pointer event.
1404/// - `Option<bool>` - Optional explicit pressed override (`Some(true)` on down, `Some(false)` on up, `None` to inspect `buttons()`).
1405///
1406/// # Returns
1407///
1408/// - `PointerEvent` - Cross-platform pointer event.
1409#[cfg(target_arch = "wasm32")]
1410fn web_pointer_from_dom(ev: &web_sys::PointerEvent, force_pressed: Option<bool>) -> PointerEvent {
1411    let (left, top, _, _, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1412    let x: f32 = (ev.client_x() as f64 - left) as f32;
1413    let y: f32 = (ev.client_y() as f64 - top) as f32;
1414    let pid: u64 = web_pointer_id_from_dom(ev);
1415    let ptype: String = ev.pointer_type();
1416    let device: PointerDevice = if ptype == WEB_PTR_TYPE_TOUCH {
1417        PointerDevice::Touch
1418    } else if ptype == WEB_PTR_TYPE_PEN {
1419        PointerDevice::Stylus
1420    } else {
1421        PointerDevice::Mouse
1422    };
1423    let is_pressed: bool =
1424        force_pressed.unwrap_or_else(|| ev.buttons() != 0 || device == PointerDevice::Touch);
1425    let pressure: f32 = if is_pressed { 1.0 } else { 0.0 };
1426    let mods: Modifiers =
1427        Modifiers::new(ev.shift_key(), ev.ctrl_key(), ev.alt_key(), ev.meta_key());
1428    PointerEvent::new(
1429        pid,
1430        device,
1431        Point::new(x, y),
1432        PointerButton::Primary,
1433        pressure,
1434        mods,
1435    )
1436}
1437
1438/// Enqueues a browser pointer move into the active WebAssembly runtime without forcing redundant repaints on no-op hover movement.
1439///
1440/// # Arguments
1441///
1442/// - `PointerEvent` - Normalized pointer move event.
1443#[cfg(target_arch = "wasm32")]
1444fn web_queue_pointer_move_event(ptr: PointerEvent) {
1445    let mut needs_redraw: bool = false;
1446    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1447        if let Ok(mut borrow) = slot.try_borrow_mut()
1448            && let Some((app, _)) = borrow.as_mut()
1449        {
1450            let rev_before: u64 = app.get_scene().with_read(SceneTree::get_revision, 0);
1451            let cursor_before: CursorIcon = app.get_last_cursor();
1452            let wid: WindowId = app.get_window_state().get_id();
1453            app.dispatch_window_event(WindowEvent::PointerMove(wid, ptr));
1454            let rev_after: u64 = app.get_scene().with_read(SceneTree::get_revision, 0);
1455            let cursor_after: CursorIcon = app.get_last_cursor();
1456            let active_drag: bool =
1457                ptr.get_pressure() > 0.0 || ptr.get_device() != PointerDevice::Mouse;
1458            let has_anim: bool = app
1459                .get_scene()
1460                .with_read(SceneTree::has_active_transitions, false);
1461            needs_redraw = rev_after != rev_before
1462                || cursor_after != cursor_before
1463                || active_drag
1464                || has_anim
1465                || is_frame_needed();
1466        }
1467    });
1468    if needs_redraw {
1469        web_mark_needs_frame();
1470    }
1471}
1472
1473/// Enqueues a browser pointer press into the active WebAssembly runtime for the next animation frame.
1474///
1475/// # Arguments
1476///
1477/// - `PointerEvent` - Normalized pointer press event.
1478#[cfg(target_arch = "wasm32")]
1479fn web_queue_pointer_down_event(ptr: PointerEvent) {
1480    let mut queued: bool = false;
1481    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1482        if let Ok(mut borrow) = slot.try_borrow_mut()
1483            && let Some((app, _)) = borrow.as_mut()
1484        {
1485            let wid: WindowId = app.get_window_state().get_id();
1486            app.dispatch_window_event(WindowEvent::PointerDown(wid, ptr));
1487            queued = true;
1488        }
1489    });
1490    if queued {
1491        web_mark_needs_frame();
1492    }
1493}
1494
1495/// Enqueues a browser pointer release into the active WebAssembly runtime for the next animation frame.
1496///
1497/// # Arguments
1498///
1499/// - `PointerEvent` - Normalized pointer release event.
1500#[cfg(target_arch = "wasm32")]
1501fn web_queue_pointer_up_event(ptr: PointerEvent) {
1502    let mut queued: bool = false;
1503    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1504        if let Ok(mut borrow) = slot.try_borrow_mut()
1505            && let Some((app, _)) = borrow.as_mut()
1506        {
1507            let wid: WindowId = app.get_window_state().get_id();
1508            app.dispatch_window_event(WindowEvent::PointerUp(wid, ptr));
1509            queued = true;
1510        }
1511    });
1512    if queued {
1513        web_mark_needs_frame();
1514    }
1515}
1516
1517/// Enqueues a browser pointer cancel (`0` cancels all active contacts) into the active WebAssembly runtime.
1518///
1519/// # Arguments
1520///
1521/// - `u64` - Cancelled pointer identifier (`0` cancels all active pointers).
1522#[cfg(target_arch = "wasm32")]
1523fn web_queue_pointer_cancel(pointer_id: u64) {
1524    let mut queued: bool = false;
1525    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1526        if let Ok(mut borrow) = slot.try_borrow_mut()
1527            && let Some((app, _)) = borrow.as_mut()
1528        {
1529            let wid: WindowId = app.get_window_state().get_id();
1530            app.dispatch_window_event(WindowEvent::PointerCancel(wid, pointer_id));
1531            queued = true;
1532        }
1533    });
1534    if queued {
1535        web_mark_needs_frame();
1536    }
1537}
1538
1539/// Enqueues a normalized browser wheel scroll delta at `(x, y)` for coalesced VSync rendering.
1540///
1541/// # Arguments
1542///
1543/// - `f32` - Pointer X coordinate inside the canvas.
1544/// - `f32` - Pointer Y coordinate inside the canvas.
1545/// - `f32` - Horizontal scroll delta.
1546/// - `f32` - Vertical scroll delta.
1547#[cfg(target_arch = "wasm32")]
1548fn web_queue_scroll_at(x: f32, y: f32, dx: f32, dy: f32) {
1549    let mut queued: bool = false;
1550    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1551        if let Ok(mut borrow) = slot.try_borrow_mut()
1552            && let Some((app, _)) = borrow.as_mut()
1553        {
1554            let wid: WindowId = app.get_window_state().get_id();
1555            app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
1556            app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
1557            queued = true;
1558        }
1559    });
1560    if queued {
1561        web_mark_needs_frame();
1562    }
1563}
1564
1565/// Enqueues a browser key-down and optional printable text event for the next animation frame.
1566///
1567/// # Arguments
1568///
1569/// - `&str` - DOM `KeyboardEvent.key` string.
1570/// - `&str` - DOM physical `KeyboardEvent.code` string.
1571/// - `Modifiers` - Active Shift/Ctrl/Alt/Meta modifier flags from the DOM `KeyboardEvent`.
1572/// - `bool` - Whether the DOM `KeyboardEvent` is a key auto-repeat.
1573#[cfg(target_arch = "wasm32")]
1574fn web_queue_key_down(key: &str, code_str: &str, mods: Modifiers, repeat: bool) {
1575    if WEB_IME_COMPOSING.with(Cell::get) {
1576        return;
1577    }
1578    let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
1579    let mut queued: bool = false;
1580    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1581        if let Ok(mut borrow) = slot.try_borrow_mut()
1582            && let Some((app, _)) = borrow.as_mut()
1583        {
1584            let wid: WindowId = app.get_window_state().get_id();
1585            let code: KeyCode = web_map_key(key, code_str);
1586            let key_ev: WindowEvent = WindowEvent::KeyDown(wid, KeyEvent::new(code, mods, repeat));
1587            app.dispatch_window_event(key_ev);
1588            if web_should_dispatch_text_input(ime_active, mods, key) {
1589                app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
1590            }
1591            queued = true;
1592        }
1593    });
1594    if queued {
1595        web_mark_needs_frame();
1596    }
1597}
1598
1599/// Dispatches committed browser IME or virtual keyboard text into the active WebAssembly runtime.
1600///
1601/// # Arguments
1602///
1603/// - `String` - Committed UTF-8 text from the hidden IME proxy input.
1604#[cfg(target_arch = "wasm32")]
1605fn web_queue_text_input(text: String) {
1606    if text.is_empty() {
1607        return;
1608    }
1609    let mut queued: bool = false;
1610    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1611        if let Ok(mut borrow) = slot.try_borrow_mut()
1612            && let Some((app, _)) = borrow.as_mut()
1613        {
1614            let wid: WindowId = app.get_window_state().get_id();
1615            app.dispatch_window_event(WindowEvent::TextInput(wid, text));
1616            queued = true;
1617        }
1618    });
1619    if queued {
1620        web_mark_needs_frame();
1621    }
1622}
1623
1624/// Reads and clears the hidden browser IME proxy `<input>` value, dispatching any pending text into `euv`.
1625///
1626/// # Arguments
1627///
1628/// - `&HtmlElement` - Hidden browser IME proxy element.
1629#[cfg(target_arch = "wasm32")]
1630fn web_flush_ime_element(el: &HtmlElement) {
1631    let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
1632    if let Ok(val) = Reflect::get(el.as_ref(), &key)
1633        && let Some(text) = val.as_string()
1634        && !text.is_empty()
1635    {
1636        let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
1637        web_queue_text_input(text);
1638    }
1639}
1640
1641/// Attaches a visually hidden DOM `<input>` element so mobile browsers and CJK IMEs open native keyboards on input focus.
1642///
1643/// # Arguments
1644///
1645/// - `&Document` - Active browser DOM document.
1646#[cfg(target_arch = "wasm32")]
1647fn web_attach_ime_proxy(doc: &Document) {
1648    let Ok(raw_el) = doc.create_element(WEB_IME_INPUT_TAG) else {
1649        return;
1650    };
1651    let el: Element = raw_el;
1652    drop(el.set_attribute(WEB_IME_ATTR_ID, WEB_IME_INPUT_ID));
1653    drop(el.set_attribute(WEB_IME_ATTR_TYPE, WEB_IME_ATTR_TEXT));
1654    drop(el.set_attribute(WEB_IME_ATTR_AUTOCOMPLETE, WEB_IME_ATTR_OFF));
1655    drop(el.set_attribute(WEB_IME_ATTR_AUTOCORRECT, WEB_IME_ATTR_OFF));
1656    drop(el.set_attribute(WEB_IME_ATTR_AUTOCAPITALIZE, WEB_IME_ATTR_OFF));
1657    drop(el.set_attribute(WEB_IME_ATTR_SPELLCHECK, WEB_IME_ATTR_FALSE));
1658    drop(el.set_attribute(WEB_IME_ATTR_ARIA_LABEL, WEB_IME_ARIA_LABEL));
1659    drop(el.set_attribute(WEB_IME_ATTR_STYLE, WEB_IME_STYLE));
1660    let Ok(html_el) = el.dyn_into::<HtmlElement>() else {
1661        return;
1662    };
1663    if let Some(body) = doc.body() {
1664        drop(body.append_child(&html_el));
1665    }
1666    let comp_start: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1667        WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(true));
1668    }) as Box<dyn FnMut(Event)>);
1669    drop(html_el.add_event_listener_with_callback(
1670        WEB_EVENT_COMPOSITION_START,
1671        comp_start.as_ref().unchecked_ref(),
1672    ));
1673    comp_start.forget();
1674    let comp_el: HtmlElement = html_el.clone();
1675    let comp_end: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1676        WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1677        web_flush_ime_element(&comp_el);
1678    }) as Box<dyn FnMut(Event)>);
1679    drop(html_el.add_event_listener_with_callback(
1680        WEB_EVENT_COMPOSITION_END,
1681        comp_end.as_ref().unchecked_ref(),
1682    ));
1683    comp_end.forget();
1684    let inp_el: HtmlElement = html_el.clone();
1685    let on_input: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1686        if !WEB_IME_COMPOSING.with(Cell::get) {
1687            web_flush_ime_element(&inp_el);
1688        }
1689    }) as Box<dyn FnMut(Event)>);
1690    drop(
1691        html_el
1692            .add_event_listener_with_callback(WEB_EVENT_INPUT, on_input.as_ref().unchecked_ref()),
1693    );
1694    on_input.forget();
1695    let on_ime_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1696        WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
1697        WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1698        WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1699            if let Ok(mut borrow) = slot.try_borrow_mut()
1700                && let Some((app, _)) = borrow.as_mut()
1701            {
1702                let wid: WindowId = app.get_window_state().get_id();
1703                app.dispatch_window_event(WindowEvent::Ime(wid, ImeEvent::Disabled));
1704            }
1705        });
1706    }) as Box<dyn FnMut(Event)>);
1707    drop(
1708        html_el
1709            .add_event_listener_with_callback(WEB_EVENT_BLUR, on_ime_blur.as_ref().unchecked_ref()),
1710    );
1711    on_ime_blur.forget();
1712    WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
1713        if let Ok(mut guard) = slot.try_borrow_mut() {
1714            *guard = Some(html_el);
1715        }
1716    });
1717}
1718
1719/// Handles `euv` native action requests in the browser (fullscreen, external URL open, and hidden IME proxy focus).
1720///
1721/// # Arguments
1722///
1723/// - `&str` - Action category (e.g. `NATIVE_ACTION_FULLSCREEN`, `NATIVE_ACTION_OPEN_URL`, `NATIVE_ACTION_IME`).
1724/// - `&str` - Action subcommand (`"show"` / `"hide"` / `"on"` / `"off"` or external URL).
1725/// - `&str` - Secondary payload argument.
1726///
1727/// # Returns
1728///
1729/// - `bool` - `true` when handled by the browser bridge.
1730#[cfg(target_arch = "wasm32")]
1731fn web_native_action_bridge(kind: &str, arg1: &str, _arg2: &str) -> bool {
1732    if kind == NATIVE_ACTION_FULLSCREEN {
1733        if arg1 == WEB_FS_ACTION_ON {
1734            web_set_fullscreen(true);
1735            return true;
1736        }
1737        if arg1 == WEB_FS_ACTION_OFF {
1738            web_set_fullscreen(false);
1739            return true;
1740        }
1741        return false;
1742    }
1743    if kind == NATIVE_ACTION_OPEN_URL {
1744        if !is_valid_external_url(arg1) {
1745            return false;
1746        }
1747        let Some(win) = window() else {
1748            return false;
1749        };
1750        return win
1751            .open_with_url_and_target_and_features(
1752                arg1.trim(),
1753                WEB_OPEN_TARGET_BLANK,
1754                WEB_OPEN_FEATURES_SAFE,
1755            )
1756            .is_ok();
1757    }
1758    if kind != NATIVE_ACTION_IME {
1759        return false;
1760    }
1761    WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
1762        let Ok(guard) = slot.try_borrow() else {
1763            return false;
1764        };
1765        let Some(el) = guard.as_ref() else {
1766            return false;
1767        };
1768        if arg1 == WEB_IME_ACTION_SHOW {
1769            WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(true));
1770            if let Some(win) = window()
1771                && let Some(doc) = win.document()
1772                && let Some(active_el) = doc.active_element()
1773                && active_el.id() == WEB_IME_INPUT_ID
1774            {
1775                drop(el.blur());
1776            }
1777            drop(el.focus());
1778            true
1779        } else if arg1 == WEB_IME_ACTION_HIDE {
1780            WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
1781            WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1782            let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
1783            let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
1784            drop(el.blur());
1785            true
1786        } else {
1787            false
1788        }
1789    })
1790}
1791
1792/// Enqueues a browser key-up event into the active WebAssembly runtime and game host.
1793///
1794/// # Arguments
1795///
1796/// - `&str` - DOM `KeyboardEvent.key` string.
1797/// - `&str` - DOM physical `KeyboardEvent.code` string.
1798/// - `Modifiers` - Active Shift/Ctrl/Alt/Meta modifier flags from the DOM `KeyboardEvent`.
1799#[cfg(target_arch = "wasm32")]
1800fn web_queue_key_up(key: &str, code_str: &str, mods: Modifiers) {
1801    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1802        if let Ok(mut borrow) = slot.try_borrow_mut()
1803            && let Some((app, _)) = borrow.as_mut()
1804        {
1805            let wid: WindowId = app.get_window_state().get_id();
1806            let code: KeyCode = web_map_key(key, code_str);
1807            app.dispatch_window_event(WindowEvent::KeyUp(wid, KeyEvent::new(code, mods, false)));
1808        }
1809    });
1810}
1811
1812/// Reads the browser's live CSS viewport `(width, height)` preferring `visualViewport` and `documentElement.clientWidth/Height` before `innerWidth/Height`.
1813///
1814/// # Arguments
1815///
1816/// - `&Window` - Active browser window.
1817///
1818/// # Returns
1819///
1820/// - `(f64, f64)` - Measured CSS viewport `(width, height)`.
1821#[cfg(target_arch = "wasm32")]
1822fn web_read_window_css_viewport(win: &Window) -> (f64, f64) {
1823    if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
1824        && !vv.is_null()
1825        && !vv.is_undefined()
1826    {
1827        let vw: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_WIDTH))
1828            .ok()
1829            .and_then(|v: JsValue| v.as_f64())
1830            .filter(|v: &f64| v.is_finite() && *v >= 64.0);
1831        let vh: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_HEIGHT))
1832            .ok()
1833            .and_then(|v: JsValue| v.as_f64())
1834            .filter(|v: &f64| v.is_finite() && *v >= 64.0);
1835        if let (Some(w), Some(h)) = (vw, vh) {
1836            return (w, h);
1837        }
1838    }
1839    if let Some(root) = win
1840        .document()
1841        .and_then(|doc: Document| doc.document_element())
1842    {
1843        let cw: f64 = f64::from(root.client_width());
1844        let ch: f64 = f64::from(root.client_height());
1845        if cw >= 64.0 && ch >= 64.0 {
1846            return (cw, ch);
1847        }
1848    }
1849    let w: f64 = win
1850        .inner_width()
1851        .ok()
1852        .and_then(|v: JsValue| v.as_f64())
1853        .filter(|w: &f64| w.is_finite() && *w >= 64.0)
1854        .unwrap_or(SHOWCASE_WINDOW_WIDTH as f64);
1855    let h: f64 = win
1856        .inner_height()
1857        .ok()
1858        .and_then(|v: JsValue| v.as_f64())
1859        .filter(|h: &f64| h.is_finite() && *h >= 64.0)
1860        .unwrap_or(SHOWCASE_WINDOW_HEIGHT as f64);
1861    (w, h)
1862}
1863
1864/// Queries browser `<canvas>` geometry and `devicePixelRatio` once before constructing `App` so Frame 1 renders directly at exact physical pixels.
1865///
1866/// # Returns
1867///
1868/// - `(f64, f64, f64, f64, f32)` - Measured `(left, top, css_width, css_height, dpr)`.
1869#[cfg(target_arch = "wasm32")]
1870fn web_query_initial_viewport() -> (f64, f64, f64, f64, f32) {
1871    let Some(win) = window() else {
1872        return (
1873            0.0,
1874            0.0,
1875            SHOWCASE_WINDOW_WIDTH as f64,
1876            SHOWCASE_WINDOW_HEIGHT as f64,
1877            1.0,
1878        );
1879    };
1880    let dpr_raw: f64 = win.device_pixel_ratio();
1881    let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
1882        dpr_raw.clamp(1.0, 4.5) as f32
1883    } else {
1884        1.0
1885    };
1886    let mut left: f64 = 0.0;
1887    let mut top: f64 = 0.0;
1888    let mut css_w: f64 = 0.0;
1889    let mut css_h: f64 = 0.0;
1890    if let Some(doc) = win.document()
1891        && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
1892        && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
1893    {
1894        let rect: DomRect = canvas.get_bounding_client_rect();
1895        left = rect.left();
1896        top = rect.top();
1897        css_w = rect.width();
1898        css_h = rect.height();
1899    }
1900    let (win_w, win_h): (f64, f64) = web_read_window_css_viewport(&win);
1901    if !css_w.is_finite() || css_w < 64.0 {
1902        css_w = win_w;
1903    }
1904    if !css_h.is_finite() || css_h < 64.0 {
1905        css_h = win_h;
1906    }
1907    (left, top, css_w, css_h, dpr)
1908}
1909
1910/// Refreshes `WEB_CACHED_VIEWPORT` from DOM resize or DPR change events and marks the viewport dirty when metrics change.
1911///
1912/// # Arguments
1913///
1914/// - `&Window` - Browser window object.
1915/// - `&HtmlCanvasElement` - Target full-viewport canvas element.
1916///
1917/// # Returns
1918///
1919/// - `bool` - `true` when cached position, logical CSS dimensions, or DPR changed.
1920#[cfg(target_arch = "wasm32")]
1921fn web_refresh_cached_viewport(win: &Window, canvas: &HtmlCanvasElement) -> bool {
1922    let rect: DomRect = canvas.get_bounding_client_rect();
1923    let left: f64 = rect.left();
1924    let top: f64 = rect.top();
1925    let (win_w, win_h): (f64, f64) = web_read_window_css_viewport(win);
1926    let css_w: f64 = if rect.width().is_finite() && rect.width() >= 64.0 {
1927        rect.width()
1928    } else {
1929        win_w
1930    };
1931    let css_h: f64 = if rect.height().is_finite() && rect.height() >= 64.0 {
1932        rect.height()
1933    } else {
1934        win_h
1935    };
1936    let dpr_raw: f64 = win.device_pixel_ratio();
1937    let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
1938        dpr_raw.clamp(1.0, 4.5) as f32
1939    } else {
1940        1.0
1941    };
1942    let prev: (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1943    let changed: bool = (prev.0 - left).abs() > 0.25
1944        || (prev.1 - top).abs() > 0.25
1945        || (prev.2 - css_w).abs() > 0.25
1946        || (prev.3 - css_h).abs() > 0.25
1947        || (prev.4 - dpr).abs() > 0.005;
1948    if changed {
1949        WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
1950            cell.set((left, top, css_w, css_h, dpr));
1951        });
1952        WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(true));
1953    }
1954    changed
1955}
1956
1957/// Applies the cached `(css_w, css_h, dpr)` metrics in `WEB_CACHED_VIEWPORT` to the `<canvas>` backing store and `App`.
1958///
1959/// # Arguments
1960///
1961/// - `&HtmlCanvasElement` - Target full-viewport canvas element.
1962///
1963/// # Returns
1964///
1965/// - `bool` - `true` when physical dimensions or DPI scale changed and the viewport was updated.
1966#[cfg(target_arch = "wasm32")]
1967fn web_apply_cached_viewport(canvas: &HtmlCanvasElement) -> bool {
1968    let (_, _, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1969    let dpr_f64: f64 = f64::from(dpr);
1970    let phys_w: u32 = (css_w * dpr_f64).round().max(1.0) as u32;
1971    let phys_h: u32 = (css_h * dpr_f64).round().max(1.0) as u32;
1972    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1973        let Ok(mut borrow) = slot.try_borrow_mut() else {
1974            return false;
1975        };
1976        let Some((app, _)) = borrow.as_mut() else {
1977            return false;
1978        };
1979        let ws: WindowState = app.get_window_state();
1980        let size_diff: bool = ws.get_physical_width() != phys_w
1981            || ws.get_physical_height() != phys_h
1982            || (ws.get_scale_factor() - dpr).abs() > 0.005
1983            || canvas.width() != phys_w
1984            || canvas.height() != phys_h;
1985        if !size_diff {
1986            return false;
1987        }
1988        if canvas.width() != phys_w {
1989            canvas.set_width(phys_w);
1990        }
1991        if canvas.height() != phys_h {
1992            canvas.set_height(phys_h);
1993        }
1994        app.set_exact_physical_viewport(phys_w, phys_h, dpr);
1995        true
1996    })
1997}
1998
1999/// Re-queries browser CSS `env(safe-area-inset-*)` values and dispatches `WindowEvent::SafeAreaChanged` when changed.
2000///
2001/// # Returns
2002///
2003/// - `bool` - `true` when effective safe-area insets changed and require a relayout frame.
2004#[cfg(target_arch = "wasm32")]
2005fn web_sync_safe_area() -> bool {
2006    let measured: SafeAreaInsets = web_query_safe_area_insets();
2007    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2008        let Ok(mut borrow) = slot.try_borrow_mut() else {
2009            return false;
2010        };
2011        let Some((app, _)) = borrow.as_mut() else {
2012            return false;
2013        };
2014        let effective: SafeAreaInsets = if app.is_immersive_fullscreen() {
2015            SafeAreaInsets::default()
2016        } else {
2017            measured
2018        };
2019        let current: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
2020        if current == effective {
2021            return false;
2022        }
2023        let wid: WindowId = app.get_window_state().get_id();
2024        app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective));
2025        true
2026    })
2027}
2028
2029/// Reports measured browser `requestAnimationFrame` refresh cadence into the active `App` runtime.
2030///
2031/// # Arguments
2032///
2033/// - `f32` - Measured browser presentation cadence in Hertz.
2034#[cfg(target_arch = "wasm32")]
2035fn web_report_host_refresh_rate(measured_hz: f32) {
2036    let mut needs_redraw: bool = false;
2037    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2038        if let Ok(mut borrow) = slot.try_borrow_mut()
2039            && let Some((app, _)) = borrow.as_mut()
2040        {
2041            let prev_fps: f32 = app.get_context().get_live_fps().get_untracked();
2042            app.report_host_refresh_rate(measured_hz);
2043            let next_fps: f32 = app.get_context().get_live_fps().get_untracked();
2044            if (next_fps - prev_fps).abs() >= 1.0 {
2045                needs_redraw = true;
2046            }
2047        }
2048    });
2049    if needs_redraw {
2050        web_mark_needs_frame();
2051    }
2052}
2053
2054/// Steps one coalesced WebAssembly frame during `requestAnimationFrame` with accurate real-time `dt_secs`.
2055///
2056/// # Arguments
2057///
2058/// - `f32` - Elapsed seconds since the previous animation frame.
2059///
2060/// # Returns
2061///
2062/// - `u64` - Rendered frame hash.
2063#[cfg(target_arch = "wasm32")]
2064fn web_flush_frame(dt_secs: f32) -> u64 {
2065    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2066        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2067            Ok(guard) => guard,
2068            Err(_) => return 0,
2069        };
2070        let Some((app, _)) = borrow.as_mut() else {
2071            return 0;
2072        };
2073        let hash: u64 = app
2074            .step_game_frame(dt_secs)
2075            .map(|stats: FrameStats| stats.get_frame_hash())
2076            .unwrap_or(0);
2077        let pump: bool = app.should_pump_frames();
2078        WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
2079        hash
2080    })
2081}
2082
2083/// Initializes the persistent WebAssembly showcase on the browser `<canvas>` and renders the first frame.
2084///
2085/// # Returns
2086///
2087/// - `u64` - Deterministic frame hash produced by the initial render, or `0` on startup failure.
2088#[cfg(target_arch = "wasm32")]
2089#[wasm_bindgen]
2090pub fn euv_example_web_start() -> u64 {
2091    reset_reactive_runtime();
2092    register_frame_wakeup(web_mark_needs_frame);
2093    let (left, top, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = web_query_initial_viewport();
2094    WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2095        cell.set((left, top, css_w, css_h, dpr));
2096    });
2097    WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
2098    let logical_w: u32 = css_w.round().max(64.0) as u32;
2099    let logical_h: u32 = css_h.round().max(64.0) as u32;
2100    let phys_w: u32 = (css_w * f64::from(dpr)).round().max(1.0) as u32;
2101    let phys_h: u32 = (css_h * f64::from(dpr)).round().max(1.0) as u32;
2102    if let Some(win) = window()
2103        && let Some(doc) = win.document()
2104        && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2105        && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2106    {
2107        if canvas.width() != phys_w {
2108            canvas.set_width(phys_w);
2109        }
2110        if canvas.height() != phys_h {
2111            canvas.set_height(phys_h);
2112        }
2113    }
2114    match create_showcase_app_with_viewport(false, RenderMode::Auto, logical_w, logical_h, dpr) {
2115        Ok((mut app, state)) => {
2116            app.set_exact_physical_viewport(phys_w, phys_h, dpr);
2117            if let Some(win) = window()
2118                && let Ok(hash_str) = win.location().hash()
2119            {
2120                let initial: String =
2121                    resolve_web_hash_route(&hash_str, Some(state.get_dynamic_hub()));
2122                let _: bool = state.get_route().set_if_changed(initial);
2123            }
2124            let route_watch: Signal<String> = state.get_route();
2125            let hub_watch: DynamicUpdateHub = state.get_dynamic_hub().clone();
2126            let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
2127                Effect::new(move || {
2128                    let r: String = route_watch.get();
2129                    if WEB_SYNCING_FROM_HISTORY.with(Cell::get) {
2130                        return;
2131                    }
2132                    if let Some(win) = window() {
2133                        let cur_raw: String = win.location().hash().unwrap_or_default();
2134                        let cur_norm: String = resolve_web_hash_route(&cur_raw, Some(&hub_watch));
2135                        if cur_norm != r {
2136                            let target_hash: String = format!("#{r}");
2137                            let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
2138                        }
2139                    }
2140                })
2141            });
2142            let root_id: NodeId = app
2143                .get_scene()
2144                .with_read(SceneTree::get_root, NodeId::default());
2145            app.get_scene().with_write(
2146                |tree: &mut SceneTree| {
2147                    tree.attach_scope(root_id, hash_scope);
2148                },
2149                (),
2150            );
2151            let hash: u64 = app
2152                .step_frame()
2153                .map(|stats: FrameStats| stats.get_frame_hash())
2154                .unwrap_or(0);
2155            let pump: bool = app.should_pump_frames();
2156            WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
2157            WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2158                if let Ok(mut borrow) = slot.try_borrow_mut() {
2159                    *borrow = Some((app, state));
2160                }
2161            });
2162            hash
2163        }
2164        Err(_) => 0,
2165    }
2166}
2167
2168/// Switches the active route in the persistent WebAssembly showcase and renders immediately.
2169///
2170/// # Arguments
2171///
2172/// - `&str` - Route path to navigate to.
2173///
2174/// # Returns
2175///
2176/// - `u64` - Deterministic frame hash after route navigation.
2177#[cfg(target_arch = "wasm32")]
2178#[wasm_bindgen]
2179pub fn euv_example_render_route(route: &str) -> u64 {
2180    let has_runtime: bool = WEB_SHOWCASE_RUNTIME.with(
2181        |slot: &RefCell<Option<(App, ShowcaseState)>>| matches!(slot.try_borrow(), Ok(guard) if guard.is_some()),
2182    );
2183    if !has_runtime {
2184        let _: u64 = euv_example_web_start();
2185    }
2186    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2187        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2188            Ok(guard) => guard,
2189            Err(_) => return 0,
2190        };
2191        let Some((app, state)) = borrow.as_mut() else {
2192            return 0;
2193        };
2194        let _: bool = state.get_route().set_if_changed(route.to_string());
2195        app.step_frame()
2196            .map(|stats: FrameStats| stats.get_frame_hash())
2197            .unwrap_or(0)
2198    })
2199}
2200
2201/// Dispatches a browser pointer move event into the persistent WebAssembly showcase and re-renders.
2202///
2203/// # Arguments
2204///
2205/// - `f32` - Logical X coordinate inside the canvas.
2206/// - `f32` - Logical Y coordinate inside the canvas.
2207///
2208/// # Returns
2209///
2210/// - `u64` - Rendered frame hash.
2211#[cfg(target_arch = "wasm32")]
2212#[wasm_bindgen]
2213pub fn euv_web_pointer_move(x: f32, y: f32) -> u64 {
2214    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2215        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2216            Ok(guard) => guard,
2217            Err(_) => return 0,
2218        };
2219        let Some((app, _)) = borrow.as_mut() else {
2220            return 0;
2221        };
2222        let wid: WindowId = app.get_window_state().get_id();
2223        app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
2224        app.step_frame()
2225            .map(|stats: FrameStats| stats.get_frame_hash())
2226            .unwrap_or(0)
2227    })
2228}
2229
2230/// Dispatches a browser pointer press event into the persistent WebAssembly showcase and re-renders.
2231///
2232/// # Arguments
2233///
2234/// - `f32` - Logical X coordinate inside the canvas.
2235/// - `f32` - Logical Y coordinate inside the canvas.
2236///
2237/// # Returns
2238///
2239/// - `u64` - Rendered frame hash.
2240#[cfg(target_arch = "wasm32")]
2241#[wasm_bindgen]
2242pub fn euv_web_pointer_down(x: f32, y: f32) -> u64 {
2243    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2244        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2245            Ok(guard) => guard,
2246            Err(_) => return 0,
2247        };
2248        let Some((app, _)) = borrow.as_mut() else {
2249            return 0;
2250        };
2251        let wid: WindowId = app.get_window_state().get_id();
2252        app.dispatch_window_event(WindowEvent::PointerDown(wid, PointerEvent::mouse(x, y)));
2253        app.step_frame()
2254            .map(|stats: FrameStats| stats.get_frame_hash())
2255            .unwrap_or(0)
2256    })
2257}
2258
2259/// Dispatches a browser pointer release (and click) event into the persistent WebAssembly showcase and re-renders.
2260///
2261/// # Arguments
2262///
2263/// - `f32` - Logical X coordinate inside the canvas.
2264/// - `f32` - Logical Y coordinate inside the canvas.
2265///
2266/// # Returns
2267///
2268/// - `u64` - Rendered frame hash.
2269#[cfg(target_arch = "wasm32")]
2270#[wasm_bindgen]
2271pub fn euv_web_pointer_up(x: f32, y: f32) -> u64 {
2272    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2273        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2274            Ok(guard) => guard,
2275            Err(_) => return 0,
2276        };
2277        let Some((app, _)) = borrow.as_mut() else {
2278            return 0;
2279        };
2280        let wid: WindowId = app.get_window_state().get_id();
2281        app.dispatch_window_event(WindowEvent::PointerUp(wid, PointerEvent::mouse(x, y)));
2282        app.step_frame()
2283            .map(|stats: FrameStats| stats.get_frame_hash())
2284            .unwrap_or(0)
2285    })
2286}
2287
2288/// Dispatches a browser wheel scroll delta into the persistent WebAssembly showcase and re-renders.
2289///
2290/// # Arguments
2291///
2292/// - `f32` - Horizontal scroll delta.
2293/// - `f32` - Vertical scroll delta.
2294///
2295/// # Returns
2296///
2297/// - `u64` - Rendered frame hash.
2298#[cfg(target_arch = "wasm32")]
2299#[wasm_bindgen]
2300pub fn euv_web_scroll(dx: f32, dy: f32) -> u64 {
2301    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2302        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2303            Ok(guard) => guard,
2304            Err(_) => return 0,
2305        };
2306        let Some((app, _)) = borrow.as_mut() else {
2307            return 0;
2308        };
2309        let wid: WindowId = app.get_window_state().get_id();
2310        app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
2311        app.step_frame()
2312            .map(|stats: FrameStats| stats.get_frame_hash())
2313            .unwrap_or(0)
2314    })
2315}
2316
2317/// Dispatches a browser keyboard press and optional text input into the persistent WebAssembly showcase.
2318///
2319/// # Arguments
2320///
2321/// - `&str` - DOM `KeyboardEvent.key` string (e.g. `"Backspace"`, `"ArrowRight"`, `"a"`).
2322///
2323/// # Returns
2324///
2325/// - `u64` - Rendered frame hash.
2326#[cfg(target_arch = "wasm32")]
2327#[wasm_bindgen]
2328pub fn euv_web_key_down(key: &str) -> u64 {
2329    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2330        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2331            Ok(guard) => guard,
2332            Err(_) => return 0,
2333        };
2334        let Some((app, state)) = borrow.as_mut() else {
2335            return 0;
2336        };
2337        let wid: WindowId = app.get_window_state().get_id();
2338        let code: KeyCode = match key {
2339            WEB_KEY_ENTER => KeyCode::Enter,
2340            WEB_KEY_BACKSPACE => KeyCode::Backspace,
2341            WEB_KEY_DELETE => KeyCode::Delete,
2342            WEB_KEY_ESCAPE => KeyCode::Escape,
2343            WEB_KEY_TAB => KeyCode::Tab,
2344            WEB_KEY_SPACE => KeyCode::Space,
2345            WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
2346            WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
2347            WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
2348            WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
2349            other => other
2350                .chars()
2351                .next()
2352                .map(KeyCode::Character)
2353                .unwrap_or(KeyCode::Unknown),
2354        };
2355        let key_ev: WindowEvent =
2356            WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
2357        state.get_game_host().ingest_event(&key_ev);
2358        app.dispatch_window_event(key_ev);
2359        if key.chars().count() == 1 {
2360            app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
2361        }
2362        app.step_frame()
2363            .map(|stats: FrameStats| stats.get_frame_hash())
2364            .unwrap_or(0)
2365    })
2366}
2367
2368/// Advances the game physics clock by `dt_secs` when viewing the Game Engine route and renders a frame.
2369///
2370/// # Arguments
2371///
2372/// - `f32` - Elapsed seconds since the previous animation frame.
2373///
2374/// # Returns
2375///
2376/// - `u64` - Rendered frame hash.
2377#[cfg(target_arch = "wasm32")]
2378#[wasm_bindgen]
2379pub fn euv_web_tick(dt_secs: f32) -> u64 {
2380    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2381        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2382            Ok(guard) => guard,
2383            Err(_) => return 0,
2384        };
2385        let Some((app, state)) = borrow.as_mut() else {
2386            return 0;
2387        };
2388        if !app.should_pump_frames() {
2389            return app.get_renderer().get_last_stats().get_frame_hash();
2390        }
2391        let cur_route: String = state.get_route().get_untracked();
2392        let on_game: bool =
2393            cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D || cur_route == ROUTE_WATER;
2394        if on_game || app.has_active_animations() {
2395            return app
2396                .step_game_frame(dt_secs)
2397                .map(|stats: FrameStats| stats.get_frame_hash())
2398                .unwrap_or(0);
2399        }
2400        app.get_renderer().get_last_stats().get_frame_hash()
2401    })
2402}
2403
2404/// Resizes the persistent WebAssembly showcase canvas and viewport immediately and re-renders.
2405///
2406/// # Arguments
2407///
2408/// - `u32` - New logical viewport width in CSS pixels.
2409/// - `u32` - New logical viewport height in CSS pixels.
2410/// - `f32` - Active browser `window.devicePixelRatio`.
2411///
2412/// # Returns
2413///
2414/// - `u64` - Deterministic frame hash produced by the resized render.
2415#[cfg(target_arch = "wasm32")]
2416#[wasm_bindgen]
2417pub fn euv_web_resize(width: u32, height: u32, dpr: f32) -> u64 {
2418    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2419        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2420            Ok(guard) => guard,
2421            Err(_) => return 0,
2422        };
2423        let Some((app, _)) = borrow.as_mut() else {
2424            return 0;
2425        };
2426        let w: u32 = width.max(64);
2427        let h: u32 = height.max(64);
2428        let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
2429            dpr.clamp(1.0, 4.5)
2430        } else {
2431            1.0
2432        };
2433        let phys_w: u32 = ((w as f64) * (scale as f64)).round().max(1.0) as u32;
2434        let phys_h: u32 = ((h as f64) * (scale as f64)).round().max(1.0) as u32;
2435        let (prev_l, prev_t, _, _, _): (f64, f64, f64, f64, f32) =
2436            WEB_CACHED_VIEWPORT.with(Cell::get);
2437        WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2438            cell.set((prev_l, prev_t, f64::from(w), f64::from(h), scale));
2439        });
2440        WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
2441        if let Some(win) = window()
2442            && let Some(doc) = win.document()
2443            && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2444            && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2445        {
2446            if canvas.width() != phys_w {
2447                canvas.set_width(phys_w);
2448            }
2449            if canvas.height() != phys_h {
2450                canvas.set_height(phys_h);
2451            }
2452        }
2453        app.set_exact_physical_viewport(phys_w, phys_h, scale);
2454        app.step_frame()
2455            .map(|stats: FrameStats| stats.get_frame_hash())
2456            .unwrap_or(0)
2457    })
2458}
2459
2460/// Executes an AI Schema v1 JSON query against the live WebAssembly showcase in dev builds only (stripped in release).
2461///
2462/// # Arguments
2463///
2464/// - `&str` - Serialized `AiSchemaRequest` JSON string.
2465///
2466/// # Returns
2467///
2468/// - `String` - Serialized `AiSchemaResponse` JSON string.
2469#[cfg(all(debug_assertions, target_arch = "wasm32"))]
2470#[wasm_bindgen]
2471pub fn euv_dev_ai_schema(request_json: &str) -> String {
2472    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2473        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2474            Ok(guard) => guard,
2475            Err(_) => return String::new(),
2476        };
2477        let Some((app, state)) = borrow.as_mut() else {
2478            return String::new();
2479        };
2480        let hooks: AiAppHooks = state.build_ai_hooks();
2481        AiSchemaProtocol::handle_json_with_hooks(app, request_json, Some(&hooks))
2482    })
2483}
2484
2485/// Returns the active route string of the persistent WebAssembly showcase for telemetry.
2486///
2487/// # Returns
2488///
2489/// - `String` - Current active route path.
2490#[cfg(target_arch = "wasm32")]
2491#[wasm_bindgen]
2492pub fn euv_web_current_route() -> String {
2493    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2494        match slot.try_borrow() {
2495            Ok(guard) => guard
2496                .as_ref()
2497                .map(|(_, state): &(App, ShowcaseState)| state.get_route().get_untracked())
2498                .unwrap_or_default(),
2499            Err(_) => String::new(),
2500        }
2501    })
2502}