diff options
Diffstat (limited to 'src/style/font/web.rs')
-rw-r--r-- | src/style/font/web.rs | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/style/font/web.rs b/src/style/font/web.rs new file mode 100644 index 0000000..e70e7b1 --- /dev/null +++ b/src/style/font/web.rs @@ -0,0 +1,46 @@ +use super::{FontData, FontFamily, FontStyle, LayoutBox}; +use wasm_bindgen::JsCast; +use web_sys::{window, HtmlElement}; + +#[derive(Debug, Clone)] +pub enum FontError { + UnknownError, +} + +impl std::fmt::Display for FontError { + fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { + match self { + _ => write!(fmt, "Unknown error"), + } + } +} + +impl std::error::Error for FontError {} + +#[derive(Clone)] +pub struct FontDataInternal(String, String); + +impl FontData for FontDataInternal { + type ErrorType = FontError; + fn new(family: FontFamily, style: FontStyle) -> Result<Self, FontError> { + Ok(FontDataInternal( + family.as_str().into(), + style.as_str().into(), + )) + } + fn estimate_layout(&self, size: f64, text: &str) -> Result<LayoutBox, Self::ErrorType> { + let window = window().unwrap(); + let document = window.document().unwrap(); + let body = document.body().unwrap(); + let span = document.create_element("span").unwrap(); + span.set_text_content(Some(text)); + span.set_attribute("style", &format!("display: inline-block; font-family:{}; font-size: {}px; position: fixed; top: 100%", self.0, size)).unwrap(); + let span = span.into(); + body.append_with_node_1(&span).unwrap(); + let elem = JsCast::dyn_into::<HtmlElement>(span).unwrap(); + let height = elem.offset_height() as i32; + let width = elem.offset_width() as i32; + elem.remove(); + Ok(((0, 0), (width, height))) + } +} |