euv-core 0.47.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
use super::*;

/// Queries browser dark-mode preference using `window.matchMedia("(prefers-color-scheme: dark)")`.
///
/// # Returns
///
/// - `ThemeMode` - Detected browser appearance mode.
#[must_use]
pub fn web_system_theme() -> ThemeMode {
    let Some(win) = window() else {
        return ThemeMode::Light;
    };
    let matches_dark: bool = win
        .match_media(WEB_DARK_MEDIA_QUERY)
        .ok()
        .flatten()
        .map(|mql: MediaQueryList| mql.matches())
        .unwrap_or(false);
    if matches_dark {
        ThemeMode::Dark
    } else {
        ThemeMode::Light
    }
}

/// Queries the browser's `window.devicePixelRatio`, clamped to `[1.0, 4.5]` so mobile/web canvases never downscale below 1x physical pixels.
///
/// # Returns
///
/// - `f32` - Device pixel ratio clamped to `[1.0, 4.5]`.
#[must_use]
pub fn web_device_pixel_ratio() -> f32 {
    window()
        .map(|w: Window| {
            let raw: f64 = w.device_pixel_ratio();
            if raw.is_finite() && raw > 0.0 {
                (raw as f32).clamp(1.0, 4.5)
            } else {
                1.0
            }
        })
        .unwrap_or(1.0)
}

/// Opens an external HTTP(S) URL in a new browser tab with `noopener,noreferrer`.
///
/// # Arguments
///
/// - `&str` - Validated `http://` or `https://` URL string.
///
/// # Returns
///
/// - `bool` - `true` when `window.open` succeeded without error.
#[must_use]
pub(crate) fn web_open_external_url(url: &str) -> bool {
    let Some(win) = window() else {
        return false;
    };
    win.open_with_url_and_target_and_features(url, WEB_OPEN_TARGET_BLANK, WEB_OPEN_FEATURES_SAFE)
        .is_ok()
}

/// Queries the browser's live CSS viewport `(width, height)` preferring `visualViewport` and `documentElement.clientWidth/Height` before `innerWidth/Height`.
///
/// # Arguments
///
/// - `&Window` - Active browser window.
/// - `&Document` - Active browser document.
/// - `f64` - Fallback logical width.
/// - `f64` - Fallback logical height.
///
/// # Returns
///
/// - `(f64, f64)` - Live CSS viewport `(width, height)` in CSS pixels.
#[must_use]
fn web_query_viewport_css_size(
    win: &Window,
    doc: &Document,
    fallback_w: f64,
    fallback_h: f64,
) -> (f64, f64) {
    if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
        && !vv.is_null()
        && !vv.is_undefined()
    {
        let vw: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_WIDTH))
            .ok()
            .and_then(|v: JsValue| v.as_f64())
            .filter(|v: &f64| v.is_finite() && *v >= 64.0);
        let vh: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_HEIGHT))
            .ok()
            .and_then(|v: JsValue| v.as_f64())
            .filter(|v: &f64| v.is_finite() && *v >= 64.0);
        if let (Some(w), Some(h)) = (vw, vh) {
            return (w, h);
        }
    }
    if let Some(root) = doc.document_element() {
        let cw: f64 = f64::from(root.client_width());
        let ch: f64 = f64::from(root.client_height());
        if cw >= 64.0 && ch >= 64.0 {
            return (cw, ch);
        }
    }
    let w: f64 = win
        .inner_width()
        .ok()
        .and_then(|v: JsValue| v.as_f64())
        .filter(|v: &f64| v.is_finite() && *v >= 64.0)
        .unwrap_or(fallback_w.max(64.0));
    let h: f64 = win
        .inner_height()
        .ok()
        .and_then(|v: JsValue| v.as_f64())
        .filter(|v: &f64| v.is_finite() && *v >= 64.0)
        .unwrap_or(fallback_h.max(64.0));
    (w, h)
}

/// Writes `text` to the browser's `navigator.clipboard` API when available.
///
/// # Arguments
///
/// - `&str` - UTF-8 text string to copy.
///
/// # Returns
///
/// - `bool` - `true` when `navigator.clipboard.writeText` was dispatched.
pub(crate) fn web_write_clipboard(text: &str) -> bool {
    let Some(win) = window() else {
        return false;
    };
    let nav: Navigator = win.navigator();
    let clip: Clipboard = nav.clipboard();
    let _: Promise = clip.write_text(text);
    true
}

/// Queries whether the active browser tab is currently hidden (`document.hidden`).
///
/// # Returns
///
/// - `bool` - `true` when the page is in a background tab or minimized.
#[must_use]
pub(crate) fn web_document_hidden() -> bool {
    window()
        .and_then(|w: Window| w.document())
        .map(|d: Document| d.hidden())
        .unwrap_or(false)
}

/// Queries live browser online connectivity via `navigator.onLine`.
///
/// # Returns
///
/// - `bool` - `true` when the browser reports network availability.
#[must_use]
pub(crate) fn web_navigator_online() -> bool {
    window()
        .map(|w: Window| w.navigator().on_line())
        .unwrap_or(true)
}

/// Queries the browser's primary BCP-47 locale tag via `navigator.language`.
///
/// # Returns
///
/// - `String` - Locale identifier (fallback `"en-US"`).
#[must_use]
pub(crate) fn web_navigator_locale() -> String {
    window()
        .and_then(|w: Window| w.navigator().language())
        .filter(|s: &String| !s.trim().is_empty())
        .unwrap_or_else(|| DEFAULT_SYSTEM_LOCALE.to_string())
}

/// Parses a single CSS custom property value (e.g. `"44px"`) from a `CSSStyleDeclaration` without forcing layout.
///
/// # Arguments
///
/// - `&JsValue` - `CSSStyleDeclaration` returned by `window.getComputedStyle(root)`.
/// - `&Function` - Bound `getPropertyValue` method.
/// - `&str` - CSS custom property name (`--euv-safe-*`).
///
/// # Returns
///
/// - `f32` - Sanitized non-negative inset in logical CSS pixels.
#[must_use]
fn web_read_css_px_prop(style_decl: &JsValue, get_prop_fn: &Function, prop_name: &str) -> f32 {
    let Ok(raw_val) = get_prop_fn.call1(style_decl, &JsValue::from_str(prop_name)) else {
        return 0.0;
    };
    let Some(text) = raw_val.as_string() else {
        return 0.0;
    };
    let trimmed: &str = text.trim();
    let numeric: &str = trimmed
        .strip_suffix(WEB_CSS_PX_SUFFIX)
        .unwrap_or(trimmed)
        .trim();
    let parsed: f32 = numeric.parse::<f32>().unwrap_or(0.0);
    if parsed.is_finite() && parsed > 0.0 {
        parsed
    } else {
        0.0
    }
}

/// Reads browser CSS `env(safe-area-inset-*)` values via `:root` custom properties (`--euv-safe-*`) with zero DOM creation and zero forced startup reflows.
///
/// # Returns
///
/// - `SafeAreaInsets` - Sanitized browser safe-area insets (`0.0` when unsupported or non-notched).
#[must_use]
pub fn web_query_safe_area_insets() -> SafeAreaInsets {
    let Some(win) = window() else {
        return SafeAreaInsets::default();
    };
    let Some(root): Option<Element> = win.document().and_then(|d: Document| d.document_element())
    else {
        return SafeAreaInsets::default();
    };
    let Ok(get_style_val) = Reflect::get(
        win.as_ref(),
        &JsValue::from_str(WEB_METHOD_GET_COMPUTED_STYLE),
    ) else {
        return SafeAreaInsets::default();
    };
    let Ok(get_style_fn) = get_style_val.dyn_into::<Function>() else {
        return SafeAreaInsets::default();
    };
    let Ok(style_decl) = get_style_fn.call1(win.as_ref(), root.as_ref()) else {
        return SafeAreaInsets::default();
    };
    let Ok(get_prop_val) = Reflect::get(
        &style_decl,
        &JsValue::from_str(WEB_METHOD_GET_PROPERTY_VALUE),
    ) else {
        return SafeAreaInsets::default();
    };
    let Ok(get_prop_fn) = get_prop_val.dyn_into::<Function>() else {
        return SafeAreaInsets::default();
    };
    let top: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_TOP);
    let right: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_RIGHT);
    let bottom: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_BOTTOM);
    let left: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_LEFT);
    SafeAreaInsets::new(top, right, bottom, left)
}

/// Checks whether the browser exposes `navigator.gpu` for WebGPU hardware acceleration.
///
/// # Returns
///
/// - `bool` - `true` when `navigator.gpu` is present and non-null.
#[must_use]
pub fn web_has_webgpu() -> bool {
    let Some(win) = window() else {
        return false;
    };
    let nav: Navigator = win.navigator();
    Reflect::get(nav.as_ref(), &JsValue::from_str(WEB_PROP_GPU))
        .map(|val: JsValue| !val.is_undefined() && !val.is_null())
        .unwrap_or(false)
}

/// Attaches a browser `ResizeObserver` to `canvas` invoking `callback` on layout box changes without polling reflows.
///
/// # Arguments
///
/// - `&HtmlCanvasElement` - Target DOM canvas element.
/// - `&Function` - JavaScript callback invoked when `canvas` resizes.
///
/// # Returns
///
/// - `Option<Object>` - Live `ResizeObserver` instance if supported by the browser.
#[must_use]
pub fn web_attach_resize_observer(
    canvas: &HtmlCanvasElement,
    callback: &Function,
) -> Option<Object> {
    let win: Window = window()?;
    let ctor_val: JsValue =
        Reflect::get(win.as_ref(), &JsValue::from_str(WEB_CTOR_RESIZE_OBSERVER)).ok()?;
    let ctor_fn: Function = ctor_val.dyn_into::<Function>().ok()?;
    let args_obj: Object = Object::new();
    let _: bool = Reflect::set(
        args_obj.as_ref(),
        &JsValue::from_str(WEB_REFLECT_ARG0_KEY),
        callback.as_ref(),
    )
    .ok()?;
    let ro_val: JsValue = Reflect::construct(&ctor_fn, &Object::values(&args_obj)).ok()?;
    let observe_val: JsValue =
        Reflect::get(&ro_val, &JsValue::from_str(WEB_METHOD_OBSERVE)).ok()?;
    let observe_fn: Function = observe_val.dyn_into::<Function>().ok()?;
    let _: JsValue = observe_fn.call1(&ro_val, canvas.as_ref()).ok()?;
    ro_val.dyn_into::<Object>().ok()
}

/// Disconnects a live browser `ResizeObserver` cleanly on window teardown.
///
/// # Arguments
///
/// - `&Object` - Active `ResizeObserver` instance.
pub fn web_disconnect_resize_observer(observer: &Object) {
    if let Ok(disc_val) = Reflect::get(observer.as_ref(), &JsValue::from_str(WEB_METHOD_DISCONNECT))
        && let Ok(disc_fn) = disc_val.dyn_into::<Function>()
    {
        drop(disc_fn.call0(observer.as_ref()));
    }
}

/// Builds the WebGL2 context options dictionary (`alpha: false`, `desynchronized: false`, `preserveDrawingBuffer: false`, `powerPreference: "high-performance"`).
///
/// Keeps `desynchronized: false` to prevent tile tearing and blocky mosaic artifacts on mobile Safari and Android Chrome.
///
/// # Returns
///
/// - `Object` - Populated JS options object for `getContext("webgl2", opts)`.
#[must_use]
fn web_gl2_context_options() -> Object {
    let opts: Object = Object::new();
    let _: Result<bool, JsValue> = Reflect::set(
        opts.as_ref(),
        &JsValue::from_str(WEB_GL_OPT_ALPHA),
        &JsValue::from_bool(false),
    );
    let _: Result<bool, JsValue> = Reflect::set(
        opts.as_ref(),
        &JsValue::from_str(WEB_GL_OPT_ANTIALIAS),
        &JsValue::from_bool(false),
    );
    let _: Result<bool, JsValue> = Reflect::set(
        opts.as_ref(),
        &JsValue::from_str(WEB_GL_OPT_DEPTH),
        &JsValue::from_bool(false),
    );
    let _: Result<bool, JsValue> = Reflect::set(
        opts.as_ref(),
        &JsValue::from_str(WEB_GL_OPT_DESYNCHRONIZED),
        &JsValue::from_bool(false),
    );
    let _: Result<bool, JsValue> = Reflect::set(
        opts.as_ref(),
        &JsValue::from_str(WEB_GL_OPT_POWER_PREF),
        &JsValue::from_str(WEB_GL_OPT_HIGH_PERFORMANCE),
    );
    let _: Result<bool, JsValue> = Reflect::set(
        opts.as_ref(),
        &JsValue::from_str(WEB_GL_OPT_PRESERVE_DRAWING),
        &JsValue::from_bool(false),
    );
    opts
}

/// Applies canonical RGBA8 WebGL2 pixel unpack state (`UNPACK_ALIGNMENT = 4`, no flip-Y, no premultiply, no colorspace conversion).
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
fn web_configure_gl2_unpack_state(gl: &WebGl2RenderingContext) {
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_ALIGNMENT, 4);
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_FLIP_Y_WEBGL, 0);
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
    gl.pixel_storei(
        WebGl2RenderingContext::UNPACK_COLORSPACE_CONVERSION_WEBGL,
        WebGl2RenderingContext::NONE as i32,
    );
}

/// Initializes a `highp` fullscreen triangle `WebGlProgram`, resident RGBA8 texture handle, and `u_view` uniform location on `gl`.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
///
/// # Returns
///
/// - `Option<WebGl2BlitPipeline>` - Compiled blit program, allocated WebGL2 texture object, and `u_view` uniform location.
fn web_init_gl2_blit_pipeline(gl: &WebGl2RenderingContext) -> Option<WebGl2BlitPipeline> {
    let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
    gl.shader_source(&vs, WEB_GL2_BLIT_VERT_SHADER);
    gl.compile_shader(&vs);
    let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
    gl.shader_source(&fs, WEB_GL2_BLIT_FRAG_SHADER);
    gl.compile_shader(&fs);
    let prog: WebGlProgram = gl.create_program()?;
    gl.attach_shader(&prog, &vs);
    gl.attach_shader(&prog, &fs);
    gl.link_program(&prog);
    gl.use_program(Some(&prog));
    if let Some(loc) = gl.get_uniform_location(&prog, WEB_GL2_UNIFORM_TEX) {
        gl.uniform1i(Some(&loc), 0);
    }
    let view_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&prog, WEB_GL2_UNIFORM_VIEW);
    web_configure_gl2_unpack_state(gl);
    let texture: Option<JsValue> =
        Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_CREATE_TEXTURE))
            .ok()
            .and_then(|v: JsValue| v.dyn_into::<Function>().ok())
            .and_then(|f: Function| f.call0(gl.as_ref()).ok())
            .filter(|t: &JsValue| !t.is_null() && !t.is_undefined());
    if let Some(tex) = texture.as_ref() {
        let target: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
        if let Ok(bind_val) = Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_BIND_TEXTURE))
            && let Ok(bind_fn) = bind_val.dyn_into::<Function>()
        {
            drop(bind_fn.call2(gl.as_ref(), &target, tex));
        }
        if let Ok(param_val) = Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_TEX_PARAMETERI))
            && let Ok(param_fn) = param_val.dyn_into::<Function>()
        {
            let linear: JsValue = JsValue::from_f64(WebGl2RenderingContext::LINEAR as f64);
            let clamp: JsValue = JsValue::from_f64(WebGl2RenderingContext::CLAMP_TO_EDGE as f64);
            drop(param_fn.call3(
                gl.as_ref(),
                &target,
                &JsValue::from_f64(WebGl2RenderingContext::TEXTURE_MIN_FILTER as f64),
                &linear,
            ));
            drop(param_fn.call3(
                gl.as_ref(),
                &target,
                &JsValue::from_f64(WebGl2RenderingContext::TEXTURE_MAG_FILTER as f64),
                &linear,
            ));
            drop(param_fn.call3(
                gl.as_ref(),
                &target,
                &JsValue::from_f64(WebGl2RenderingContext::TEXTURE_WRAP_S as f64),
                &clamp,
            ));
            drop(param_fn.call3(
                gl.as_ref(),
                &target,
                &JsValue::from_f64(WebGl2RenderingContext::TEXTURE_WRAP_T as f64),
                &clamp,
            ));
        }
    }
    Some(WebGl2BlitPipeline {
        program: prog,
        texture,
        view_loc,
    })
}

/// Invokes a zero-argument DOM method that may return a JS `Promise`, swallowing rejections so browser consoles stay clean.
///
/// # Arguments
///
/// - `&JsValue` - Target DOM receiver (`Element` or `Document`).
/// - `&str` - Method property name to invoke.
fn web_invoke_promise_method(target: &JsValue, method: &str) {
    let Ok(func_val) = Reflect::get(target, &JsValue::from_str(method)) else {
        return;
    };
    let Ok(func) = func_val.dyn_into::<Function>() else {
        return;
    };
    if let Ok(ret) = func.call0(target)
        && let Ok(promise) = ret.dyn_into::<Promise>()
    {
        WEB_PROMISE_NOOP_REJECT.with(|cb: &Closure<dyn FnMut(JsValue)>| {
            let _: Promise = promise.catch(cb);
        });
    }
}

/// Requests or exits browser Fullscreen API cleanly on `document.documentElement`.
///
/// # Arguments
///
/// - `bool` - `true` to enter fullscreen; `false` to exit fullscreen.
pub fn web_set_fullscreen(enabled: bool) {
    let Some(doc) = window().and_then(|w: Window| w.document()) else {
        return;
    };
    if enabled {
        if doc.fullscreen_element().is_none()
            && let Some(root) = doc.document_element()
        {
            web_invoke_promise_method(root.as_ref(), WEB_METHOD_REQUEST_FULLSCREEN);
        }
    } else if doc.fullscreen_element().is_some() {
        web_invoke_promise_method(doc.as_ref(), WEB_METHOD_EXIT_FULLSCREEN);
    }
}

/// Creates or reuses the mounted `HTMLCanvasElement`, preferring WebGPU / WebGL2 hardware contexts and locking `"2d"` only if GPU contexts fail or `RenderMode::Software` is explicitly requested.
///
/// # Arguments
///
/// - `&WindowConfig` - Declarative window configuration.
/// - `f32` - Browser device pixel ratio.
/// - `bool` - `true` when an existing DOM `<canvas>` may be reused to prevent duplicate stacked canvases.
///
/// # Returns
///
/// - `Result<WebCanvasSurface, PlatformError>` - Mounted canvas and active WebGPU, WebGL2, or 2D context.
pub(crate) fn web_create_canvas(
    config: &WindowConfig,
    dpr: f32,
    reuse_existing: bool,
) -> Result<WebCanvasSurface, PlatformError> {
    let win: Window = window()
        .ok_or_else(|| PlatformError::InitializationFailed(ERR_WEB_WINDOW_MISSING.to_string()))?;
    let doc: Document = win
        .document()
        .ok_or_else(|| PlatformError::InitializationFailed(ERR_WEB_WINDOW_MISSING.to_string()))?;
    doc.set_title(config.get_title());
    let mut existing_canvas: Option<HtmlCanvasElement> = None;
    if reuse_existing
        && let Ok(Some(found)) = doc.query_selector(WEB_CANVAS_TAG)
        && let Ok(existing) = found.dyn_into::<HtmlCanvasElement>()
    {
        existing_canvas = Some(existing);
    }
    let (canvas, needs_append): (HtmlCanvasElement, bool) = match existing_canvas {
        Some(existing) => (existing, false),
        None => {
            let el: Element = doc.create_element(WEB_CANVAS_TAG).map_err(|_: JsValue| {
                PlatformError::InitializationFailed(ERR_WEB_CANVAS_CREATE.to_string())
            })?;
            let created: HtmlCanvasElement =
                el.dyn_into::<HtmlCanvasElement>().map_err(|_: Element| {
                    PlatformError::InitializationFailed(ERR_WEB_CANVAS_CREATE.to_string())
                })?;
            (created, true)
        }
    };
    let (win_w, win_h): (f64, f64) = web_query_viewport_css_size(
        &win,
        &doc,
        config.get_width() as f64,
        config.get_height() as f64,
    );
    let safe_dpr: f64 = f64::from(dpr.clamp(1.0, 4.5));
    let phys_w: u32 = (win_w * safe_dpr).round().max(1.0) as u32;
    let phys_h: u32 = (win_h * safe_dpr).round().max(1.0) as u32;
    canvas.set_width(phys_w);
    canvas.set_height(phys_h);
    let css_style: String =
        format!("{WEB_CANVAS_STYLE_PREFIX}{WEB_CURSOR_POINTER}{WEB_CANVAS_STYLE_SUFFIX}");
    drop(canvas.set_attribute(WEB_ATTR_STYLE, &css_style));
    drop(canvas.set_attribute(WEB_ATTR_TABINDEX, WEB_ATTR_TABINDEX_ZERO));
    if let Some(body) = doc.body() {
        drop(body.set_attribute(WEB_ATTR_STYLE, WEB_BODY_STYLE));
        if needs_append {
            drop(body.append_child(&canvas));
        }
    }
    let render_mode: RenderMode = config.get_render().get_mode();
    if render_mode == RenderMode::Hardware
        && web_has_webgpu()
        && let Ok(Some(gpu_ctx)) = canvas.get_context(WEB_CONTEXT_WEBGPU)
    {
        return Ok(WebCanvasSurface {
            canvas,
            context_kind: WebCanvasContextKind::WebGpu,
            webgpu_ctx: Some(gpu_ctx),
            gl2: None,
            gl2_program: None,
            gl2_texture: None,
            gl2_view_loc: None,
            ctx2d: None,
        });
    }
    if render_mode != RenderMode::Software {
        let gl_opts: Object = web_gl2_context_options();
        if let Ok(Some(raw_gl)) =
            canvas.get_context_with_context_options(WEB_CONTEXT_WEBGL2, gl_opts.as_ref())
            && let Ok(gl2) = raw_gl.dyn_into::<WebGl2RenderingContext>()
        {
            let pipeline: Option<WebGl2BlitPipeline> = web_init_gl2_blit_pipeline(&gl2);
            let (gl2_program, gl2_texture, gl2_view_loc): (
                Option<WebGlProgram>,
                Option<JsValue>,
                Option<WebGlUniformLocation>,
            ) = match pipeline {
                Some(p) => (Some(p.program), p.texture, p.view_loc),
                None => (None, None, None),
            };
            return Ok(WebCanvasSurface {
                canvas,
                context_kind: WebCanvasContextKind::WebGl2,
                webgpu_ctx: None,
                gl2: Some(gl2),
                gl2_program,
                gl2_texture,
                gl2_view_loc,
                ctx2d: None,
            });
        }
    }
    let raw_ctx: Object = canvas
        .get_context(WEB_CONTEXT_2D)
        .map_err(|_: JsValue| PlatformError::SurfaceError(ERR_WEB_CTX2D_MISSING.to_string()))?
        .ok_or_else(|| PlatformError::SurfaceError(ERR_WEB_CTX2D_MISSING.to_string()))?;
    let ctx2d: CanvasRenderingContext2d = raw_ctx
        .dyn_into::<CanvasRenderingContext2d>()
        .map_err(|_: Object| PlatformError::SurfaceError(ERR_WEB_CTX2D_MISSING.to_string()))?;
    Ok(WebCanvasSurface {
        canvas,
        context_kind: WebCanvasContextKind::Canvas2d,
        webgpu_ctx: None,
        gl2: None,
        gl2_program: None,
        gl2_texture: None,
        gl2_view_loc: None,
        ctx2d: Some(ctx2d),
    })
}

/// Packs a partial dirty sub-rectangle of `framebuffer` into tightly contiguous RGBA8 bytes.
///
/// # Arguments
///
/// - `&Framebuffer` - Source RGBA8 framebuffer.
/// - `u32` - Inclusive left pixel coordinate.
/// - `u32` - Inclusive top pixel coordinate.
/// - `u32` - Sub-rectangle width in pixels.
/// - `u32` - Sub-rectangle height in pixels.
///
/// # Returns
///
/// - `Vec<u8>` - Tightly packed RGBA8 sub-rectangle pixels.
fn web_pack_rgba_subrect(
    framebuffer: &Framebuffer,
    x0: u32,
    y0: u32,
    width: u32,
    height: u32,
) -> Vec<u8> {
    let fb_w: usize = framebuffer.get_width() as usize;
    let src: &[u8] = framebuffer.get_pixels().as_slice();
    let row_bytes: usize = (width as usize) * 4;
    let mut out: Vec<u8> = Vec::with_capacity(row_bytes * (height as usize));
    for row in y0..(y0 + height) {
        let start: usize = ((row as usize) * fb_w + (x0 as usize)) * 4;
        let end: usize = start + row_bytes;
        if end <= src.len() {
            out.extend_from_slice(&src[start..end]);
        }
    }
    out
}

/// Uploads full or dirty sub-rectangle RGBA8 pixels directly from WASM linear memory (zero-copy `Uint8Array::view` + WebGL2 `UNPACK_ROW_LENGTH` / `UNPACK_SKIP_*`) and draws a bit-exact `highp` fullscreen triangle.
///
/// # Arguments
///
/// - `&mut WebWindowRecord` - Browser window record holding the WebGL2 context, program, resident texture, and canvas.
/// - `&Framebuffer` - Source RGBA8 framebuffer.
/// - `DamageRegion` - Damaged physical pixel region.
///
/// # Returns
///
/// - `Result<bool, PlatformError>` - `Ok(true)` when presented via WebGL2; `Ok(false)` when no WebGL2 pipeline is bound.
pub(crate) fn web_present_gl2_region(
    rec: &mut WebWindowRecord,
    framebuffer: &Framebuffer,
    damage: DamageRegion,
) -> Result<bool, PlatformError> {
    let WebWindowRecord {
        canvas,
        gl2,
        gl2_program,
        gl2_texture,
        gl2_view_loc,
        gl2_tex_width,
        gl2_tex_height,
        ..
    } = rec;
    let (Some(gl), Some(program), Some(texture)) =
        (gl2.as_ref(), gl2_program.as_ref(), gl2_texture.as_ref())
    else {
        return Ok(false);
    };
    let fb_w: u32 = framebuffer.get_width();
    let fb_h: u32 = framebuffer.get_height();
    if fb_w == 0 || fb_h == 0 {
        return Ok(true);
    }
    let pixels: &[u8] = framebuffer.get_pixels().as_slice();
    let required_bytes: usize = (fb_w as usize)
        .saturating_mul(fb_h as usize)
        .saturating_mul(4);
    if pixels.len() < required_bytes {
        return Err(PlatformError::SurfaceError(
            ERR_WEB_PRESENT_FAILED.to_string(),
        ));
    }
    let mut drawing_resized: bool =
        gl.drawing_buffer_width() != (fb_w as i32) || gl.drawing_buffer_height() != (fb_h as i32);
    if drawing_resized && let Some(el) = canvas.as_ref() {
        if el.width() != fb_w {
            el.set_width(fb_w);
        }
        if el.height() != fb_h {
            el.set_height(fb_h);
        }
        drawing_resized = true;
    }
    let tex_dims_changed: bool = *gl2_tex_width != fb_w || *gl2_tex_height != fb_h;
    let resolved_rect: Option<Rect> = damage.resolve(fb_w, fb_h);
    if resolved_rect.is_none() && !drawing_resized && !tex_dims_changed {
        return Ok(true);
    }
    let target_val: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
    if let Ok(active_val) = Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_ACTIVE_TEXTURE))
        && let Ok(active_fn) = active_val.dyn_into::<Function>()
    {
        drop(active_fn.call1(
            gl.as_ref(),
            &JsValue::from_f64(WebGl2RenderingContext::TEXTURE0 as f64),
        ));
    }
    if let Ok(bind_val) = Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_BIND_TEXTURE))
        && let Ok(bind_fn) = bind_val.dyn_into::<Function>()
    {
        drop(bind_fn.call2(gl.as_ref(), &target_val, texture));
    }
    web_configure_gl2_unpack_state(gl);
    let surface_dirty: bool = drawing_resized || tex_dims_changed;
    let needs_full_upload: bool = damage.get_full_damage() || surface_dirty;
    if needs_full_upload {
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
        // SAFETY: `pixels` stays valid and immovable in WASM linear memory for the synchronous WebGL2 upload call.
        let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
        gl.tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
            WebGl2RenderingContext::TEXTURE_2D,
            0,
            WebGl2RenderingContext::RGBA8 as i32,
            fb_w as i32,
            fb_h as i32,
            0,
            WebGl2RenderingContext::RGBA,
            WebGl2RenderingContext::UNSIGNED_BYTE,
            Some(view.as_ref()),
        )
        .map_err(|_: JsValue| PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string()))?;
        *gl2_tex_width = fb_w;
        *gl2_tex_height = fb_h;
    } else if let Some(rect) = resolved_rect {
        let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(fb_w);
        let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(fb_h);
        let x1: u32 = (rect.right().ceil().max(0.0) as u32).min(fb_w);
        let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).min(fb_h);
        if x1 > x0 && y1 > y0 {
            let rw: u32 = x1 - x0;
            let rh: u32 = y1 - y0;
            gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, fb_w as i32);
            gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, x0 as i32);
            gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, y0 as i32);
            // SAFETY: `pixels` stays valid and immovable in WASM linear memory for the synchronous WebGL2 upload call.
            let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
            let upload_res: Result<(), JsValue> = gl
                .tex_sub_image_2d_with_i32_and_i32_and_u32_and_type_and_opt_array_buffer_view(
                    WebGl2RenderingContext::TEXTURE_2D,
                    0,
                    x0 as i32,
                    y0 as i32,
                    rw as i32,
                    rh as i32,
                    WebGl2RenderingContext::RGBA,
                    WebGl2RenderingContext::UNSIGNED_BYTE,
                    Some(view.as_ref()),
                );
            gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
            gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
            gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
            upload_res.map_err(|_: JsValue| {
                PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
            })?;
        }
    }
    let draw_w: i32 = gl.drawing_buffer_width().max(1);
    let draw_h: i32 = gl.drawing_buffer_height().max(1);
    gl.viewport(0, 0, draw_w, draw_h);
    gl.use_program(Some(program));
    if let Some(loc) = gl2_view_loc.as_ref() {
        gl.uniform2f(Some(loc), draw_w as f32, draw_h as f32);
    }
    gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 3);
    Ok(true)
}

/// Blits only the damaged physical rectangle of an RGBA8 `Framebuffer` onto a browser `CanvasRenderingContext2d`.
///
/// # Arguments
///
/// - `&CanvasRenderingContext2d` - Browser 2D rendering context.
/// - `&Framebuffer` - Rendered RGBA8 framebuffer.
/// - `DamageRegion` - Damaged pixel region to copy into the canvas.
///
/// # Returns
///
/// - `Result<(), PlatformError>` - Presentation status.
pub(crate) fn web_present_image_data_region(
    ctx2d: &CanvasRenderingContext2d,
    framebuffer: &Framebuffer,
    damage: DamageRegion,
) -> Result<(), PlatformError> {
    let fb_w: u32 = framebuffer.get_width();
    let fb_h: u32 = framebuffer.get_height();
    let Some(rect) = damage.resolve(fb_w, fb_h) else {
        return Ok(());
    };
    if damage.get_full_damage() {
        let clamped: Clamped<&[u8]> = Clamped(framebuffer.get_pixels().as_slice());
        let img: ImageData = ImageData::new_with_u8_clamped_array_and_sh(clamped, fb_w, fb_h)
            .map_err(|_: JsValue| {
                PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
            })?;
        ctx2d
            .put_image_data(&img, 0.0, 0.0)
            .map_err(|_: JsValue| PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string()))
    } else {
        let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(fb_w);
        let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(fb_h);
        let x1: u32 = (rect.right().ceil().max(0.0) as u32).min(fb_w);
        let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).min(fb_h);
        if x1 <= x0 || y1 <= y0 {
            return Ok(());
        }
        let rw: u32 = x1 - x0;
        let rh: u32 = y1 - y0;
        let sub: Vec<u8> = web_pack_rgba_subrect(framebuffer, x0, y0, rw, rh);
        let clamped: Clamped<&[u8]> = Clamped(sub.as_slice());
        let img: ImageData = ImageData::new_with_u8_clamped_array_and_sh(clamped, rw, rh).map_err(
            |_: JsValue| PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string()),
        )?;
        ctx2d
            .put_image_data(&img, x0 as f64, y0 as f64)
            .map_err(|_: JsValue| PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string()))
    }
}

/// Reads an optional finite numeric property from a JS object via `Reflect::get`.
///
/// # Arguments
///
/// - `&JsValue` - Target JS object.
/// - `&str` - Property name.
///
/// # Returns
///
/// - `Option<f32>` - Finite `f32` value when present and numeric.
fn web_read_opt_f32(target: &JsValue, key: &str) -> Option<f32> {
    let val: JsValue = Reflect::get(target, &JsValue::from_str(key)).ok()?;
    let num: f64 = val.as_f64()?;
    if num.is_finite() {
        Some(num as f32)
    } else {
        None
    }
}

/// Reads a 3-component `(x, y, z)` vector from a nested JS property (such as `accelerationIncludingGravity`).
///
/// # Arguments
///
/// - `&JsValue` - Parent DOM event object.
/// - `&str` - Nested vector property name.
///
/// # Returns
///
/// - `Option<[f32; 3]>` - Vector when the nested object is non-null and carries at least one finite axis.
fn web_read_vec3_prop(event_val: &JsValue, prop: &str) -> Option<[f32; 3]> {
    let sub: JsValue = Reflect::get(event_val, &JsValue::from_str(prop)).ok()?;
    if sub.is_null() || sub.is_undefined() {
        return None;
    }
    let ox: Option<f32> = web_read_opt_f32(&sub, WEB_PROP_AXIS_X);
    let oy: Option<f32> = web_read_opt_f32(&sub, WEB_PROP_AXIS_Y);
    let oz: Option<f32> = web_read_opt_f32(&sub, WEB_PROP_AXIS_Z);
    if ox.is_none() && oy.is_none() && oz.is_none() {
        return None;
    }
    Some([ox.unwrap_or(0.0), oy.unwrap_or(0.0), oz.unwrap_or(0.0)])
}

/// Reads `DeviceMotionEvent.rotationRate` (`beta`->X, `gamma`->Y, `alpha`->Z) converted from `deg/s` into `rad/s`.
///
/// # Arguments
///
/// - `&JsValue` - `DeviceMotionEvent` JS object.
///
/// # Returns
///
/// - `[f32; 3]` - Device-frame angular velocity `[wx, wy, wz]` in `rad/s`.
fn web_read_rotation_rate_rad(event_val: &JsValue) -> [f32; 3] {
    let Ok(sub) = Reflect::get(event_val, &JsValue::from_str(WEB_PROP_ROTATION_RATE)) else {
        return [0.0, 0.0, 0.0];
    };
    if sub.is_null() || sub.is_undefined() {
        return [0.0, 0.0, 0.0];
    }
    let alpha_dps: f32 = web_read_opt_f32(&sub, WEB_PROP_ALPHA).unwrap_or(0.0);
    let beta_dps: f32 = web_read_opt_f32(&sub, WEB_PROP_BETA).unwrap_or(0.0);
    let gamma_dps: f32 = web_read_opt_f32(&sub, WEB_PROP_GAMMA).unwrap_or(0.0);
    [
        beta_dps * WEB_DEG_TO_RAD,
        gamma_dps * WEB_DEG_TO_RAD,
        alpha_dps * WEB_DEG_TO_RAD,
    ]
}

/// Queries the active browser screen rotation angle in degrees (`0`, `90`, `180`, `270`) from `screen.orientation.angle` with legacy `window.orientation` fallback.
///
/// # Returns
///
/// - `i32` - Normalized screen rotation angle in degrees.
#[must_use]
pub fn web_screen_orientation_angle_deg() -> i32 {
    let Some(win) = window() else {
        return 0;
    };
    if let Ok(screen_val) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_SCREEN))
        && !screen_val.is_null()
        && !screen_val.is_undefined()
        && let Ok(orient_val) = Reflect::get(&screen_val, &JsValue::from_str(WEB_PROP_ORIENTATION))
        && !orient_val.is_null()
        && !orient_val.is_undefined()
        && let Some(angle) = web_read_opt_f32(&orient_val, WEB_PROP_ANGLE)
    {
        return angle.round() as i32;
    }
    if let Some(legacy_angle) = web_read_opt_f32(win.as_ref(), WEB_PROP_ORIENTATION) {
        return legacy_angle.round() as i32;
    }
    0
}

/// Returns current browser monotonic timestamp in nanoseconds via `window.performance.now()`.
///
/// # Returns
///
/// - `u64` - Monotonic timestamp in nanoseconds (`0` when unavailable).
#[must_use]
fn web_monotonic_now_ns() -> u64 {
    window()
        .and_then(|win: Window| win.performance())
        .map(|perf: Performance| (perf.now().max(0.0) * 1_000_000.0) as u64)
        .unwrap_or(0)
}

/// Processes a browser `deviceorientation` event and updates the thread-local gravity orientation reference.
///
/// # Arguments
///
/// - `&Event` - Incoming DOM `DeviceOrientationEvent`.
fn web_handle_device_orientation(event: &Event) {
    let ev_val: &JsValue = event.as_ref();
    let Some(beta_deg) = web_read_opt_f32(ev_val, WEB_PROP_BETA) else {
        return;
    };
    let Some(gamma_deg) = web_read_opt_f32(ev_val, WEB_PROP_GAMMA) else {
        return;
    };
    let alpha_deg: f32 = web_read_opt_f32(ev_val, WEB_PROP_ALPHA).unwrap_or(0.0);
    let b: f32 = beta_deg * WEB_DEG_TO_RAD;
    let g: f32 = gamma_deg * WEB_DEG_TO_RAD;
    let yaw_rad: f32 = alpha_deg * WEB_DEG_TO_RAD;
    let g_dev: [f32; 3] = [
        STANDARD_GRAVITY_MPS2 * b.cos() * g.sin(),
        -STANDARD_GRAVITY_MPS2 * b.sin(),
        -STANDARD_GRAVITY_MPS2 * b.cos() * g.cos(),
    ];
    let angle_deg: i32 = web_screen_orientation_angle_deg();
    let ts_ns: u64 = web_monotonic_now_ns();
    WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
        if let Ok(mut st) = cell.try_borrow_mut() {
            st.orient_gravity_dev = Some(g_dev);
            st.last_yaw_rad = yaw_rad;
            if !st.has_motion_event {
                let mut sample: DeviceMotionSample = DeviceMotionSample::from_device_axes(
                    g_dev,
                    [0.0, 0.0, 0.0],
                    [0.0, 0.0, 0.0],
                    angle_deg,
                    ts_ns,
                );
                sample.set_yaw_rad(yaw_rad);
                st.pending_sample = sample;
                st.has_pending_sample = true;
            }
        }
    });
}

/// Processes a browser `devicemotion` event, fuses gravity, linear acceleration, and gyroscope rate into screen-aligned coordinates.
///
/// # Arguments
///
/// - `&Event` - Incoming DOM `DeviceMotionEvent`.
fn web_handle_device_motion(event: &Event) {
    let ev_val: &JsValue = event.as_ref();
    let accel_incl: Option<[f32; 3]> = web_read_vec3_prop(ev_val, WEB_PROP_ACCEL_INCLUDING_GRAVITY);
    let accel_lin: Option<[f32; 3]> = web_read_vec3_prop(ev_val, WEB_PROP_ACCELERATION);
    let gyro_dev: [f32; 3] = web_read_rotation_rate_rad(ev_val);
    let angle_deg: i32 = web_screen_orientation_angle_deg();
    let ts_ns: u64 = web_monotonic_now_ns();
    WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
        if let Ok(mut st) = cell.try_borrow_mut() {
            let mut g_dev_opt: Option<[f32; 3]> = None;
            let mut lin_dev: [f32; 3] = [0.0, 0.0, 0.0];
            if let Some(ag) = accel_incl {
                st.has_motion_event = true;
                let (raw_g, raw_lin): ([f32; 3], [f32; 3]) = if let Some(al) = accel_lin {
                    ([ag[0] - al[0], ag[1] - al[1], ag[2] - al[2]], al)
                } else {
                    let prev: [f32; 3] = st.filtered_gravity_dev.unwrap_or(ag);
                    let a: f32 = WEB_GRAVITY_LPF_ALPHA;
                    let filt: [f32; 3] = [
                        prev[0] * (1.0 - a) + ag[0] * a,
                        prev[1] * (1.0 - a) + ag[1] * a,
                        prev[2] * (1.0 - a) + ag[2] * a,
                    ];
                    st.filtered_gravity_dev = Some(filt);
                    (filt, [ag[0] - filt[0], ag[1] - filt[1], ag[2] - filt[2]])
                };
                if let Some(og) = st.orient_gravity_dev {
                    let dot: f32 = raw_g[0] * og[0] + raw_g[1] * og[1] + raw_g[2] * og[2];
                    if dot > WEB_GRAVITY_SIGN_DOT_THRESHOLD {
                        st.gravity_sign = 1.0;
                    } else if dot < -WEB_GRAVITY_SIGN_DOT_THRESHOLD {
                        st.gravity_sign = -1.0;
                    }
                }
                let s: f32 = st.gravity_sign;
                g_dev_opt = Some([raw_g[0] * s, raw_g[1] * s, raw_g[2] * s]);
                let lin_sign: f32 = if s > 0.0 { -1.0 } else { 1.0 };
                lin_dev = [
                    raw_lin[0] * lin_sign,
                    raw_lin[1] * lin_sign,
                    raw_lin[2] * lin_sign,
                ];
            } else if let Some(og) = st.orient_gravity_dev {
                g_dev_opt = Some(og);
                if let Some(al) = accel_lin {
                    lin_dev = al;
                }
            }
            if let Some(g_dev) = g_dev_opt {
                let mut sample: DeviceMotionSample = DeviceMotionSample::from_device_axes(
                    g_dev, lin_dev, gyro_dev, angle_deg, ts_ns,
                );
                sample.set_yaw_rad(st.last_yaw_rad);
                st.pending_sample = sample;
                st.has_pending_sample = true;
            }
        }
    });
}

/// Attaches browser `devicemotion` and `deviceorientation` listeners once onto `window` so `WebPlatform::poll_events` emits screen-aligned `SystemEvent::DeviceMotion` samples.
///
/// # Returns
///
/// - `bool` - `true` when browser motion listeners are attached and ready.
pub fn web_attach_device_motion_listeners() -> bool {
    let already: bool = WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
        cell.try_borrow()
            .map(|st: Ref<'_, WebDeviceMotionState>| st.listeners_attached)
            .unwrap_or(false)
    });
    if already {
        return true;
    }
    let Some(win) = window() else {
        return false;
    };
    let on_motion: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(|ev: Event| {
        web_handle_device_motion(&ev);
    }) as Box<dyn FnMut(Event)>);
    let motion_ok: bool = win
        .add_event_listener_with_callback(
            WEB_EVENT_DEVICE_MOTION,
            on_motion.as_ref().unchecked_ref(),
        )
        .is_ok();
    on_motion.forget();
    let on_orient: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(|ev: Event| {
        web_handle_device_orientation(&ev);
    }) as Box<dyn FnMut(Event)>);
    let orient_ok: bool = win
        .add_event_listener_with_callback(
            WEB_EVENT_DEVICE_ORIENTATION,
            on_orient.as_ref().unchecked_ref(),
        )
        .is_ok();
    on_orient.forget();
    let attached: bool = motion_ok || orient_ok;
    if attached {
        WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
            if let Ok(mut st) = cell.try_borrow_mut() {
                st.listeners_attached = true;
            }
        });
    }
    attached
}

/// Drains the most recent browser-fused `DeviceMotionSample`, if a fresh sensor reading arrived since the previous poll.
///
/// # Returns
///
/// - `Option<DeviceMotionSample>` - Latest screen-aligned sample ready for `SystemEvent::DeviceMotion`.
#[must_use]
pub fn web_take_pending_device_motion() -> Option<DeviceMotionSample> {
    WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
        cell.try_borrow_mut()
            .ok()
            .and_then(|mut st: RefMut<'_, WebDeviceMotionState>| {
                if st.has_pending_sample {
                    st.has_pending_sample = false;
                    Some(st.pending_sample)
                } else {
                    None
                }
            })
    })
}

/// Invokes a static Safari sensor `requestPermission()` method on `ctor_name`, attaching motion listeners if permission resolves as `"granted"`.
///
/// # Arguments
///
/// - `&Window` - Active browser `Window`.
/// - `&str` - Constructor name (`DeviceMotionEvent` or `DeviceOrientationEvent`).
///
/// # Returns
///
/// - `bool` - `true` when the browser exposed and invoked `requestPermission()`.
fn web_try_request_ctor_permission(win: &Window, ctor_name: &str) -> bool {
    let Ok(ctor_val) = Reflect::get(win.as_ref(), &JsValue::from_str(ctor_name)) else {
        return false;
    };
    if ctor_val.is_null() || ctor_val.is_undefined() {
        return false;
    }
    let Ok(req_val) = Reflect::get(&ctor_val, &JsValue::from_str(WEB_METHOD_REQUEST_PERMISSION))
    else {
        return false;
    };
    let Ok(req_fn) = req_val.dyn_into::<Function>() else {
        return false;
    };
    if let Ok(ret) = req_fn.call0(&ctor_val)
        && let Ok(promise) = ret.dyn_into::<Promise>()
    {
        let on_granted: Closure<dyn FnMut(JsValue)> = Closure::wrap(Box::new(|res: JsValue| {
            if res.as_string().as_deref() == Some(WEB_PERMISSION_GRANTED) {
                let _: bool = web_attach_device_motion_listeners();
            }
        })
            as Box<dyn FnMut(JsValue)>);
        let chained: Promise = promise.then(&on_granted);
        on_granted.forget();
        WEB_PROMISE_NOOP_REJECT.with(|cb: &Closure<dyn FnMut(JsValue)>| {
            let _: Promise = chained.catch(cb);
        });
        return true;
    }
    false
}

/// Requests browser device motion/orientation permission (required on iOS 13+ Safari inside a user gesture) and attaches sensor listeners.
///
/// # Returns
///
/// - `bool` - `true` when permission request was dispatched or listeners were immediately attached.
pub(crate) fn web_request_motion_permission_impl() -> bool {
    let Some(win) = window() else {
        return false;
    };
    let motion_req: bool = web_try_request_ctor_permission(&win, WEB_CTOR_DEVICE_MOTION_EVENT);
    let orient_req: bool = web_try_request_ctor_permission(&win, WEB_CTOR_DEVICE_ORIENTATION_EVENT);
    if motion_req || orient_req {
        return true;
    }
    web_attach_device_motion_listeners()
}