Skip to main content

freya_html/
content.rs

1use std::borrow::Cow;
2
3use url::{
4    ParseError,
5    Url,
6};
7
8/// Inline HTML and its optional base URL for resolving relative resources and links.
9/// Static HTML is borrowed, while dynamically generated HTML is owned.
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct HtmlContent {
12    pub(crate) html: Cow<'static, str>,
13    pub(crate) base_url: Option<Url>,
14}
15
16impl HtmlContent {
17    pub fn new(html: impl Into<Cow<'static, str>>) -> Self {
18        Self {
19            html: html.into(),
20            base_url: None,
21        }
22    }
23
24    /// Sets an absolute base URL, rejecting malformed URLs and opaque URLs such as `data:`.
25    pub fn with_base_url(mut self, base_url: impl AsRef<str>) -> Result<Self, ParseError> {
26        let base_url = Url::parse(base_url.as_ref())?;
27        if base_url.cannot_be_a_base() {
28            return Err(ParseError::RelativeUrlWithCannotBeABaseBase);
29        }
30
31        self.base_url = Some(base_url);
32        Ok(self)
33    }
34}
35
36impl<T: Into<Cow<'static, str>>> From<T> for HtmlContent {
37    fn from(html: T) -> Self {
38        Self::new(html)
39    }
40}