Skip to content

Commit 434e4fd

Browse files
authored
Fix up wasm-bindgen glue for POC (#17)
1 parent 8bb37b3 commit 434e4fd

File tree

2 files changed

+39
-6
lines changed

2 files changed

+39
-6
lines changed

crates/wasm-qmd-parser/pkg/index.html

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
import main from "./wasm_qmd_parser.js";
88
let m = await main();
99
debugger;
10-
m.parse_qmd("# Hello");
10+
let parsed = m.parse_qmd("# Hello\n");
11+
console.log(parsed);
1112
</script>
1213
</head>
1314
<body>

crates/wasm-qmd-parser/src/lib.rs

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ pub mod c_shim;
1212

1313
mod utils;
1414

15-
use std::io;
15+
use std::{io, panic};
1616

1717
use quarto_markdown_pandoc::readers::qmd;
1818
use quarto_markdown_pandoc::utils::output::VerboseOutput;
@@ -29,11 +29,43 @@ pub fn greet() {
2929
alert("Hello, wasm-qmd-parser!");
3030
}
3131

32+
#[wasm_bindgen(start)]
33+
pub fn run() {
34+
// Set a panic hook on program start that prints panics to the console
35+
panic::set_hook(Box::new(console_error_panic_hook::hook));
36+
}
37+
3238
#[wasm_bindgen]
33-
pub fn parse_qmd(input: &str) -> String {
39+
pub fn parse_qmd(input: JsValue) -> JsValue {
3440
let mut output = VerboseOutput::Sink(io::sink());
35-
let result = qmd::read(input.as_bytes(), &mut output).unwrap();
41+
42+
let input = match input.as_string() {
43+
Some(input) => input,
44+
None => panic!("Unable to parse `input` as a `String`."),
45+
};
46+
47+
let result = match qmd::read(input.as_bytes(), &mut output) {
48+
Ok(result) => result,
49+
Err(err) => panic!("Unable to read as a qmd:\n{}", err.join("\n")),
50+
};
51+
3652
let mut buf = Vec::new();
37-
let _ = json::write(&result, &mut buf).unwrap();
38-
String::from_utf8(buf).unwrap()
53+
54+
match json::write(&result, &mut buf) {
55+
Ok(_) => {
56+
// Nothing to do
57+
}
58+
Err(err) => {
59+
panic!("Unable to write as json: {:?}", err)
60+
}
61+
}
62+
63+
let json = match String::from_utf8(buf) {
64+
Ok(json) => json,
65+
Err(err) => {
66+
panic!("Unable to convert json to string: {:?}", err)
67+
}
68+
};
69+
70+
JsValue::from_str(&json)
3971
}

0 commit comments

Comments
 (0)