1
1
#[ macro_use]
2
2
extern crate cfg_if;
3
-
3
+ extern crate web_sys ;
4
4
extern crate wasm_bindgen;
5
+
5
6
use wasm_bindgen:: prelude:: * ;
6
7
7
8
cfg_if ! {
@@ -10,6 +11,9 @@ cfg_if! {
10
11
if #[ cfg( feature = "console_error_panic_hook" ) ] {
11
12
extern crate console_error_panic_hook;
12
13
use console_error_panic_hook:: set_once as set_panic_hook;
14
+ } else {
15
+ #[ inline]
16
+ fn set_panic_hook( ) { }
13
17
}
14
18
}
15
19
@@ -23,36 +27,20 @@ cfg_if! {
23
27
}
24
28
}
25
29
26
- // Definitions of the functionality available in JS, which wasm-bindgen will
27
- // generate shims for today (and eventually these should be near-0 cost!)
28
- //
29
- // These definitions need to be hand-written today but the current vision is
30
- // that we'll use WebIDL to generate this `extern` block into a crate which you
31
- // can link and import. There's a tracking issue for this at
32
- // https://github.com/rustwasm/wasm-bindgen/issues/42
33
- //
34
- // In the meantime these are written out by hand and correspond to the names and
35
- // signatures documented on MDN, for example
30
+ // Called by our JS entry point to run the example.
36
31
#[ wasm_bindgen]
37
- extern "C" {
38
- type HTMLDocument ;
39
- static document: HTMLDocument ;
40
- #[ wasm_bindgen( method) ]
41
- fn createElement ( this : & HTMLDocument , tagName : & str ) -> Element ;
42
- #[ wasm_bindgen( method, getter) ]
43
- fn body ( this : & HTMLDocument ) -> Element ;
44
-
45
- type Element ;
46
- #[ wasm_bindgen( method, setter = innerHTML) ]
47
- fn set_inner_html ( this : & Element , html : & str ) ;
48
- #[ wasm_bindgen( method, js_name = appendChild) ]
49
- fn append_child ( this : & Element , other : Element ) ;
50
- }
32
+ pub fn run ( ) -> Result < ( ) , JsValue > {
33
+ set_panic_hook ( ) ;
51
34
52
- // Called by our JS entry point to run the example
53
- #[ wasm_bindgen]
54
- pub fn run ( ) {
55
- let val = document. createElement ( "p" ) ;
56
- val. set_inner_html ( "Hello from Rust, WebAssembly, and Webpack!" ) ;
57
- document. body ( ) . append_child ( val) ;
35
+ let window = web_sys:: window ( ) . expect ( "should have a Window" ) ;
36
+ let document = window. document ( ) . expect ( "should have a Document" ) ;
37
+
38
+ let p: web_sys:: Node = document. create_element ( "p" ) ?. into ( ) ;
39
+ p. set_text_content ( Some ( "Hello from Rust, WebAssembly, and Webpack!" ) ) ;
40
+
41
+ let body = document. body ( ) . expect ( "should have a body" ) ;
42
+ let body: & web_sys:: Node = body. as_ref ( ) ;
43
+ body. append_child ( & p) ?;
44
+
45
+ Ok ( ( ) )
58
46
}
0 commit comments