I'd like to convert text-area value into the Markdown, I successfully managed to display pure text from text-area into output container however I stuck on binding parser inside closure, so how could I use properly parser and convert new text and display in output container?
lib.rs
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::{Document};
use pulldown_cmark::{html, Options, Parser};
#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
let window = web_sys::window().expect("should have a window in this context");
let document = window.document().expect("window should have a document");
setup_preview(&document);
Ok(())
}
pub fn get_value(target: &web_sys::EventTarget) -> String {
if let Some(input) = target.dyn_ref::<web_sys::HtmlTextAreaElement>() {
return input.value();
}
"".into()
}
fn setup_preview(document: &Document) {
let input = document.query_selector("textarea").unwrap().unwrap();
let output = document.query_selector("output").unwrap().unwrap();
let text: &str = "### Init";
let parser = Parser::new_ext(text, Options::empty());
let mut html_output_buf = String::new();
html::push_html(&mut html_output_buf, parser);
output.set_inner_html(&html_output_buf);
let a = Closure::wrap(Box::new(move |event: web_sys::KeyboardEvent| {
let val = get_value(&event.target().unwrap());
let mut new_html_output_buf: String = String::with_capacity(val.len() * 3 / 2);
html::push_html(&mut new_html_output_buf, parser); // <-- bad line here :(
output.set_inner_html(&new_html_output_buf);
}) as Box<dyn FnMut(_)>);
input.add_event_listener_with_callback("keydown", a.as_ref().unchecked_ref()).unwrap();
a.forget();
}
Html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Example</title>
</head>
<body>
<main>
<textarea autofocus="autofocus" id="editor"></textarea>
<output></output>
</main>
<script src="index.js"></script>
</body>
</html>
Cargo.toml
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
js-sys = "0.3"
pulldown-cmark = "0.8.0"
[dependencies.web-sys]
version = "0.3"
features = ["Window", "Document", "KeyboardEvent", "HtmlTextAreaElement"]