Skip to content

Commit

Permalink
call global javascript function from rust (ugly)
Browse files Browse the repository at this point in the history
  • Loading branch information
MingweiSamuel committed Sep 5, 2024
1 parent 5b8ed84 commit 0af83db
Show file tree
Hide file tree
Showing 5 changed files with 18 additions and 10 deletions.
3 changes: 3 additions & 0 deletions wasm_test_site/shim.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
function writeToDom(str) {
document.body.appendChild(str);
}
7 changes: 6 additions & 1 deletion wasm_test_site/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ fn log(string: impl AsRef<str>) {
web_sys::console::log_1(&JsValue::from_str(string.as_ref()));
}

#[wasm_bindgen(module = "/shim.js")]
extern "C" {
fn writeToDom(s: String);
}

#[wasm_bindgen]
pub fn greet() {
console_error_panic_hook::set_once();
Expand All @@ -17,7 +22,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 {
Expand Down
6 changes: 6 additions & 0 deletions wasm_test_site/www/index.ts
Original file line number Diff line number Diff line change
@@ -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();
10 changes: 2 additions & 8 deletions wasm_test_site/www/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion wasm_test_site/www/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@
"vite-plugin-html": "^3.2.0",
"vite-plugin-wasm-pack": "^0.1.12"
}
}
}

0 comments on commit 0af83db

Please sign in to comment.