cranpose 0.1.4

Cranpose runtime and UI facade
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
//! Web runtime for Compose applications.
//!
//! This module provides the web event loop implementation using wasm-bindgen and WebGPU.

use crate::launcher::AppSettings;
use cranpose_app_shell::{default_root_key, AppShell};
use cranpose_platform_web::WebPlatform;
use cranpose_render_wgpu::WgpuRenderer;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::{HtmlCanvasElement, MouseEvent, PointerEvent, WheelEvent};

const WEB_WHEEL_LINE_DELTA_PIXELS: f32 = 40.0;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum WebBackendPreference {
    Auto,
    WebGpu,
    Gl,
}

/// Runs a web Compose application with wgpu rendering.
///
/// Called by `AppLauncher::run_web()`. This is the framework-level
/// entrypoint that manages the web canvas and rendering.
///
/// **Note:** Applications should use `AppLauncher` instead of calling this directly.
pub async fn run(
    canvas_id: &str,
    settings: AppSettings,
    content: impl FnMut() + 'static,
) -> Result<(), JsValue> {
    // Set up console logging
    console_error_panic_hook::set_once();

    // Get the window and document
    let window = web_sys::window().ok_or("no global window exists")?;
    let document = window
        .document()
        .ok_or("should have a document on window")?;

    // Get the canvas element
    let canvas = document
        .get_element_by_id(canvas_id)
        .ok_or_else(|| format!("canvas with id '{}' not found", canvas_id))?
        .dyn_into::<HtmlCanvasElement>()?;

    // Get device pixel ratio for proper scaling
    let scale_factor = window.device_pixel_ratio();

    // Set canvas size
    let width = settings.initial_width;
    let height = settings.initial_height;

    canvas.set_width((width as f64 * scale_factor) as u32);
    canvas.set_height((height as f64 * scale_factor) as u32);

    // Set CSS size and disable browser touch gesture handling on the canvas
    if let Some(html_element) = canvas.dyn_ref::<web_sys::HtmlElement>() {
        let style = html_element.style();
        style.set_property("width", &format!("{}px", width))?;
        style.set_property("height", &format!("{}px", height))?;
        style.set_property("touch-action", "none")?;
    }

    let backend_preference = requested_web_backend(&window);
    let instance_desc = wgpu::InstanceDescriptor {
        backends: instance_backends(backend_preference),
        ..Default::default()
    };
    let instance = match backend_preference {
        WebBackendPreference::Auto => {
            wgpu::util::new_instance_with_webgpu_detection(&instance_desc).await
        }
        WebBackendPreference::WebGpu | WebBackendPreference::Gl => {
            wgpu::Instance::new(&instance_desc)
        }
    };

    let surface = instance
        .create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone()))
        .map_err(|e| format!("failed to create surface: {:?}", e))?;

    let adapter = instance
        .request_adapter(&wgpu::RequestAdapterOptions {
            power_preference: wgpu::PowerPreference::HighPerformance,
            compatible_surface: Some(&surface),
            force_fallback_adapter: false,
        })
        .await
        .map_err(|e| format!("failed to find suitable adapter: {:?}", e))?;

    let adapter_info = adapter.get_info();
    let adapter_limits = adapter.limits();
    let required_limits =
        required_limits_for_web_backend(adapter_info.backend, adapter_limits.clone());
    log::info!(
        "Web backend preference={:?}, selected backend={:?}, max_texture_dimension_2d={}",
        backend_preference,
        adapter_info.backend,
        adapter_limits.max_texture_dimension_2d
    );

    let (device, queue) = adapter
        .request_device(&wgpu::DeviceDescriptor {
            label: Some("Main Device"),
            required_features: wgpu::Features::empty(),
            required_limits,
            experimental_features: wgpu::ExperimentalFeatures::disabled(),
            memory_hints: wgpu::MemoryHints::default(),
            trace: wgpu::Trace::Off,
        })
        .await
        .map_err(|e| format!("failed to create device: {:?}", e))?;

    let surface_caps = surface.get_capabilities(&adapter);
    let surface_format = surface_caps
        .formats
        .iter()
        .copied()
        .find(|f| f.is_srgb())
        .unwrap_or(surface_caps.formats[0]);

    let present_mode = crate::present_mode::select_present_mode(&surface_caps);
    let surface_config = wgpu::SurfaceConfiguration {
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
        format: surface_format,
        width: (width as f64 * scale_factor) as u32,
        height: (height as f64 * scale_factor) as u32,
        present_mode,
        alpha_mode: surface_caps.alpha_modes[0],
        view_formats: vec![],
        desired_maximum_frame_latency: 2,
    };

    surface.configure(&device, &surface_config);

    let mut surface_config = surface_config;
    let (actual_width, actual_height, effective_scale) =
        if adapter_info.backend == wgpu::Backend::BrowserWebGpu {
            (surface_config.width, surface_config.height, scale_factor)
        } else {
            // WebGL backends can cap the swapchain below the requested size.
            // Probe the actual surface once so layout and root scale match the
            // real render target instead of the requested CSS size.
            let probe = surface
                .get_current_texture()
                .map_err(|e| format!("failed to probe surface texture: {e:?}"))?;
            let actual_width = probe.texture.width();
            let actual_height = probe.texture.height();
            probe.present();
            let effective_scale =
                if actual_width < surface_config.width || actual_height < surface_config.height {
                    let fit_x = actual_width as f64 / width as f64;
                    let fit_y = actual_height as f64 / height as f64;
                    let s = fit_x.min(fit_y);
                    surface_config.width = actual_width;
                    surface_config.height = actual_height;
                    s
                } else {
                    scale_factor
                };
            (actual_width, actual_height, effective_scale)
        };

    // Create renderer with fonts from settings
    let fonts: &[&[u8]] = settings.fonts.unwrap_or(&[]);
    log::info!("Web renderer startup: {} font(s)", fonts.len());
    let mut renderer = WgpuRenderer::new(fonts);
    renderer.init_gpu(
        Arc::new(device),
        Arc::new(queue),
        surface_format,
        adapter_info.backend,
    );
    renderer.set_root_scale(effective_scale as f32);
    cranpose_ui::set_density(effective_scale as f32);

    let app = Rc::new(RefCell::new(AppShell::new(
        renderer,
        default_root_key(),
        content,
    )));
    let platform = Rc::new(RefCell::new(WebPlatform::default()));
    platform.borrow_mut().set_scale_factor(effective_scale);

    // Set buffer_size to actual physical pixels and viewport to logical dp
    app.borrow_mut()
        .set_buffer_size(actual_width, actual_height);
    app.borrow_mut().set_viewport(width as f32, height as f32);

    let surface = Rc::new(surface);
    let surface_config = Rc::new(RefCell::new(surface_config));

    // Set up mouse event handlers
    {
        let app = app.clone();
        let platform = platform.clone();
        let closure = Closure::wrap(Box::new(move |event: MouseEvent| {
            let x = event.offset_x() as f64;
            let y = event.offset_y() as f64;
            let logical = platform.borrow().pointer_position(x, y);
            // Use try_borrow_mut to avoid panic if render loop is active
            if let Ok(mut app_mut) = app.try_borrow_mut() {
                app_mut.set_cursor(logical.x, logical.y);
            }
        }) as Box<dyn FnMut(_)>);
        canvas.add_event_listener_with_callback("mousemove", closure.as_ref().unchecked_ref())?;
        closure.forget();
    }

    {
        let app = app.clone();
        let platform = platform.clone();
        let closure = Closure::wrap(Box::new(move |event: MouseEvent| {
            let x = event.offset_x() as f64;
            let y = event.offset_y() as f64;
            let logical = platform.borrow().pointer_position(x, y);
            if let Ok(mut app_mut) = app.try_borrow_mut() {
                app_mut.set_cursor(logical.x, logical.y);
                app_mut.pointer_pressed();
            }
        }) as Box<dyn FnMut(_)>);
        canvas.add_event_listener_with_callback("mousedown", closure.as_ref().unchecked_ref())?;
        closure.forget();
    }

    {
        let app = app.clone();
        let platform = platform.clone();
        let closure = Closure::wrap(Box::new(move |event: MouseEvent| {
            let x = event.offset_x() as f64;
            let y = event.offset_y() as f64;
            let logical = platform.borrow().pointer_position(x, y);
            if let Ok(mut app_mut) = app.try_borrow_mut() {
                app_mut.set_cursor(logical.x, logical.y);
                app_mut.pointer_released();
            }
        }) as Box<dyn FnMut(_)>);
        canvas.add_event_listener_with_callback("mouseup", closure.as_ref().unchecked_ref())?;
        closure.forget();
    }

    {
        let app = app.clone();
        let platform = platform.clone();
        let wheel_canvas = canvas.clone();
        let closure = Closure::wrap(Box::new(move |event: WheelEvent| {
            let x = event.offset_x() as f64;
            let y = event.offset_y() as f64;
            let logical = platform.borrow().pointer_position(x, y);

            let mut delta_x = event.delta_x() as f32;
            let mut delta_y = event.delta_y() as f32;
            match event.delta_mode() {
                WheelEvent::DOM_DELTA_PIXEL => {}
                WheelEvent::DOM_DELTA_LINE => {
                    delta_x *= WEB_WHEEL_LINE_DELTA_PIXELS;
                    delta_y *= WEB_WHEEL_LINE_DELTA_PIXELS;
                }
                WheelEvent::DOM_DELTA_PAGE => {
                    let page_width = wheel_canvas.client_width().max(1) as f32;
                    let page_height = wheel_canvas.client_height().max(1) as f32;
                    delta_x *= page_width;
                    delta_y *= page_height;
                }
                _ => {}
            }

            if event.alt_key() {
                if delta_x.abs() <= f32::EPSILON {
                    delta_x = delta_y;
                }
                delta_y = 0.0;
            }

            if let Ok(mut app_mut) = app.try_borrow_mut() {
                app_mut.set_cursor(logical.x, logical.y);
                if app_mut.pointer_scrolled(delta_x, delta_y) {
                    event.prevent_default();
                }
            }
        }) as Box<dyn FnMut(_)>);
        canvas.add_event_listener_with_callback("wheel", closure.as_ref().unchecked_ref())?;
        closure.forget();
    }

    // Set up pointer event handlers for touch support
    {
        let app = app.clone();
        let platform = platform.clone();
        let closure = Closure::wrap(Box::new(move |event: PointerEvent| {
            event.prevent_default();
            let x = event.offset_x() as f64;
            let y = event.offset_y() as f64;
            let logical = platform.borrow().pointer_position(x, y);
            if let Ok(mut app_mut) = app.try_borrow_mut() {
                app_mut.set_cursor(logical.x, logical.y);
            }
        }) as Box<dyn FnMut(_)>);
        canvas.add_event_listener_with_callback("pointermove", closure.as_ref().unchecked_ref())?;
        closure.forget();
    }

    {
        let app = app.clone();
        let platform = platform.clone();
        let closure = Closure::wrap(Box::new(move |event: PointerEvent| {
            event.prevent_default();
            let x = event.offset_x() as f64;
            let y = event.offset_y() as f64;
            let logical = platform.borrow().pointer_position(x, y);
            if let Ok(mut app_mut) = app.try_borrow_mut() {
                app_mut.set_cursor(logical.x, logical.y);
                app_mut.pointer_pressed();
            }
        }) as Box<dyn FnMut(_)>);
        canvas.add_event_listener_with_callback("pointerdown", closure.as_ref().unchecked_ref())?;
        closure.forget();
    }

    {
        let app = app.clone();
        let platform = platform.clone();
        let closure = Closure::wrap(Box::new(move |event: PointerEvent| {
            event.prevent_default();
            let x = event.offset_x() as f64;
            let y = event.offset_y() as f64;
            let logical = platform.borrow().pointer_position(x, y);
            if let Ok(mut app_mut) = app.try_borrow_mut() {
                app_mut.set_cursor(logical.x, logical.y);
                app_mut.pointer_released();
            }
        }) as Box<dyn FnMut(_)>);
        canvas.add_event_listener_with_callback("pointerup", closure.as_ref().unchecked_ref())?;
        closure.forget();
    }

    {
        let app = app.clone();
        let closure = Closure::wrap(Box::new(move |event: PointerEvent| {
            event.prevent_default();
            if let Ok(mut app_mut) = app.try_borrow_mut() {
                app_mut.cancel_gesture();
            }
        }) as Box<dyn FnMut(_)>);
        canvas
            .add_event_listener_with_callback("pointercancel", closure.as_ref().unchecked_ref())?;
        closure.forget();
    }

    // Set up keyboard event handlers
    // Note: We need to listen on document (not canvas) for keyboard events
    // unless the canvas has tabindex set and is focused
    {
        let app = app.clone();
        let closure = Closure::wrap(Box::new(move |event: web_sys::KeyboardEvent| {
            use cranpose_app_shell::{KeyCode, KeyEvent, KeyEventType, Modifiers};

            // Convert web key code to our KeyCode
            let key_code = match event.code().as_str() {
                // Letters
                "KeyA" => KeyCode::A,
                "KeyB" => KeyCode::B,
                "KeyC" => KeyCode::C,
                "KeyD" => KeyCode::D,
                "KeyE" => KeyCode::E,
                "KeyF" => KeyCode::F,
                "KeyG" => KeyCode::G,
                "KeyH" => KeyCode::H,
                "KeyI" => KeyCode::I,
                "KeyJ" => KeyCode::J,
                "KeyK" => KeyCode::K,
                "KeyL" => KeyCode::L,
                "KeyM" => KeyCode::M,
                "KeyN" => KeyCode::N,
                "KeyO" => KeyCode::O,
                "KeyP" => KeyCode::P,
                "KeyQ" => KeyCode::Q,
                "KeyR" => KeyCode::R,
                "KeyS" => KeyCode::S,
                "KeyT" => KeyCode::T,
                "KeyU" => KeyCode::U,
                "KeyV" => KeyCode::V,
                "KeyW" => KeyCode::W,
                "KeyX" => KeyCode::X,
                "KeyY" => KeyCode::Y,
                "KeyZ" => KeyCode::Z,
                // Numbers
                "Digit0" => KeyCode::Digit0,
                "Digit1" => KeyCode::Digit1,
                "Digit2" => KeyCode::Digit2,
                "Digit3" => KeyCode::Digit3,
                "Digit4" => KeyCode::Digit4,
                "Digit5" => KeyCode::Digit5,
                "Digit6" => KeyCode::Digit6,
                "Digit7" => KeyCode::Digit7,
                "Digit8" => KeyCode::Digit8,
                "Digit9" => KeyCode::Digit9,
                // Navigation
                "ArrowUp" => KeyCode::ArrowUp,
                "ArrowDown" => KeyCode::ArrowDown,
                "ArrowLeft" => KeyCode::ArrowLeft,
                "ArrowRight" => KeyCode::ArrowRight,
                "Home" => KeyCode::Home,
                "End" => KeyCode::End,
                "PageUp" => KeyCode::PageUp,
                "PageDown" => KeyCode::PageDown,
                // Editing
                "Backspace" => KeyCode::Backspace,
                "Delete" => KeyCode::Delete,
                "Enter" | "NumpadEnter" => KeyCode::Enter,
                "Tab" => KeyCode::Tab,
                "Space" => KeyCode::Space,
                "Escape" => KeyCode::Escape,
                // Punctuation
                "Minus" => KeyCode::Minus,
                "Equal" => KeyCode::Equal,
                "BracketLeft" => KeyCode::BracketLeft,
                "BracketRight" => KeyCode::BracketRight,
                "Backslash" => KeyCode::Backslash,
                "Semicolon" => KeyCode::Semicolon,
                "Quote" => KeyCode::Quote,
                "Comma" => KeyCode::Comma,
                "Period" => KeyCode::Period,
                "Slash" => KeyCode::Slash,
                "Backquote" => KeyCode::Backquote,
                _ => KeyCode::Unknown,
            };

            let modifiers = Modifiers {
                shift: event.shift_key(),
                ctrl: event.ctrl_key(),
                alt: event.alt_key(),
                meta: event.meta_key(),
            };

            // Get the text produced by this key (from event.key)
            // Filter out long key names like "Shift", "Control", etc.
            let text = {
                let key = event.key();
                if key.len() == 1 {
                    key
                } else {
                    String::new()
                }
            };

            let key_event = KeyEvent {
                key_code,
                text,
                modifiers,
                event_type: KeyEventType::KeyDown,
            };

            if let Ok(mut app_mut) = app.try_borrow_mut() {
                if app_mut.on_key_event(&key_event) {
                    event.prevent_default();
                }
            }
        }) as Box<dyn FnMut(_)>);
        document.add_event_listener_with_callback("keydown", closure.as_ref().unchecked_ref())?;
        closure.forget();
    }

    {
        let app = app.clone();
        let closure = Closure::wrap(Box::new(move |event: web_sys::KeyboardEvent| {
            use cranpose_app_shell::{KeyCode, KeyEvent, KeyEventType, Modifiers};

            // Similar conversion for keyup
            let key_code = match event.code().as_str() {
                "KeyA" => KeyCode::A,
                "KeyB" => KeyCode::B,
                "KeyC" => KeyCode::C,
                "KeyD" => KeyCode::D,
                "KeyE" => KeyCode::E,
                "KeyF" => KeyCode::F,
                "KeyG" => KeyCode::G,
                "KeyH" => KeyCode::H,
                "KeyI" => KeyCode::I,
                "KeyJ" => KeyCode::J,
                "KeyK" => KeyCode::K,
                "KeyL" => KeyCode::L,
                "KeyM" => KeyCode::M,
                "KeyN" => KeyCode::N,
                "KeyO" => KeyCode::O,
                "KeyP" => KeyCode::P,
                "KeyQ" => KeyCode::Q,
                "KeyR" => KeyCode::R,
                "KeyS" => KeyCode::S,
                "KeyT" => KeyCode::T,
                "KeyU" => KeyCode::U,
                "KeyV" => KeyCode::V,
                "KeyW" => KeyCode::W,
                "KeyX" => KeyCode::X,
                "KeyY" => KeyCode::Y,
                "KeyZ" => KeyCode::Z,
                "Digit0" => KeyCode::Digit0,
                "Digit1" => KeyCode::Digit1,
                "Digit2" => KeyCode::Digit2,
                "Digit3" => KeyCode::Digit3,
                "Digit4" => KeyCode::Digit4,
                "Digit5" => KeyCode::Digit5,
                "Digit6" => KeyCode::Digit6,
                "Digit7" => KeyCode::Digit7,
                "Digit8" => KeyCode::Digit8,
                "Digit9" => KeyCode::Digit9,
                "ArrowUp" => KeyCode::ArrowUp,
                "ArrowDown" => KeyCode::ArrowDown,
                "ArrowLeft" => KeyCode::ArrowLeft,
                "ArrowRight" => KeyCode::ArrowRight,
                "Backspace" => KeyCode::Backspace,
                "Delete" => KeyCode::Delete,
                "Enter" | "NumpadEnter" => KeyCode::Enter,
                "Tab" => KeyCode::Tab,
                "Space" => KeyCode::Space,
                _ => KeyCode::Unknown,
            };

            let modifiers = Modifiers {
                shift: event.shift_key(),
                ctrl: event.ctrl_key(),
                alt: event.alt_key(),
                meta: event.meta_key(),
            };

            let key_event = KeyEvent {
                key_code,
                text: String::new(), // KeyUp doesn't produce text
                modifiers,
                event_type: KeyEventType::KeyUp,
            };

            if let Ok(mut app_mut) = app.try_borrow_mut() {
                app_mut.on_key_event(&key_event);
            }
        }) as Box<dyn FnMut(_)>);
        document.add_event_listener_with_callback("keyup", closure.as_ref().unchecked_ref())?;
        closure.forget();
    }

    // Set up paste event handler for clipboard paste
    {
        let app = app.clone();
        let closure = Closure::wrap(Box::new(move |event: web_sys::ClipboardEvent| {
            // Get pasted text from clipboardData (synchronous!)
            if let Some(data) = event.clipboard_data() {
                if let Ok(text) = data.get_data("text/plain") {
                    if !text.is_empty() {
                        if let Ok(mut app_mut) = app.try_borrow_mut() {
                            if app_mut.on_paste(&text) {
                                event.prevent_default();
                            }
                        }
                    }
                }
            }
        }) as Box<dyn FnMut(_)>);
        document.add_event_listener_with_callback("paste", closure.as_ref().unchecked_ref())?;
        closure.forget();
    }

    // Set up copy event handler for clipboard copy
    {
        let app = app.clone();
        let closure = Closure::wrap(Box::new(move |event: web_sys::ClipboardEvent| {
            if let Ok(mut app_mut) = app.try_borrow_mut() {
                if let Some(text) = app_mut.on_copy() {
                    // Put copied text into the clipboard via the event
                    if let Some(data) = event.clipboard_data() {
                        let _ = data.set_data("text/plain", &text);
                        event.prevent_default();
                    }
                }
            }
        }) as Box<dyn FnMut(_)>);
        document.add_event_listener_with_callback("copy", closure.as_ref().unchecked_ref())?;
        closure.forget();
    }

    // Set up cut event handler for clipboard cut
    {
        let app = app.clone();
        let closure = Closure::wrap(Box::new(move |event: web_sys::ClipboardEvent| {
            if let Ok(mut app_mut) = app.try_borrow_mut() {
                if let Some(text) = app_mut.on_cut() {
                    // Put cut text into the clipboard via the event
                    if let Some(data) = event.clipboard_data() {
                        let _ = data.set_data("text/plain", &text);
                        event.prevent_default();
                    }
                }
            }
        }) as Box<dyn FnMut(_)>);
        document.add_event_listener_with_callback("cut", closure.as_ref().unchecked_ref())?;
        closure.forget();
    }

    // Render loop
    let render_loop = Rc::new(RefCell::new(None));
    let render_loop_clone = render_loop.clone();

    *render_loop.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        app.borrow_mut().update();

        let config = surface_config.borrow();
        match surface.get_current_texture() {
            Ok(output) => {
                let view = output
                    .texture
                    .create_view(&wgpu::TextureViewDescriptor::default());
                let render_width = output.texture.width();
                let render_height = output.texture.height();

                {
                    let mut app_mut = app.borrow_mut();
                    if let Err(err) = app_mut
                        .renderer()
                        .render(&view, render_width, render_height)
                    {
                        log::error!("render failed: {:?}", err);
                    }
                }

                output.present();
            }
            Err(wgpu::SurfaceError::Lost) | Err(wgpu::SurfaceError::Outdated) => {
                // Reconfigure surface
                let mut app_mut = app.borrow_mut();
                let device = app_mut.renderer().device();
                surface.configure(device, &*config);
            }
            Err(wgpu::SurfaceError::OutOfMemory) => {
                log::error!("Out of memory");
            }
            Err(wgpu::SurfaceError::Timeout) => {
                log::debug!("Surface timeout, skipping frame");
            }
            Err(wgpu::SurfaceError::Other) => {
                log::error!("Surface other error, skipping frame");
            }
        }

        // Request next frame
        request_animation_frame(render_loop_clone.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    // Start the render loop
    request_animation_frame(render_loop.borrow().as_ref().unwrap());

    Ok(())
}

fn request_animation_frame(f: &Closure<dyn FnMut()>) {
    web_sys::window()
        .unwrap()
        .request_animation_frame(f.as_ref().unchecked_ref())
        .expect("should register `requestAnimationFrame` OK");
}

fn requested_web_backend(window: &web_sys::Window) -> WebBackendPreference {
    let query = window.location().search().unwrap_or_default();
    for pair in query.trim_start_matches('?').split('&') {
        let Some((key, value)) = pair.split_once('=') else {
            continue;
        };
        if key != "backend" {
            continue;
        }
        return match value {
            "webgpu" => WebBackendPreference::WebGpu,
            "gl" => WebBackendPreference::Gl,
            _ => WebBackendPreference::Auto,
        };
    }
    WebBackendPreference::Gl
}

fn instance_backends(preference: WebBackendPreference) -> wgpu::Backends {
    match preference {
        WebBackendPreference::Auto => wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL,
        WebBackendPreference::WebGpu => wgpu::Backends::BROWSER_WEBGPU,
        WebBackendPreference::Gl => wgpu::Backends::GL,
    }
}

fn required_limits_for_web_backend(
    backend: wgpu::Backend,
    adapter_limits: wgpu::Limits,
) -> wgpu::Limits {
    match backend {
        wgpu::Backend::BrowserWebGpu => wgpu::Limits::default().using_resolution(adapter_limits),
        _ => wgpu::Limits::downlevel_webgl2_defaults().using_resolution(adapter_limits),
    }
}