1
1
use css_inline as rust_inline;
2
2
use wasm_bindgen:: prelude:: * ;
3
3
use std:: borrow:: Cow ;
4
+ use std:: convert:: TryFrom ;
5
+ use std:: convert:: TryInto ;
4
6
5
7
struct InlineErrorWrapper ( rust_inline:: InlineError ) ;
6
8
@@ -26,22 +28,63 @@ fn parse_url(url: Option<String>) -> Result<Option<url::Url>, JsValue> {
26
28
} )
27
29
}
28
30
31
+ #[ macro_use]
32
+ extern crate serde_derive;
33
+
34
+ #[ derive( Deserialize ) ]
35
+ #[ serde( default ) ]
36
+ pub struct Options {
37
+ inline_style_tags : bool ,
38
+ remove_style_tags : bool ,
39
+ base_url : Option < String > ,
40
+ load_remote_stylesheets : bool ,
41
+ extra_css : Option < String > ,
42
+ }
43
+
44
+ impl Default for Options {
45
+ fn default ( ) -> Self {
46
+ Options {
47
+ inline_style_tags : true ,
48
+ remove_style_tags : false ,
49
+ base_url : None ,
50
+ load_remote_stylesheets : true ,
51
+ extra_css : None ,
52
+ }
53
+ }
54
+ }
55
+
56
+ struct SerdeError ( serde_json:: Error ) ;
57
+
58
+ impl From < SerdeError > for JsValue {
59
+ fn from ( error : SerdeError ) -> Self {
60
+ JsValue :: from_str ( error. 0 . to_string ( ) . as_str ( ) )
61
+ }
62
+ }
63
+
64
+ impl TryFrom < Options > for rust_inline:: InlineOptions < ' _ > {
65
+ type Error = JsValue ;
66
+
67
+ fn try_from ( value : Options ) -> Result < Self , Self :: Error > {
68
+ Ok ( rust_inline:: InlineOptions {
69
+ inline_style_tags : value. inline_style_tags ,
70
+ remove_style_tags : value. remove_style_tags ,
71
+ base_url : parse_url ( value. base_url ) ?,
72
+ load_remote_stylesheets : value. load_remote_stylesheets ,
73
+ extra_css : value. extra_css . map ( Cow :: Owned ) ,
74
+ } )
75
+ }
76
+ }
77
+
29
78
#[ wasm_bindgen]
30
79
pub fn inline (
31
80
html : & str ,
32
- inline_style_tags : Option < bool > ,
33
- remove_style_tags : Option < bool > ,
34
- base_url : Option < String > ,
35
- load_remote_stylesheets : Option < bool > ,
36
- extra_css : Option < String > ,
81
+ options : JsValue ,
37
82
) -> Result < String , JsValue > {
38
- let options = rust_inline:: InlineOptions {
39
- inline_style_tags : inline_style_tags. unwrap_or ( true ) ,
40
- remove_style_tags : remove_style_tags. unwrap_or ( false ) ,
41
- base_url : parse_url ( base_url) ?,
42
- load_remote_stylesheets : load_remote_stylesheets. unwrap_or ( true ) ,
43
- extra_css : extra_css. map ( Cow :: Owned ) ,
83
+ let options: Options = if !options. is_undefined ( ) {
84
+ options. into_serde ( ) . map_err ( SerdeError ) ?
85
+ } else {
86
+ Options :: default ( )
44
87
} ;
45
- let inliner = rust_inline:: CSSInliner :: new ( options) ;
88
+ let inliner = rust_inline:: CSSInliner :: new ( options. try_into ( ) ? ) ;
46
89
Ok ( inliner. inline ( html) . map_err ( InlineErrorWrapper ) ?)
47
90
}
0 commit comments