Skip to main content

yaiko_core/
image.rs

1//! Image optimization metadata and deterministic responsive HTML rendering.
2use std::collections::BTreeSet;
3#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
4pub enum ImageFormat {
5    Webp,
6    Avif,
7}
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum Loading {
10    Lazy,
11    Eager,
12}
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum ImageError {
15    InvalidSource,
16    InvalidDimensions,
17    InvalidWidth,
18}
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Image {
21    pub src: String,
22    pub alt: String,
23    pub width: u32,
24    pub height: u32,
25    pub formats: BTreeSet<ImageFormat>,
26    pub responsive: BTreeSet<u32>,
27    pub loading: Loading,
28}
29impl Image {
30    pub fn new(
31        src: impl Into<String>,
32        alt: impl Into<String>,
33        width: u32,
34        height: u32,
35    ) -> Result<Self, ImageError> {
36        let src = src.into();
37        let alt = alt.into();
38        if !src.starts_with('/') && !src.starts_with("https://") {
39            return Err(ImageError::InvalidSource);
40        }
41        if width == 0 || height == 0 || width > 8192 || height > 8192 {
42            return Err(ImageError::InvalidDimensions);
43        }
44        Ok(Self {
45            src,
46            alt,
47            width,
48            height,
49            formats: BTreeSet::new(),
50            responsive: BTreeSet::new(),
51            loading: Loading::Lazy,
52        })
53    }
54    pub fn format(mut self, f: ImageFormat) -> Self {
55        self.formats.insert(f);
56        self
57    }
58    pub fn responsive(mut self, w: u32) -> Result<Self, ImageError> {
59        if w == 0 || w > 8192 {
60            return Err(ImageError::InvalidWidth);
61        }
62        self.responsive.insert(w);
63        Ok(self)
64    }
65    pub fn loading(mut self, l: Loading) -> Self {
66        self.loading = l;
67        self
68    }
69    pub fn render(&self) -> String {
70        let mut s = format!(
71            "<img src=\"{}\" alt=\"{}\" width=\"{}\" height=\"{}\" loading=\"{}\"",
72            esc(&self.src),
73            esc(&self.alt),
74            self.width,
75            self.height,
76            match self.loading {
77                Loading::Lazy => "lazy",
78                Loading::Eager => "eager",
79            }
80        );
81        if !self.responsive.is_empty() {
82            let widths = self
83                .responsive
84                .iter()
85                .map(|w| format!("{}w", w))
86                .collect::<Vec<_>>()
87                .join(",");
88            s.push_str(&format!(" srcset=\"{}\" sizes=\"100vw\"", widths))
89        }
90        s.push_str(" />");
91        s
92    }
93}
94fn esc(x: &str) -> String {
95    x.replace('&', "&amp;")
96        .replace('"', "&quot;")
97        .replace('<', "&lt;")
98}
99#[cfg(test)]
100mod tests {
101    use super::*;
102    #[test]
103    fn renders_optimized_responsive_image() {
104        let i = Image::new("/hero.jpg", "Hero", 1200, 800)
105            .unwrap()
106            .format(ImageFormat::Webp)
107            .format(ImageFormat::Avif)
108            .responsive(640)
109            .unwrap()
110            .responsive(1200)
111            .unwrap();
112        let o = i.render();
113        assert!(o.contains("loading=\"lazy\""));
114        assert!(o.contains("640w,1200w"))
115    }
116    #[test]
117    fn validates_sources_dimensions_and_widths() {
118        assert_eq!(
119            Image::new("http://bad", "x", 1, 1),
120            Err(ImageError::InvalidSource)
121        );
122        assert_eq!(
123            Image::new("/x", "x", 0, 1),
124            Err(ImageError::InvalidDimensions)
125        );
126        assert_eq!(
127            Image::new("/x", "x", 1, 1).unwrap().responsive(9000),
128            Err(ImageError::InvalidWidth)
129        )
130    }
131}