nightshade-api 0.53.0

Procedural high level API for the nightshade game engine
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
//! The worker side of a web-worker-hosted engine, enabled by the `offscreen`
//! cargo feature.
//!
//! [`WorkerHostPlugin`] is the hosting capability as a plugin: composing it
//! installs a custom runner that owns the `OffscreenCanvas`, the renderer,
//! the `requestAnimationFrame` loop, and the page conversation. The control
//! plane ([`crate::wire::ToWorker`] / [`crate::wire::FromWorker`]: init,
//! resize, input injection, picking, stats) is handled by the host; the
//! application's own messages ride the [`crate::wire::APP_KEY`] envelope
//! field as the [`WorkerProtocol`] pair, with binary [`Attachments`]
//! transferred alongside. Systems reply through the [`WorkerOutbox`]
//! resource, drained after every frame; async callbacks with no world
//! access post directly with [`post_app_message`].
//!
//! ```ignore
//! #[wasm_bindgen(start)]
//! pub fn start() {
//!     App::new()
//!         .add_plugin(WorkerHostPlugin::<GameProtocol>::new(
//!             OffscreenConfig::default(),
//!             systems::apply_message,
//!         ))
//!         .add_plugin(UiPlugin)
//!         .add_plugin(GamePlugin)
//!         .run()
//!         .expect("worker failed to start");
//! }
//! ```
//!
//! [`run_offscreen`] remains the closure form over [`ValueProtocol`] for
//! apps without message enums: scene state, a setup, a tick, and a JSON
//! message handler.

use std::cell::RefCell;
use std::rc::Rc;

use crate::picking::{entity_under_cursor, request_surface_pick};
use crate::transfer::{
    app_value_from, attach, attachments_from, control_value_from, envelope_with,
};
use crate::wire::{
    APP_KEY, Attachments, CANVAS_KEY, FromWorker, MESSAGE_KEY, SelectedEntity, ToWorker,
    ValueProtocol, WorkerProtocol,
};
use nightshade::prelude::*;
use nightshade::render::wgpu::create_wgpu_renderer;
use serde::Serialize;
use serde_json::Value;
use wasm_bindgen::prelude::*;
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::spawn_local;
use web_sys::{DedicatedWorkerGlobalScope, MessageEvent, OffscreenCanvas};

/// How the host resolves the `Pick` a click or tap without drag sends. The
/// cursor position is injected in every mode, so the pick lands where the
/// engine believes the cursor is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PickMode {
    /// Resolve synchronously with the cursor ray, update the engine
    /// selection (and its outline), and report the result to the page.
    CursorRay,
    /// Request a GPU pick through `request_surface_pick`. The result lands a
    /// frame later: poll `take_surface_pick` from a system and answer the
    /// page with [`post_control`].
    Gpu,
    /// Leave picking entirely to the app.
    Manual,
}

/// Behavior switches for the host. The defaults are what [`run_offscreen`]
/// runs with: the engine camera controllers every frame and the synchronous
/// cursor ray pick on click.
#[derive(Clone, Copy, Debug)]
pub struct OffscreenConfig {
    /// Runs `camera_controllers_system` on [`Stage::First`]. Disable to
    /// drive the camera entirely from the app's systems.
    pub camera_controllers: bool,
    /// How clicks and taps resolve to a selection. The current selection is
    /// readable from any system through the [`HostSelection`] resource;
    /// outside [`PickMode::CursorRay`] the host never writes it.
    pub pick_mode: PickMode,
}

impl Default for OffscreenConfig {
    fn default() -> Self {
        Self {
            camera_controllers: true,
            pick_mode: PickMode::CursorRay,
        }
    }
}

/// The selection the host's pick resolution last produced, as a group
/// resource any system can read.
#[derive(Default)]
pub struct HostSelection(pub Option<Entity>);

/// Worker-to-page mail: systems push [`WorkerProtocol::Outgoing`] messages
/// (optionally with named binary attachments, which ride the transfer
/// list), and the host drains and posts everything after each frame.
pub struct WorkerOutbox<Outgoing> {
    pub messages: Vec<Outgoing>,
    pub attachments: Vec<(Outgoing, Attachments)>,
}

impl<Outgoing> Default for WorkerOutbox<Outgoing> {
    fn default() -> Self {
        Self {
            messages: Vec::new(),
            attachments: Vec::new(),
        }
    }
}

impl<Outgoing> WorkerOutbox<Outgoing> {
    pub fn send(&mut self, message: Outgoing) {
        self.messages.push(message);
    }

    pub fn send_with_attachments(&mut self, message: Outgoing, attachments: Attachments) {
        self.attachments.push((message, attachments));
    }
}

thread_local! {
    static HOST_CANVAS: RefCell<Option<OffscreenCanvas>> = const { RefCell::new(None) };
    static LOG_GUARDS: RefCell<Vec<Box<dyn std::any::Any>>> = const { RefCell::new(Vec::new()) };
}

/// The `OffscreenCanvas` the host renders into, available once `Init` has
/// arrived. For app code that reads pixels back, like a screenshot tool.
pub fn host_canvas() -> Option<OffscreenCanvas> {
    HOST_CANVAS.with(|canvas| canvas.borrow().clone())
}

type MessageFn<P> =
    Box<dyn FnMut(&mut World, <P as WorkerProtocol>::Incoming, Attachments) + 'static>;
type PostFrameFn = Box<dyn FnMut(&mut World) + 'static>;

struct HostHandlers<P: WorkerProtocol> {
    on_message: MessageFn<P>,
    post_frame: Vec<PostFrameFn>,
}

/// Hosts the composed [`App`] inside a dedicated web worker: composing this
/// plugin installs the runner that owns the message pump, the renderer, and
/// the render loop. Add it once; the app's other plugins and systems
/// compose around it unchanged.
pub struct WorkerHostPlugin<P: WorkerProtocol> {
    config: OffscreenConfig,
    handlers: RefCell<Option<HostHandlers<P>>>,
}

impl<P: WorkerProtocol + 'static> WorkerHostPlugin<P> {
    /// A host with `config` and the handler invoked for every decoded
    /// application message, with whatever attachments rode the envelope.
    pub fn new(
        config: OffscreenConfig,
        on_message: impl FnMut(&mut World, P::Incoming, Attachments) + 'static,
    ) -> Self {
        Self {
            config,
            handlers: RefCell::new(Some(HostHandlers {
                on_message: Box::new(on_message),
                post_frame: Vec::new(),
            })),
        }
    }

    /// The [`new`](WorkerHostPlugin::new) form with the app's state scoped
    /// in: the handler keeps the plain `(state, world, message, attachments)`
    /// signature and the host applies [`game_scope`] per message. The state
    /// must be inserted as an app resource.
    pub fn new_scoped<T: Send + Sync + 'static>(
        config: OffscreenConfig,
        mut on_message: impl FnMut(&mut T, &mut World, P::Incoming, Attachments) + 'static,
    ) -> Self {
        Self::new(config, move |world, message, attachments| {
            game_scope(world, |state: &mut T, world| {
                on_message(state, world, message, attachments)
            });
        })
    }

    /// Adds a hook that runs after each frame's tick, before the outbox
    /// drains. For work that must observe the rendered frame, like flushing
    /// screenshot readbacks.
    pub fn with_post_frame(self, hook: impl FnMut(&mut World) + 'static) -> Self {
        if let Some(handlers) = self.handlers.borrow_mut().as_mut() {
            handlers.post_frame.push(Box::new(hook));
        }
        self
    }

    /// The [`with_post_frame`](WorkerHostPlugin::with_post_frame) form with
    /// the app's state scoped in.
    pub fn with_scoped_post_frame<T: Send + Sync + 'static>(
        self,
        mut hook: impl FnMut(&mut T, &mut World) + 'static,
    ) -> Self {
        self.with_post_frame(move |world| {
            game_scope(world, |state: &mut T, world| hook(state, world));
        })
    }
}

impl<P: WorkerProtocol + 'static> Plugin for WorkerHostPlugin<P> {
    fn build(&self, app: &mut App) {
        let handlers = self
            .handlers
            .borrow_mut()
            .take()
            .expect("WorkerHostPlugin can only be added once");
        app.insert_resource(WorkerOutbox::<P::Outgoing>::default());
        app.insert_resource(HostSelection::default());
        if self.config.camera_controllers {
            app.add_system(Stage::First, camera_controllers_system);
        }
        let config = self.config;
        app.set_runner(move |app| {
            run_worker::<P>(app, config, handlers);
            Ok(())
        });
    }
}

struct Host<P: WorkerProtocol> {
    world: World,
    renderer: WgpuRenderer,
    state: Box<dyn State>,
    config: OffscreenConfig,
    handlers: HostHandlers<P>,
}

struct PendingHost<P: WorkerProtocol> {
    world: World,
    state: Box<dyn State>,
    config: OffscreenConfig,
    handlers: HostHandlers<P>,
}

type HostSlot<P> = Rc<RefCell<Option<Host<P>>>>;
type Pending<P> = Rc<RefCell<Option<PendingHost<P>>>>;
type PendingMessages = Rc<RefCell<Vec<JsValue>>>;

fn run_worker<P: WorkerProtocol + 'static>(
    mut app: App,
    config: OffscreenConfig,
    handlers: HostHandlers<P>,
) {
    console_error_panic_hook::set_once();

    let log_guards = app.take_log_guards();
    LOG_GUARDS.with(|slot| *slot.borrow_mut() = log_guards);
    let (world, state) = app.into_parts();
    let pending: Pending<P> = Rc::new(RefCell::new(Some(PendingHost {
        world,
        state: Box::new(state),
        config,
        handlers,
    })));
    let host: HostSlot<P> = Rc::new(RefCell::new(None));
    let queued: PendingMessages = Rc::new(RefCell::new(Vec::new()));

    let scope: DedicatedWorkerGlobalScope = js_sys::global().unchecked_into();
    let handler_scope = scope.clone();
    let onmessage = Closure::<dyn FnMut(MessageEvent)>::new(move |event: MessageEvent| {
        handle_data(&handler_scope, &host, &queued, &pending, event.data());
    });
    scope.set_onmessage(Some(onmessage.as_ref().unchecked_ref()));
    onmessage.forget();
}

fn handle_data<P: WorkerProtocol + 'static>(
    scope: &DedicatedWorkerGlobalScope,
    host: &HostSlot<P>,
    queued: &PendingMessages,
    pending: &Pending<P>,
    data: JsValue,
) {
    let control = control_from(&data);

    if host.borrow().is_none() && !matches!(control, Some(ToWorker::Init { .. })) {
        queued.borrow_mut().push(data);
        return;
    }

    match control {
        Some(ToWorker::Init { width, height }) => {
            let Some(canvas) = canvas_from(&data) else {
                return;
            };
            let Some(parts) = pending.borrow_mut().take() else {
                return;
            };
            let scope = scope.clone();
            let host = host.clone();
            let queued = queued.clone();
            let pending = pending.clone();
            spawn_local(async move {
                let ready = create_host(canvas, width, height, parts).await;
                *host.borrow_mut() = Some(ready);
                let backlog = std::mem::take(&mut *queued.borrow_mut());
                for data in backlog {
                    handle_data(&scope, &host, &queued, &pending, data);
                }
                post_control(&FromWorker::Ready {
                    adapter: "WebGPU".to_string(),
                });
                start_render_loop(host);
            });
        }
        Some(ToWorker::Resize { width, height }) => {
            if let Some(host) = host.borrow_mut().as_mut() {
                let physical_width = (width as u32).max(1);
                let physical_height = (height as u32).max(1);
                resize_offscreen(
                    &mut host.world,
                    &mut host.renderer,
                    physical_width,
                    physical_height,
                );
                host.world.resources.window.active_viewport_rect =
                    Some(nightshade::render::config::ViewportRect {
                        x: 0.0,
                        y: 0.0,
                        width: physical_width as f32,
                        height: physical_height as f32,
                    });
            }
        }
        Some(message) => {
            if let Some(host) = host.borrow_mut().as_mut() {
                apply_control(host, message);
            }
        }
        None => {
            if let Some(host) = host.borrow_mut().as_mut()
                && let Some(message) = app_message_from::<P>(&data)
            {
                let attachments = attachments_from(&data);
                (host.handlers.on_message)(&mut host.world, message, attachments);
            }
        }
    }
}

fn apply_control<P: WorkerProtocol>(host: &mut Host<P>, message: ToWorker) {
    let world = &mut host.world;
    match message {
        ToWorker::PointerMove { x, y } => input_inject_cursor_moved(world, Vec2::new(x, y)),
        ToWorker::PointerMotion { dx, dy } => {
            input_inject_mouse_motion(world, Vec2::new(dx, dy));
        }
        ToWorker::PointerButton { button, pressed } => {
            let state = if pressed {
                KeyState::Pressed
            } else {
                KeyState::Released
            };
            input_inject_mouse_button(world, mouse_button(button), state);
        }
        ToWorker::Wheel { delta } => {
            input_inject_mouse_wheel(world, Vec2::new(0.0, -delta / 100.0))
        }
        ToWorker::Touch { id, phase, x, y } => {
            input_inject_touch(world, id, touch_phase(phase), Vec2::new(x, y));
        }
        ToWorker::Key {
            code,
            pressed,
            text,
        } => {
            if let Some(key_code) = key_code_from_dom(&code) {
                let state = if pressed {
                    KeyState::Pressed
                } else {
                    KeyState::Released
                };
                input_inject_keyboard(world, key_code, state, text.as_deref());
                world.resources.input.events.push(AppEvent::Keyboard {
                    key: key_code,
                    state,
                });
            }
        }
        ToWorker::Pick { x, y } => {
            let position = Vec2::new(x.max(0.0), y.max(0.0));
            input_inject_cursor_moved(world, position);
            match host.config.pick_mode {
                PickMode::CursorRay => {
                    let entity = entity_under_cursor(world);
                    if let Some(selection) = world.ecs.resource_mut::<HostSelection>() {
                        selection.0 = entity;
                    }
                    world.resources.selection.active_entity = entity;
                    world.resources.selection.entities = entity.into_iter().collect();
                    let detail = entity.map(|entity| SelectedEntity {
                        id: entity.id,
                        name: world
                            .get::<nightshade::ecs::primitives::Name>(entity)
                            .map(|name| name.0.clone())
                            .unwrap_or_default(),
                    });
                    post_control(&FromWorker::Selected { detail });
                }
                PickMode::Gpu => request_surface_pick(world, position),
                PickMode::Manual => {}
            }
        }
        ToWorker::Init { .. } | ToWorker::Resize { .. } => {}
    }
}

async fn create_host<P: WorkerProtocol>(
    canvas: OffscreenCanvas,
    width: f32,
    height: f32,
    parts: PendingHost<P>,
) -> Host<P> {
    let physical_width = (width as u32).max(1);
    let physical_height = (height as u32).max(1);

    HOST_CANVAS.with(|slot| *slot.borrow_mut() = Some(canvas.clone()));
    let surface_target = wgpu::SurfaceTarget::OffscreenCanvas(canvas);
    let mut renderer = create_wgpu_renderer(surface_target, physical_width, physical_height)
        .await
        .expect("failed to create renderer from offscreen canvas");

    let PendingHost {
        mut world,
        mut state,
        config,
        handlers,
    } = parts;
    initialize_offscreen(
        &mut world,
        state.as_mut(),
        &mut renderer,
        (physical_width, physical_height),
        1.0,
    );
    world.resources.window.active_viewport_rect = Some(nightshade::render::config::ViewportRect {
        x: 0.0,
        y: 0.0,
        width: physical_width as f32,
        height: physical_height as f32,
    });

    Host {
        world,
        renderer,
        state,
        config,
        handlers,
    }
}

fn start_render_loop<P: WorkerProtocol + 'static>(host: HostSlot<P>) {
    let last_push = Rc::new(RefCell::new(0.0_f64));

    spawn_animation_frame_loop(move || {
        if let Some(host) = host.borrow_mut().as_mut() {
            tick_offscreen(&mut host.world, host.state.as_mut(), &mut host.renderer);
            for hook in &mut host.handlers.post_frame {
                hook(&mut host.world);
            }
            drain_outbox::<P>(&mut host.world);
            let scope: DedicatedWorkerGlobalScope = js_sys::global().unchecked_into();
            if let Some(performance) = scope.performance() {
                let now = performance.now();
                let mut last = last_push.borrow_mut();
                if now - *last > 500.0 {
                    *last = now;
                    let entity_count = host.world.ecs.worlds[CORE]
                        .query_entities(
                            nightshade::ecs::world::LOCAL_TRANSFORM
                                | nightshade::ecs::world::GLOBAL_TRANSFORM,
                        )
                        .count() as u32;
                    post_control(&FromWorker::Stats {
                        fps: host.world.resources.window.timing.frames_per_second,
                        entity_count,
                    });
                }
            }
        }
    });
}

fn drain_outbox<P: WorkerProtocol>(world: &mut World) {
    let (messages, attachments) = {
        let Some(outbox) = world.ecs.resource_mut::<WorkerOutbox<P::Outgoing>>() else {
            return;
        };
        (
            std::mem::take(&mut outbox.messages),
            std::mem::take(&mut outbox.attachments),
        )
    };
    for message in &messages {
        post_app_message(message);
    }
    for (message, attachments) in &attachments {
        post_app_message_with_attachments(message, attachments);
    }
}

/// Posts an application message to the page over the [`APP_KEY`] envelope
/// field. For async callbacks with no world access; systems prefer the
/// [`WorkerOutbox`] resource.
pub fn post_app_message<Message: Serialize>(message: &Message) {
    let scope: DedicatedWorkerGlobalScope = js_sys::global().unchecked_into();
    if let Some(envelope) = envelope_with(APP_KEY, message) {
        drop(scope.post_message(&envelope));
    }
}

/// Posts an application message with named binary attachments, transferring
/// the attachment buffers.
pub fn post_app_message_with_attachments<Message: Serialize>(
    message: &Message,
    attachments: &[(String, Vec<u8>)],
) {
    let scope: DedicatedWorkerGlobalScope = js_sys::global().unchecked_into();
    let Some(envelope) = envelope_with(APP_KEY, message) else {
        return;
    };
    let transfer = js_sys::Array::new();
    if !attach(&envelope, &transfer, attachments) {
        return;
    }
    drop(scope.post_message_with_transfer(&envelope, &transfer));
}

/// Posts a control message to the page. Apps that pick outside
/// [`PickMode::CursorRay`] report the selection with
/// `post_control(&FromWorker::Selected { detail })`.
pub fn post_control(message: &FromWorker) {
    let scope: DedicatedWorkerGlobalScope = js_sys::global().unchecked_into();
    if let Some(envelope) = envelope_with(MESSAGE_KEY, message) {
        drop(scope.post_message(&envelope));
    }
}

/// Posts an application-defined message to the page as a JSON value, the
/// [`ValueProtocol`] form [`run_offscreen`] apps reply with.
pub fn post_custom<Message: Serialize>(message: &Message) {
    post_app_message(message);
}

/// Starts the worker in the closure form: `config` selects the camera and
/// picking behavior, `scene` is the app state, `setup` runs once with the
/// world ready, `tick` runs every frame, and `on_custom` receives each
/// decoded JSON message along with the current selection. Composes a
/// [`WorkerHostPlugin`] over [`ValueProtocol`] under the hood; apps with
/// their own plugins and message enums compose the plugin directly.
pub fn run_offscreen<Scene, Setup, Tick, OnCustom>(
    config: OffscreenConfig,
    scene: Scene,
    setup: Setup,
    tick: Tick,
    mut on_custom: OnCustom,
) where
    Scene: Send + Sync + 'static,
    Setup: FnOnce(&mut Scene, &mut World) + Send + 'static,
    Tick: FnMut(&mut Scene, &mut World) + Send + 'static,
    OnCustom: FnMut(&mut Scene, &mut World, Option<Entity>, Value) + 'static,
{
    let host = WorkerHostPlugin::<ValueProtocol>::new(config, move |world, value, _attachments| {
        let selected = world
            .ecs
            .resource::<HostSelection>()
            .and_then(|selection| selection.0);
        game_scope(world, |scene: &mut Scene, world| {
            on_custom(scene, world, selected, value);
        });
    });

    let mut setup = Some(setup);
    let mut app = App::new().add_plugin(host);
    app.insert_resource(scene);
    app.add_system(
        Stage::Startup,
        move |scene: &mut Scene, world: &mut World| {
            if let Some(setup) = setup.take() {
                setup(scene, world);
            }
        },
    );
    app.add_system(Stage::Update, tick);
    app.run().expect("offscreen worker failed to start");
}

fn control_from(data: &JsValue) -> Option<ToWorker> {
    serde_wasm_bindgen::from_value::<ToWorker>(control_value_from(data)?).ok()
}

fn app_message_from<P: WorkerProtocol>(data: &JsValue) -> Option<P::Incoming> {
    serde_wasm_bindgen::from_value::<P::Incoming>(app_value_from(data)?).ok()
}

fn mouse_button(button: u8) -> MouseButton {
    match button {
        1 => MouseButton::Middle,
        2 => MouseButton::Right,
        _ => MouseButton::Left,
    }
}

fn touch_phase(phase: crate::wire::TouchPhase) -> TouchPhase {
    match phase {
        crate::wire::TouchPhase::Started => TouchPhase::Started,
        crate::wire::TouchPhase::Moved => TouchPhase::Moved,
        crate::wire::TouchPhase::Ended => TouchPhase::Ended,
        crate::wire::TouchPhase::Cancelled => TouchPhase::Cancelled,
    }
}

fn canvas_from(data: &JsValue) -> Option<OffscreenCanvas> {
    js_sys::Reflect::get(data, &JsValue::from_str(CANVAS_KEY))
        .ok()
        .and_then(|value| value.dyn_into::<OffscreenCanvas>().ok())
}

/// The DOM `KeyboardEvent.code` to engine key code mapping the host injects
/// keyboard input through.
pub fn key_code_from_dom(code: &str) -> Option<KeyCode> {
    Some(match code {
        "KeyA" => KeyCode::KeyA,
        "KeyB" => KeyCode::KeyB,
        "KeyC" => KeyCode::KeyC,
        "KeyD" => KeyCode::KeyD,
        "KeyE" => KeyCode::KeyE,
        "KeyF" => KeyCode::KeyF,
        "KeyG" => KeyCode::KeyG,
        "KeyH" => KeyCode::KeyH,
        "KeyI" => KeyCode::KeyI,
        "KeyJ" => KeyCode::KeyJ,
        "KeyK" => KeyCode::KeyK,
        "KeyL" => KeyCode::KeyL,
        "KeyM" => KeyCode::KeyM,
        "KeyN" => KeyCode::KeyN,
        "KeyO" => KeyCode::KeyO,
        "KeyP" => KeyCode::KeyP,
        "KeyQ" => KeyCode::KeyQ,
        "KeyR" => KeyCode::KeyR,
        "KeyS" => KeyCode::KeyS,
        "KeyT" => KeyCode::KeyT,
        "KeyU" => KeyCode::KeyU,
        "KeyV" => KeyCode::KeyV,
        "KeyW" => KeyCode::KeyW,
        "KeyX" => KeyCode::KeyX,
        "KeyY" => KeyCode::KeyY,
        "KeyZ" => KeyCode::KeyZ,
        "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,
        "Escape" => KeyCode::Escape,
        "Enter" => KeyCode::Enter,
        "NumpadEnter" => KeyCode::NumpadEnter,
        "Tab" => KeyCode::Tab,
        "Space" => KeyCode::Space,
        "Delete" => KeyCode::Delete,
        "Backspace" => KeyCode::Backspace,
        "Home" => KeyCode::Home,
        "End" => KeyCode::End,
        "ArrowLeft" => KeyCode::ArrowLeft,
        "ArrowRight" => KeyCode::ArrowRight,
        "ArrowUp" => KeyCode::ArrowUp,
        "ArrowDown" => KeyCode::ArrowDown,
        "ShiftLeft" => KeyCode::ShiftLeft,
        "ShiftRight" => KeyCode::ShiftRight,
        "ControlLeft" => KeyCode::ControlLeft,
        "ControlRight" => KeyCode::ControlRight,
        "AltLeft" => KeyCode::AltLeft,
        "AltRight" => KeyCode::AltRight,
        "F1" => KeyCode::F1,
        "F2" => KeyCode::F2,
        "F3" => KeyCode::F3,
        "F4" => KeyCode::F4,
        "F5" => KeyCode::F5,
        "F6" => KeyCode::F6,
        "F7" => KeyCode::F7,
        "F8" => KeyCode::F8,
        "F9" => KeyCode::F9,
        "F10" => KeyCode::F10,
        "F11" => KeyCode::F11,
        "F12" => KeyCode::F12,
        "Comma" => KeyCode::Comma,
        "Period" => KeyCode::Period,
        "Minus" => KeyCode::Minus,
        "Equal" => KeyCode::Equal,
        _ => return None,
    })
}