Skip to main content

larust_image/
lib.rs

1//! Automatic image optimization - Larust's answer to Next.js's `<Image />`
2//! component. **Core framework surface, not an optional Tier-1 shim** - the
3//! same tier as `@wire`/`@resource`/`@spa`/`@vitex`, always compiled in,
4//! never behind a Cargo feature flag, because the `<Image ...>` template
5//! tag itself (`larust-view`'s own parser, see that crate's `ast.rs`) is
6//! real, fixed grammar, not something an optional crate bolts on.
7//!
8//! **Local images only, for now.** [`ImageOptions::src`] is always a path
9//! relative to the app's own `public/` directory - never an arbitrary
10//! remote URL. Proxying remote images the way Next.js's own allow-listed
11//! `images.domains` config does is a real, separate feature (SSRF
12//! hardening, fetch timeouts/size limits, a domain allow-list) - a
13//! deliberate v1 boundary, not an oversight.
14//!
15//! ## What actually happens
16//!
17//! 1. [`tag`] (called by `<Image ...>` - see `larust-macros`' own `view!`
18//!    codegen) is a pure, synchronous computation: it builds a plain
19//!    `<img>` pointing at [`optimized_url`]'s URL. No decoding, resizing,
20//!    or encoding happens yet.
21//! 2. The browser requests that URL, handled by [`route::ImagePlugin`]'s
22//!    one route. The first request for a given combination of inputs
23//!    decodes the source file, resizes it, encodes it, and writes the
24//!    result to `storage/framework/cache/images/` before serving it.
25//! 3. Every later request for that same combination is a plain cached-file
26//!    read - no re-decoding, no re-encoding.
27//!
28//! ## Formats
29//!
30//! AVIF (via [`ravif`]/`rav1e`, both pure Rust - no C toolchain, matching
31//! this project's own `redb` posture elsewhere) when the request's
32//! `Accept` header includes `image/avif`; JPEG otherwise, as the universal
33//! fallback. **No lossy WebP** - there's no good pure-Rust lossy WebP
34//! encoder, only a C-library one (`libwebp`), which this crate
35//! deliberately doesn't pull in.
36//!
37//! ## Attributes
38//!
39//! Every [`ImageOptions`] field maps to one `<Image ...>` attribute (see
40//! `docs/MACROS.md`'s own entry for the exact template-level grammar):
41//!
42//! - **`width`/`height`** - a fixed box; resized to exactly this, not
43//!   aspect-ratio-preserving. Required unless `fill` is set.
44//! - **`fill`** - expands to fill the parent element instead of a fixed
45//!   box (`position:absolute;inset:0;object-fit:cover` - the parent needs
46//!   its own `position: relative/absolute/fixed`). Mutually exclusive
47//!   with `width`/`height` - `larust-macros`' own codegen rejects both
48//!   being given together at compile time.
49//! - **`sizes`** - a CSS-like breakpoint hint (`"(max-width: 768px) 100vw,
50//!   50vw"`), passed straight through to the rendered `sizes` attribute.
51//!   Its presence is also what *triggers* [`build_srcset`] - there's no
52//!   separate `srcset` attribute to write by hand; every variant it names
53//!   is generated on demand (decoded/resized/encoded, then cached) the
54//!   first time some visitor's browser actually requests it, exactly like
55//!   the single base image already is. See [`SRCSET_BREAKPOINTS`].
56//! - **`priority`** - `loading="eager"` + `fetchpriority="high"`, for an
57//!   LCP element (a hero image), plus a real resource hint: an inline
58//!   `<link rel="preload" as="image">` immediately before the `<img>`
59//!   itself (not injected into `<head>` - see [`tag`]'s own doc comment
60//!   for why inline placement gets essentially the same preload timing
61//!   as a `<head>`-placed one would for a response this framework always
62//!   serves as one complete buffer, never streamed).
63//! - **`loading`** - `"lazy"` (default) or `"eager"`, overridden to
64//!   `"eager"` automatically when `priority` is set.
65//! - **`quality`** - 1-100, defaults to [`DEFAULT_QUALITY`].
66//! - **`placeholder`** - `Empty` (default) or `Blur`, a background-image
67//!   blur-up shown behind the real `<img>` while it loads. See
68//!   [`route`]'s own doc comment for why this is a *cached, separately
69//!   generated* thumbnail rather than Next.js's build-time-computed
70//!   inline base64 - and why a brand-new image's very first view renders
71//!   with no blur.
72//! - **`unoptimized`** - serves `src` exactly as-is, skipping the optimize
73//!   route entirely. For the cases this crate's own processing would
74//!   actively break: an SVG (not a raster format `image` can decode as a
75//!   bitmap at all), an animated GIF (resize/re-encode would collapse it
76//!   to one frame), or a already-tiny icon not worth a round trip to
77//!   optimize.
78//!
79//! Re-exported through `larust_support::image` (unconditionally - see
80//! `crates/larust-support/src/lib.rs`) so generated apps depend only on
81//! `larust-support`, never on this crate directly.
82//!
83//! ## Deliberately out of scope
84//!
85//! - **Remote images.** See this module's own opening paragraph.
86//! - **Static-import-time (build-time) optimization.** Everything here is
87//!   on-demand, at request time, cached after the first hit - there's no
88//!   separate build step that pre-generates optimized variants.
89//! - **Any `object-fit` mode besides `cover` for `fill`.** A real,
90//!   small follow-up (an `object_fit` option) if a caller ever needs
91//!   `contain`/`fill`/`none`; not built speculatively ahead of that need.
92
93mod optimize;
94mod route;
95
96pub use optimize::{
97    optimize, EncodedFormat, OptimizeError, OptimizeResult, Optimized, ResizeTarget,
98};
99pub use route::ImagePlugin;
100
101/// Default JPEG/AVIF quality (1-100) when a call site doesn't pick one -
102/// the same ballpark Next.js's own default (`75`) uses: a real size
103/// reduction with no visible artifacting for typical photographic content.
104pub const DEFAULT_QUALITY: u8 = 75;
105
106/// A conservative upper bound on any single dimension - not a real product
107/// limit, just a guard against a request accidentally (or maliciously)
108/// asking this crate to allocate and encode an enormous image. Four times
109/// a typical high-DPI viewport's own largest dimension is generous for
110/// every real layout this crate is meant to serve.
111pub const MAX_DIMENSION: u32 = 4096;
112
113/// `fill`'s own fallback width, used only for the plain `src` attribute
114/// (the one a browser with no `srcset`/`sizes` support, or no `sizes`
115/// given at all, actually fetches) - `fill` by definition has no
116/// known-ahead-of-time render width to derive one from. A common "assume
117/// a reasonably large viewport" default, the same instinct Next.js's own
118/// fallback device-size handling uses.
119const FILL_FALLBACK_WIDTH: u32 = 1920;
120
121/// The responsive breakpoints [`build_srcset`] generates a variant for -
122/// closely mirroring Next.js's own default device-size list (phone
123/// through large desktop), wide enough to cover realistic viewports
124/// without generating an excessive number of cached variants per image.
125/// Fixed, not configurable, in this version - a real follow-up if an app
126/// ever needs a different set.
127const SRCSET_BREAKPOINTS: &[u32] = &[320, 420, 640, 750, 828, 1080, 1200, 1920, 2560, 3840];
128
129/// `"lazy"` (default - load when entering the viewport) or `"eager"`
130/// (load immediately). See [`ImageOptions::loading`].
131#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
132pub enum Loading {
133    #[default]
134    Lazy,
135    Eager,
136}
137
138impl Loading {
139    fn as_str(self) -> &'static str {
140        match self {
141            Loading::Lazy => "lazy",
142            Loading::Eager => "eager",
143        }
144    }
145}
146
147/// `Empty` (default - nothing shown while loading) or `Blur` (a cached
148/// blur-up thumbnail behind the image). See [`ImageOptions::placeholder`].
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
150pub enum Placeholder {
151    #[default]
152    Empty,
153    Blur,
154}
155
156/// Every `<Image ...>` attribute, one field each - see this crate's own
157/// doc comment for the full meaning of each one. Owned `String`s, not
158/// borrowed `&str`s, deliberately: `larust-macros`' own codegen (which
159/// constructs this struct literal directly, one field per attribute, no
160/// builder calls needed there) hands it a `:src="expr"` dynamic
161/// attribute's own value exactly as whatever type that expression
162/// produces (`String`, `&str`, anything `Display`) - converted uniformly
163/// via `.to_string()` either way - rather than needing a lifetime
164/// parameter here just to borrow a value that's just as often a literal
165/// as it is some other owned value computed on the spot.
166/// [`ImageOptions::new`]/[`ImageOptions::fill`] plus the builder-style
167/// setters below are for a hand-written Rust call site instead, and
168/// accept `impl Into<String>` so a plain `&str` literal still needs no
169/// extra ceremony there either.
170#[derive(Debug, Clone)]
171pub struct ImageOptions {
172    pub src: String,
173    pub width: Option<u32>,
174    pub height: Option<u32>,
175    pub alt: String,
176    pub quality: u8,
177    pub fill: bool,
178    pub sizes: Option<String>,
179    pub priority: bool,
180    pub placeholder: Placeholder,
181    pub loading: Loading,
182    pub unoptimized: bool,
183}
184
185impl ImageOptions {
186    /// A fixed-box image - the common case.
187    pub fn new(src: impl Into<String>, width: u32, height: u32) -> Self {
188        Self {
189            src: src.into(),
190            width: Some(width),
191            height: Some(height),
192            alt: String::new(),
193            quality: DEFAULT_QUALITY,
194            fill: false,
195            sizes: None,
196            priority: false,
197            placeholder: Placeholder::default(),
198            loading: Loading::default(),
199            unoptimized: false,
200        }
201    }
202
203    /// A `fill`-mode image - expands to its parent's own box, which must
204    /// have `position: relative/absolute/fixed` in your own CSS.
205    pub fn fill(src: impl Into<String>) -> Self {
206        Self {
207            src: src.into(),
208            width: None,
209            height: None,
210            alt: String::new(),
211            quality: DEFAULT_QUALITY,
212            fill: true,
213            sizes: None,
214            priority: false,
215            placeholder: Placeholder::default(),
216            loading: Loading::default(),
217            unoptimized: false,
218        }
219    }
220
221    pub fn alt(mut self, alt: impl Into<String>) -> Self {
222        self.alt = alt.into();
223        self
224    }
225
226    pub fn quality(mut self, quality: u8) -> Self {
227        self.quality = quality;
228        self
229    }
230
231    /// Also triggers [`build_srcset`] generation - see this crate's own
232    /// `sizes` doc bullet above.
233    pub fn sizes(mut self, sizes: impl Into<String>) -> Self {
234        self.sizes = Some(sizes.into());
235        self
236    }
237
238    /// Also forces [`Loading::Eager`] - Next.js's own identical coupling
239    /// (`loading` is ignored, treated as `"eager"`, whenever `priority` is
240    /// set).
241    pub fn priority(mut self) -> Self {
242        self.priority = true;
243        self.loading = Loading::Eager;
244        self
245    }
246
247    pub fn placeholder(mut self, placeholder: Placeholder) -> Self {
248        self.placeholder = placeholder;
249        self
250    }
251
252    pub fn loading(mut self, loading: Loading) -> Self {
253        self.loading = loading;
254        self
255    }
256
257    pub fn unoptimized(mut self) -> Self {
258        self.unoptimized = true;
259        self
260    }
261}
262
263/// The URL `<Image ...>` renders into its `src` attribute (or one entry of
264/// its `srcset`) - your own app never calls this route directly, this
265/// *is* the one real entry point. `src` is a path relative to `public/`
266/// (e.g. `"images/hero.jpg"` for a file at `public/images/hero.jpg`) -
267/// percent-encoded here so a path containing spaces or other reserved
268/// query-string characters still round-trips correctly. `height: None`
269/// requests an aspect-ratio-preserving resize instead of a fixed box (see
270/// [`ResizeTarget::Width`]) - used for every `fill`/`sizes`-driven variant,
271/// where only a target width is actually known.
272pub fn optimized_url(src: &str, width: u32, height: Option<u32>, quality: u8) -> String {
273    match height {
274        Some(height) => format!(
275            "/__larust_image/optimize?src={}&w={width}&h={height}&q={quality}",
276            percent_encode(src)
277        ),
278        None => format!(
279            "/__larust_image/optimize?src={}&w={width}&q={quality}",
280            percent_encode(src)
281        ),
282    }
283}
284
285/// `srcset`'s own value when `sizes` is set - one entry per
286/// [`SRCSET_BREAKPOINTS`] (capped at [`MAX_DIMENSION`]), each an
287/// aspect-ratio-preserving width-only variant (see [`optimized_url`]'s own
288/// `height: None` case) of the *same* on-demand route the plain `src`
289/// already uses - nothing here is pre-generated; a given breakpoint is
290/// decoded/resized/encoded (and cached) only the first time some visitor's
291/// browser actually requests exactly that width.
292pub fn build_srcset(src: &str, quality: u8) -> String {
293    SRCSET_BREAKPOINTS
294        .iter()
295        .filter(|&&width| width <= MAX_DIMENSION)
296        .map(|&width| format!("{} {width}w", optimized_url(src, width, None, quality)))
297        .collect::<Vec<_>>()
298        .join(", ")
299}
300
301/// A ready `<img>` tag - what `<Image ...>` actually expands to. See this
302/// crate's own doc comment for the full meaning of every [`ImageOptions`]
303/// field. Takes `options` by reference - several fields (`src` in
304/// particular) are read more than once below, and `ImageOptions` owns
305/// `String`s rather than borrowing `&str`s (see that struct's own doc
306/// comment for why), so a by-value `ImageOptions` would mean the first
307/// read moved a field a later one still needed.
308pub fn tag(options: &ImageOptions) -> String {
309    // `priority` always forces eager loading, regardless of whether the
310    // caller went through `ImageOptions::priority()` (which also sets
311    // this) or built the struct literal directly (as `larust-macros`' own
312    // codegen does, for a `priority` attribute whose value isn't known
313    // until runtime) - this is the one place that coupling is guaranteed
314    // to actually apply, so nothing upstream needs to replicate it.
315    let loading = if options.priority {
316        Loading::Eager
317    } else {
318        options.loading
319    };
320
321    let mut style = String::new();
322    if options.fill {
323        style.push_str("position:absolute;inset:0;width:100%;height:100%;object-fit:cover;");
324    }
325    if options.placeholder == Placeholder::Blur {
326        if let Some(data_uri) = route::read_blur_data_uri(&options.src) {
327            style.push_str(&format!(
328                "background-image:url({data_uri});background-size:cover;background-position:50% 50%;"
329            ));
330        }
331    }
332
333    let src_url = if options.unoptimized {
334        format!("/{}", options.src.trim_start_matches('/'))
335    } else {
336        let fallback_width = options.width.unwrap_or(FILL_FALLBACK_WIDTH);
337        optimized_url(
338            &options.src,
339            fallback_width,
340            options.height,
341            options.quality,
342        )
343    };
344    let srcset = (!options.unoptimized)
345        .then_some(options.sizes.as_ref())
346        .flatten()
347        .map(|sizes| (build_srcset(&options.src, options.quality), sizes));
348
349    let mut html = String::new();
350
351    // A real resource hint for `priority` images, not just a stronger
352    // fetch once the browser's main parser reaches the `<img>` itself -
353    // see this crate's own doc comment for why placing it *inline*, right
354    // here, gets essentially the same preload timing as a `<head>`-placed
355    // one would: the browser's preload scanner tokenizes the whole
356    // document speculatively, independent of and ahead of the main
357    // parser, and this framework always serves one complete, buffered
358    // response rather than a streamed one - there's no meaningful
359    // "arrived later" penalty to placement within it the way there would
360    // be for a real multi-chunk stream. `imagesrcset`/`imagesizes` mirror
361    // whatever the `<img>` itself will carry, so the browser preloads the
362    // exact variant it's actually going to use, not just the fallback.
363    if options.priority {
364        html.push_str("<link rel=\"preload\" as=\"image\"");
365        push_attr(&mut html, "href", &src_url);
366        if let Some((set, sizes)) = &srcset {
367            push_attr(&mut html, "imagesrcset", set);
368            push_attr(&mut html, "imagesizes", sizes);
369        }
370        html.push_str(" fetchpriority=\"high\">");
371    }
372
373    html.push_str("<img");
374    push_attr(&mut html, "src", &src_url);
375    if let Some((set, sizes)) = &srcset {
376        push_attr(&mut html, "srcset", set);
377        push_attr(&mut html, "sizes", sizes);
378    }
379
380    if let Some(width) = options.width {
381        html.push_str(&format!(r#" width="{width}""#));
382    }
383    if let Some(height) = options.height {
384        html.push_str(&format!(r#" height="{height}""#));
385    }
386    push_attr(&mut html, "alt", &options.alt);
387    push_attr(&mut html, "loading", loading.as_str());
388    if options.priority {
389        html.push_str(r#" fetchpriority="high""#);
390    }
391    html.push_str(r#" decoding="async""#);
392    if !style.is_empty() {
393        push_attr(&mut html, "style", &style);
394    }
395    html.push('>');
396    html
397}
398
399fn push_attr(html: &mut String, name: &str, value: &str) {
400    html.push_str(&format!(r#" {name}="{}""#, escape_attr(value)));
401}
402
403/// Minimal HTML attribute escaping - just the characters that actually
404/// matter inside a double-quoted attribute value. Not imported from
405/// `larust-view` (which already has a real `escape` function) - the same
406/// "ten-line helper, not worth a cross-dependency" reasoning
407/// `larust-passport`/`larust-cashier-stripe`'s own tiny local helpers
408/// already establish, and this crate has no other reason to depend on the
409/// template engine at all.
410fn escape_attr(value: &str) -> String {
411    let mut out = String::with_capacity(value.len());
412    for ch in value.chars() {
413        match ch {
414            '&' => out.push_str("&amp;"),
415            '"' => out.push_str("&quot;"),
416            '<' => out.push_str("&lt;"),
417            '>' => out.push_str("&gt;"),
418            other => out.push(other),
419        }
420    }
421    out
422}
423
424/// Percent-encodes everything outside the RFC 3986 "unreserved" set plus
425/// `/` (kept literal purely for readability in a URL that's already a
426/// query-string value, not because `/` is unsafe there) - enough to carry
427/// a filesystem path safely through a query string. Hand-rolled rather
428/// than pulling in a dedicated URL-encoding crate - the same "small,
429/// self-contained helper" precedent `larust-passport`'s own `hex_encode`
430/// establishes for an equally narrow, equally stable piece of text
431/// encoding.
432fn percent_encode(value: &str) -> String {
433    let mut out = String::with_capacity(value.len());
434    for byte in value.as_bytes() {
435        match byte {
436            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
437                out.push(*byte as char);
438            }
439            other => out.push_str(&format!("%{other:02X}")),
440        }
441    }
442    out
443}
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448
449    #[test]
450    fn optimized_url_percent_encodes_special_characters_in_src() {
451        let url = optimized_url("images/my photo.jpg", 400, Some(300), 75);
452        assert_eq!(
453            url,
454            "/__larust_image/optimize?src=images/my%20photo.jpg&w=400&h=300&q=75"
455        );
456    }
457
458    #[test]
459    fn optimized_url_omits_h_when_height_is_none() {
460        let url = optimized_url("hero.jpg", 400, None, 75);
461        assert_eq!(url, "/__larust_image/optimize?src=hero.jpg&w=400&q=75");
462    }
463
464    #[test]
465    fn tag_includes_width_height_lazy_loading_and_escaped_alt() {
466        let html = tag(&ImageOptions::new("hero.jpg", 800, 600).alt("A \"quoted\" <tag>"));
467        assert!(html.contains(r#"width="800""#));
468        assert!(html.contains(r#"height="600""#));
469        assert!(html.contains(r#"loading="lazy""#));
470        assert!(html.contains("&quot;quoted&quot;"));
471        assert!(html.contains("&lt;tag&gt;"));
472        // Only the real `<img` itself should be a literal `<` - the one
473        // inside `alt` must have come through escaped.
474        assert_eq!(html.matches('<').count(), 1);
475    }
476
477    #[test]
478    fn tag_defaults_quality_to_75() {
479        let html = tag(&ImageOptions::new("hero.jpg", 800, 600));
480        assert!(html.contains("q=75"));
481    }
482
483    #[test]
484    fn fill_omits_width_height_attrs_and_sets_the_cover_style() {
485        let html = tag(&ImageOptions::fill("hero.jpg"));
486        assert!(!html.contains("width="));
487        assert!(!html.contains("height="));
488        assert!(html.contains("position:absolute"));
489        assert!(html.contains("object-fit:cover"));
490        // No explicit width given - falls back to a sensible default for
491        // the plain `src` (no `sizes` was set in this test, so there's no
492        // srcset to fall back on instead).
493        assert!(html.contains(&format!("w={FILL_FALLBACK_WIDTH}")));
494    }
495
496    #[test]
497    fn priority_sets_eager_loading_and_fetchpriority() {
498        let html = tag(&ImageOptions::new("hero.jpg", 800, 600).priority());
499        assert!(html.contains(r#"loading="eager""#));
500        assert!(html.contains(r#"fetchpriority="high""#));
501    }
502
503    #[test]
504    fn priority_emits_a_real_inline_preload_link_before_the_img() {
505        let html = tag(&ImageOptions::new("hero.jpg", 800, 600).priority());
506        let link_pos = html.find("<link").expect("no preload link rendered");
507        let img_pos = html.find("<img").expect("no img rendered");
508        assert!(
509            link_pos < img_pos,
510            "preload link should precede <img>: {html}"
511        );
512        assert!(html.contains(r#"rel="preload""#));
513        assert!(html.contains(r#"as="image""#));
514        assert!(html.contains(r#"href="/__larust_image/optimize"#));
515    }
516
517    #[test]
518    fn preload_link_carries_imagesrcset_when_sizes_is_set() {
519        let html = tag(&ImageOptions::new("hero.jpg", 800, 600)
520            .priority()
521            .sizes("50vw"));
522        assert!(html.contains("imagesrcset="));
523        assert!(html.contains(r#"imagesizes="50vw""#));
524    }
525
526    #[test]
527    fn no_priority_means_no_preload_link_at_all() {
528        let html = tag(&ImageOptions::new("hero.jpg", 800, 600));
529        assert!(!html.contains("<link"));
530    }
531
532    #[test]
533    fn sizes_triggers_a_srcset_with_every_breakpoint() {
534        let html = tag(&ImageOptions::new("hero.jpg", 800, 600).sizes("50vw"));
535        assert!(html.contains(r#"sizes="50vw""#));
536        for breakpoint in SRCSET_BREAKPOINTS {
537            // `&` is HTML-escaped to `&amp;` once the srcset string is
538            // embedded as an attribute value (see `escape_attr`).
539            assert!(
540                html.contains(&format!("w={breakpoint}&amp;q=75 {breakpoint}w")),
541                "missing breakpoint {breakpoint} in srcset: {html}"
542            );
543        }
544    }
545
546    #[test]
547    fn no_sizes_means_no_srcset_at_all() {
548        let html = tag(&ImageOptions::new("hero.jpg", 800, 600));
549        assert!(!html.contains("srcset"));
550    }
551
552    #[test]
553    fn unoptimized_points_straight_at_the_public_file() {
554        let html = tag(&ImageOptions::new("icons/star.svg", 24, 24).unoptimized());
555        assert!(html.contains(r#"src="/icons/star.svg""#));
556        assert!(!html.contains("__larust_image"));
557    }
558
559    #[test]
560    fn blur_placeholder_is_absent_on_a_cold_cache_not_an_error() {
561        let html = tag(&ImageOptions::new("hero.jpg", 800, 600).placeholder(Placeholder::Blur));
562        // No cached thumbnail exists for this never-before-seen src in a
563        // test's own temp-free environment - renders cleanly without a
564        // background-image rather than failing.
565        assert!(!html.contains("background-image"));
566    }
567}