11use css_inline as rust_inline;
22use wasm_bindgen:: prelude:: * ;
33use std:: borrow:: Cow ;
4+ use std:: convert:: TryFrom ;
5+ use std:: convert:: TryInto ;
46
57struct InlineErrorWrapper ( rust_inline:: InlineError ) ;
68
@@ -26,22 +28,63 @@ fn parse_url(url: Option<String>) -> Result<Option<url::Url>, JsValue> {
2628 } )
2729}
2830
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+
2978#[ wasm_bindgen]
3079pub fn inline (
3180 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 ,
3782) -> 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 ( )
4487 } ;
45- let inliner = rust_inline:: CSSInliner :: new ( options) ;
88+ let inliner = rust_inline:: CSSInliner :: new ( options. try_into ( ) ? ) ;
4689 Ok ( inliner. inline ( html) . map_err ( InlineErrorWrapper ) ?)
4790}
0 commit comments