Skip to content

Commit 8966ae2

Browse files
cheapsteakStranger6667
authored andcommitted
feat: wasm
Signed-off-by: Chang Wang <[email protected]>
1 parent 85c17f6 commit 8966ae2

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
# will have compiled files and executables
33
/target/
44

5+
wasm/target
6+
57
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
68
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
79
Cargo.lock

wasm/Cargo.toml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
[package]
2+
name = "css-inline-wasm"
3+
version = "0.3.0"
4+
authors = ["Dmitry Dygalo <[email protected]>"]
5+
edition = "2018"
6+
7+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
8+
9+
[lib]
10+
name = "css_inline"
11+
crate-type = ["cdylib"]
12+
13+
[dependencies.css-inline]
14+
path = ".."
15+
version = "= 0.3.3"
16+
default-features = false
17+
18+
[dependencies]
19+
url = "2"
20+
wasm-bindgen = "0.2"

wasm/src/lib.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
use css_inline as rust_inline;
2+
use wasm_bindgen::prelude::*;
3+
use std::borrow::Cow;
4+
5+
struct InlineErrorWrapper(rust_inline::InlineError);
6+
7+
impl From<InlineErrorWrapper> for JsValue {
8+
fn from(error: InlineErrorWrapper) -> Self {
9+
JsValue::from_str(error.0.to_string().as_str())
10+
}
11+
}
12+
13+
struct UrlError(url::ParseError);
14+
15+
impl From<UrlError> for JsValue {
16+
fn from(error: UrlError) -> Self {
17+
wasm_bindgen::throw_str(&error.0.to_string())
18+
}
19+
}
20+
21+
fn parse_url(url: Option<String>) -> Result<Option<url::Url>, JsValue> {
22+
Ok(if let Some(url) = url {
23+
Some(url::Url::parse(url.as_str()).map_err(UrlError)?)
24+
} else {
25+
None
26+
})
27+
}
28+
29+
#[wasm_bindgen]
30+
pub fn inline(
31+
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>,
37+
) -> 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),
44+
};
45+
let inliner = rust_inline::CSSInliner::new(options);
46+
Ok(inliner.inline(html).map_err(InlineErrorWrapper)?)
47+
}

0 commit comments

Comments
 (0)