From 871263528d33a39b18c89e3baa63513fad600931 Mon Sep 17 00:00:00 2001 From: Mingwei Samuel Date: Thu, 5 Sep 2024 10:29:09 -0700 Subject: [PATCH] call global javascript function from rust (ugly) --- wasm_test_site/src/lib.rs | 8 +++++++- wasm_test_site/www/index.ts | 6 ++++++ wasm_test_site/www/package-lock.json | 10 ++-------- wasm_test_site/www/package.json | 2 +- 4 files changed, 16 insertions(+), 10 deletions(-) diff --git a/wasm_test_site/src/lib.rs b/wasm_test_site/src/lib.rs index 4ccae815119..2384e595a19 100644 --- a/wasm_test_site/src/lib.rs +++ b/wasm_test_site/src/lib.rs @@ -4,6 +4,12 @@ fn log(string: impl AsRef) { web_sys::console::log_1(&JsValue::from_str(string.as_ref())); } +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(js_namespace = window)] + fn writeToDom(s: &str); +} + #[wasm_bindgen] pub fn greet() { console_error_panic_hook::set_once(); @@ -17,7 +23,7 @@ pub fn test_hydroflow() -> web_sys::js_sys::Promise { let mut df = hydroflow::hydroflow_syntax! { // https://hydro.run/docs/hydroflow/quickstart/example_1_simplest - source_iter(0..10) -> for_each(|n| log(format!("Hello {}", n))); + source_iter(0..10) -> for_each(|n| writeToDom(&format!("Hello {}", n))); }; wasm_bindgen_futures::future_to_promise(async move { diff --git a/wasm_test_site/www/index.ts b/wasm_test_site/www/index.ts index 31168be73a8..fcc5ed43643 100644 --- a/wasm_test_site/www/index.ts +++ b/wasm_test_site/www/index.ts @@ -1,4 +1,10 @@ import init, { greet, test_hydroflow } from "wasm_test_site"; let { memory } = await init(); + +(window as any).writeToDom = function(str: string) { + document.body.appendChild(document.createTextNode(str)); + document.body.append(document.createElement('br')); +}; + greet(); test_hydroflow(); diff --git a/wasm_test_site/www/package-lock.json b/wasm_test_site/www/package-lock.json index a6fa21bb31f..4d37c875cc2 100644 --- a/wasm_test_site/www/package-lock.json +++ b/wasm_test_site/www/package-lock.json @@ -8,9 +8,6 @@ "name": "create-wasm-app", "version": "0.1.0", "license": "(MIT OR Apache-2.0)", - "dependencies": { - "wasm_test_site": "file:../pkg" - }, "devDependencies": { "typescript": "^4.9.5", "vite": "^4.1.4", @@ -20,7 +17,8 @@ }, "../pkg": { "name": "wasm_test_site", - "version": "0.1.0" + "version": "0.1.0", + "extraneous": true }, "node_modules/@esbuild/win32-x64": { "version": "0.16.17", @@ -1084,10 +1082,6 @@ "fs-extra": "^10.0.0", "narrowing": "^1.4.0" } - }, - "node_modules/wasm_test_site": { - "resolved": "../pkg", - "link": true } } } diff --git a/wasm_test_site/www/package.json b/wasm_test_site/www/package.json index 0b2a75af9d9..51c26c38cab 100644 --- a/wasm_test_site/www/package.json +++ b/wasm_test_site/www/package.json @@ -27,4 +27,4 @@ "vite-plugin-html": "^3.2.0", "vite-plugin-wasm-pack": "^0.1.12" } -} +} \ No newline at end of file