mod optimize;
mod route;
pub use optimize::{
optimize, EncodedFormat, FormatPreference, OptimizeError, OptimizeResult, Optimized,
ResizeTarget,
};
pub use route::ImagePlugin;
pub const DEFAULT_QUALITY: u8 = 75;
pub const MAX_DIMENSION: u32 = 4096;
const FILL_FALLBACK_WIDTH: u32 = 1920;
const SRCSET_BREAKPOINTS: &[u32] = &[320, 420, 640, 750, 828, 1080, 1200, 1920, 2560, 3840];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Loading {
#[default]
Lazy,
Eager,
}
impl Loading {
fn as_str(self) -> &'static str {
match self {
Loading::Lazy => "lazy",
Loading::Eager => "eager",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Placeholder {
#[default]
Empty,
Blur,
}
#[derive(Debug, Clone)]
pub struct ImageOptions {
pub src: String,
pub width: Option<u32>,
pub height: Option<u32>,
pub alt: String,
pub quality: u8,
pub fill: bool,
pub sizes: Option<String>,
pub priority: bool,
pub placeholder: Placeholder,
pub loading: Loading,
pub unoptimized: bool,
}
impl ImageOptions {
pub fn new(src: impl Into<String>, width: u32, height: u32) -> Self {
Self {
src: src.into(),
width: Some(width),
height: Some(height),
alt: String::new(),
quality: DEFAULT_QUALITY,
fill: false,
sizes: None,
priority: false,
placeholder: Placeholder::default(),
loading: Loading::default(),
unoptimized: false,
}
}
pub fn fill(src: impl Into<String>) -> Self {
Self {
src: src.into(),
width: None,
height: None,
alt: String::new(),
quality: DEFAULT_QUALITY,
fill: true,
sizes: None,
priority: false,
placeholder: Placeholder::default(),
loading: Loading::default(),
unoptimized: false,
}
}
pub fn alt(mut self, alt: impl Into<String>) -> Self {
self.alt = alt.into();
self
}
pub fn quality(mut self, quality: u8) -> Self {
self.quality = quality;
self
}
pub fn sizes(mut self, sizes: impl Into<String>) -> Self {
self.sizes = Some(sizes.into());
self
}
pub fn priority(mut self) -> Self {
self.priority = true;
self.loading = Loading::Eager;
self
}
pub fn placeholder(mut self, placeholder: Placeholder) -> Self {
self.placeholder = placeholder;
self
}
pub fn loading(mut self, loading: Loading) -> Self {
self.loading = loading;
self
}
pub fn unoptimized(mut self) -> Self {
self.unoptimized = true;
self
}
}
pub fn optimized_url(src: &str, width: u32, height: Option<u32>, quality: u8) -> String {
match height {
Some(height) => format!(
"/__larust_image/optimize?src={}&w={width}&h={height}&q={quality}",
percent_encode(src)
),
None => format!(
"/__larust_image/optimize?src={}&w={width}&q={quality}",
percent_encode(src)
),
}
}
pub fn build_srcset(src: &str, quality: u8) -> String {
SRCSET_BREAKPOINTS
.iter()
.filter(|&&width| width <= MAX_DIMENSION)
.map(|&width| format!("{} {width}w", optimized_url(src, width, None, quality)))
.collect::<Vec<_>>()
.join(", ")
}
pub fn tag(options: &ImageOptions) -> String {
let loading = if options.priority {
Loading::Eager
} else {
options.loading
};
let mut style = String::new();
if options.fill {
style.push_str("position:absolute;inset:0;width:100%;height:100%;object-fit:cover;");
}
if options.placeholder == Placeholder::Blur {
if let Some(data_uri) = route::read_blur_data_uri(&options.src) {
style.push_str(&format!(
"background-image:url({data_uri});background-size:cover;background-position:50% 50%;"
));
}
}
let src_url = if options.unoptimized {
format!("/{}", options.src.trim_start_matches('/'))
} else {
let fallback_width = options.width.unwrap_or(FILL_FALLBACK_WIDTH);
optimized_url(
&options.src,
fallback_width,
options.height,
options.quality,
)
};
let srcset = (!options.unoptimized)
.then_some(options.sizes.as_ref())
.flatten()
.map(|sizes| (build_srcset(&options.src, options.quality), sizes));
let mut html = String::new();
if options.priority {
html.push_str("<link rel=\"preload\" as=\"image\"");
push_attr(&mut html, "href", &src_url);
if let Some((set, sizes)) = &srcset {
push_attr(&mut html, "imagesrcset", set);
push_attr(&mut html, "imagesizes", sizes);
}
html.push_str(" fetchpriority=\"high\">");
}
html.push_str("<img");
push_attr(&mut html, "src", &src_url);
if let Some((set, sizes)) = &srcset {
push_attr(&mut html, "srcset", set);
push_attr(&mut html, "sizes", sizes);
}
if let Some(width) = options.width {
html.push_str(&format!(r#" width="{width}""#));
}
if let Some(height) = options.height {
html.push_str(&format!(r#" height="{height}""#));
}
push_attr(&mut html, "alt", &options.alt);
push_attr(&mut html, "loading", loading.as_str());
if options.priority {
html.push_str(r#" fetchpriority="high""#);
}
html.push_str(r#" decoding="async""#);
if !style.is_empty() {
push_attr(&mut html, "style", &style);
}
html.push('>');
html
}
fn push_attr(html: &mut String, name: &str, value: &str) {
html.push_str(&format!(r#" {name}="{}""#, escape_attr(value)));
}
fn escape_attr(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for ch in value.chars() {
match ch {
'&' => out.push_str("&"),
'"' => out.push_str("""),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
other => out.push(other),
}
}
out
}
fn percent_encode(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for byte in value.as_bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
out.push(*byte as char);
}
other => out.push_str(&format!("%{other:02X}")),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn optimized_url_percent_encodes_special_characters_in_src() {
let url = optimized_url("images/my photo.jpg", 400, Some(300), 75);
assert_eq!(
url,
"/__larust_image/optimize?src=images/my%20photo.jpg&w=400&h=300&q=75"
);
}
#[test]
fn optimized_url_omits_h_when_height_is_none() {
let url = optimized_url("hero.jpg", 400, None, 75);
assert_eq!(url, "/__larust_image/optimize?src=hero.jpg&w=400&q=75");
}
#[test]
fn tag_includes_width_height_lazy_loading_and_escaped_alt() {
let html = tag(&ImageOptions::new("hero.jpg", 800, 600).alt("A \"quoted\" <tag>"));
assert!(html.contains(r#"width="800""#));
assert!(html.contains(r#"height="600""#));
assert!(html.contains(r#"loading="lazy""#));
assert!(html.contains(""quoted""));
assert!(html.contains("<tag>"));
assert_eq!(html.matches('<').count(), 1);
}
#[test]
fn tag_defaults_quality_to_75() {
let html = tag(&ImageOptions::new("hero.jpg", 800, 600));
assert!(html.contains("q=75"));
}
#[test]
fn fill_omits_width_height_attrs_and_sets_the_cover_style() {
let html = tag(&ImageOptions::fill("hero.jpg"));
assert!(!html.contains("width="));
assert!(!html.contains("height="));
assert!(html.contains("position:absolute"));
assert!(html.contains("object-fit:cover"));
assert!(html.contains(&format!("w={FILL_FALLBACK_WIDTH}")));
}
#[test]
fn priority_sets_eager_loading_and_fetchpriority() {
let html = tag(&ImageOptions::new("hero.jpg", 800, 600).priority());
assert!(html.contains(r#"loading="eager""#));
assert!(html.contains(r#"fetchpriority="high""#));
}
#[test]
fn priority_emits_a_real_inline_preload_link_before_the_img() {
let html = tag(&ImageOptions::new("hero.jpg", 800, 600).priority());
let link_pos = html.find("<link").expect("no preload link rendered");
let img_pos = html.find("<img").expect("no img rendered");
assert!(
link_pos < img_pos,
"preload link should precede <img>: {html}"
);
assert!(html.contains(r#"rel="preload""#));
assert!(html.contains(r#"as="image""#));
assert!(html.contains(r#"href="/__larust_image/optimize"#));
}
#[test]
fn preload_link_carries_imagesrcset_when_sizes_is_set() {
let html = tag(&ImageOptions::new("hero.jpg", 800, 600)
.priority()
.sizes("50vw"));
assert!(html.contains("imagesrcset="));
assert!(html.contains(r#"imagesizes="50vw""#));
}
#[test]
fn no_priority_means_no_preload_link_at_all() {
let html = tag(&ImageOptions::new("hero.jpg", 800, 600));
assert!(!html.contains("<link"));
}
#[test]
fn sizes_triggers_a_srcset_with_every_breakpoint() {
let html = tag(&ImageOptions::new("hero.jpg", 800, 600).sizes("50vw"));
assert!(html.contains(r#"sizes="50vw""#));
for breakpoint in SRCSET_BREAKPOINTS {
assert!(
html.contains(&format!("w={breakpoint}&q=75 {breakpoint}w")),
"missing breakpoint {breakpoint} in srcset: {html}"
);
}
}
#[test]
fn no_sizes_means_no_srcset_at_all() {
let html = tag(&ImageOptions::new("hero.jpg", 800, 600));
assert!(!html.contains("srcset"));
}
#[test]
fn unoptimized_points_straight_at_the_public_file() {
let html = tag(&ImageOptions::new("icons/star.svg", 24, 24).unoptimized());
assert!(html.contains(r#"src="/icons/star.svg""#));
assert!(!html.contains("__larust_image"));
}
#[test]
fn blur_placeholder_is_absent_on_a_cold_cache_not_an_error() {
let html = tag(&ImageOptions::new("hero.jpg", 800, 600).placeholder(Placeholder::Blur));
assert!(!html.contains("background-image"));
}
}