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