|
| 1 | +#![allow(dead_code)] |
| 2 | + |
| 3 | +use crate::{create_server, create_world, World}; |
| 4 | +use futures::{Future, Sink}; |
| 5 | +use lsp_async_stub::{rpc::Message, Server}; |
| 6 | +use once_cell::sync::Lazy; |
| 7 | +use std::{io, task::Poll}; |
| 8 | +use tracing::trace; |
| 9 | +use wasm_bindgen::prelude::*; |
| 10 | +use wasm_bindgen_futures::spawn_local; |
| 11 | + |
| 12 | +static SERVER: Lazy<Server<World>> = Lazy::new(|| create_server()); |
| 13 | +static WORLD: Lazy<World> = Lazy::new(|| create_world()); |
| 14 | + |
| 15 | +#[wasm_bindgen] |
| 16 | +extern { |
| 17 | + #[wasm_bindgen(js_namespace = __rhai__, js_name = onMessage)] |
| 18 | + fn js_send_message(message: JsValue); |
| 19 | +} |
| 20 | + |
| 21 | +#[cfg(feature = "wasm-export")] |
| 22 | +#[wasm_bindgen] |
| 23 | +pub async fn initialize() { |
| 24 | + console_error_panic_hook::set_once(); |
| 25 | + tracing_wasm::set_as_global_default(); |
| 26 | +} |
| 27 | + |
| 28 | +#[cfg(feature = "wasm-export")] |
| 29 | +#[wasm_bindgen] |
| 30 | +pub fn message(message: JsValue) { |
| 31 | + trace!(?message, "received message"); |
| 32 | + let msg = message.into_serde().unwrap(); |
| 33 | + spawn(async move { |
| 34 | + SERVER |
| 35 | + .handle_message(WORLD.clone(), msg, MessageWriter) |
| 36 | + .await |
| 37 | + .unwrap(); |
| 38 | + }); |
| 39 | +} |
| 40 | + |
| 41 | +pub(crate) fn spawn<F: Future<Output = ()> + 'static>(fut: F) { |
| 42 | + spawn_local(fut) |
| 43 | +} |
| 44 | + |
| 45 | +#[derive(Clone)] |
| 46 | +struct MessageWriter; |
| 47 | + |
| 48 | +impl Sink<Message> for MessageWriter { |
| 49 | + type Error = io::Error; |
| 50 | + |
| 51 | + fn poll_ready( |
| 52 | + self: std::pin::Pin<&mut Self>, |
| 53 | + _cx: &mut std::task::Context<'_>, |
| 54 | + ) -> Poll<Result<(), Self::Error>> { |
| 55 | + Poll::Ready(Ok(())) |
| 56 | + } |
| 57 | + |
| 58 | + fn start_send(self: std::pin::Pin<&mut Self>, item: Message) -> Result<(), Self::Error> { |
| 59 | + let js_msg = JsValue::from_serde(&item).unwrap(); |
| 60 | + trace!(message = ?js_msg, "sending message"); |
| 61 | + js_send_message(js_msg); |
| 62 | + Ok(()) |
| 63 | + } |
| 64 | + |
| 65 | + fn poll_flush( |
| 66 | + self: std::pin::Pin<&mut Self>, |
| 67 | + _cx: &mut std::task::Context<'_>, |
| 68 | + ) -> std::task::Poll<Result<(), Self::Error>> { |
| 69 | + Poll::Ready(Ok(())) |
| 70 | + } |
| 71 | + |
| 72 | + fn poll_close( |
| 73 | + self: std::pin::Pin<&mut Self>, |
| 74 | + _cx: &mut std::task::Context<'_>, |
| 75 | + ) -> std::task::Poll<Result<(), Self::Error>> { |
| 76 | + Poll::Ready(Ok(())) |
| 77 | + } |
| 78 | +} |
0 commit comments