Expand description
Automatic image optimization - Larust’s answer to Next.js’s <Image />
component. Core framework surface, not an optional Tier-1 shim - the
same tier as @wire/@resource/@spa/@vitex, always compiled in,
never behind a Cargo feature flag, because the <Image ...> template
tag itself (larust-view’s own parser, see that crate’s ast.rs) is
real, fixed grammar, not something an optional crate bolts on.
Local images only, for now. ImageOptions::src is always a path
relative to the app’s own public/ directory - never an arbitrary
remote URL. Proxying remote images the way Next.js’s own allow-listed
images.domains config does is a real, separate feature (SSRF
hardening, fetch timeouts/size limits, a domain allow-list) - a
deliberate v1 boundary, not an oversight.
§What actually happens
tag(called by<Image ...>- seelarust-macros’ ownview!codegen) is a pure, synchronous computation: it builds a plain<img>pointing atoptimized_url’s URL. No decoding, resizing, or encoding happens yet.- The browser requests that URL, handled by
route::ImagePlugin’s one route. The first request for a given combination of inputs decodes the source file, resizes it, encodes it, and writes the result tostorage/framework/cache/images/before serving it. - Every later request for that same combination is a plain cached-file read - no re-decoding, no re-encoding.
§Formats
AVIF (via ravif/rav1e, both pure Rust - no C toolchain, matching
this project’s own redb posture elsewhere) when the request’s
Accept header includes image/avif; otherwise lossy WebP (via
webpkit, also pure Rust) when Accept includes image/webp;
JPEG as the universal fallback when neither is accepted, or if the
preferred encoder fails for any reason.
{: .note }
WebP support is honest, not aspirational. webpkit is a genuine,
pure-Rust lossy VP8 encoder - no libwebp/C dependency, matching this
crate’s AVIF posture - but it’s pre-1.0 upstream, with no published
conformance or benchmark results yet, unlike ravif’s own AVIF path.
It was picked over the more feature-complete zenwebp for a license
reason, not a maturity one: zenwebp 0.3.0+ is AGPL-3.0/paid-
commercial, which this Apache-2.0, always-compiled-in crate can
never depend on. Every lossy WebP encode that fails falls back to
JPEG automatically (the same safety net AVIF already has) - a WebP
bug degrades an image’s compression, never breaks the page.
§Attributes
Every ImageOptions field maps to one <Image ...> attribute (see
docs/MACROS.md’s own entry for the exact template-level grammar):
width/height- a fixed box; resized to exactly this, not aspect-ratio-preserving. Required unlessfillis set.fill- expands to fill the parent element instead of a fixed box (position:absolute;inset:0;object-fit:cover- the parent needs its ownposition: relative/absolute/fixed). Mutually exclusive withwidth/height-larust-macros’ own codegen rejects both being given together at compile time.sizes- a CSS-like breakpoint hint ("(max-width: 768px) 100vw, 50vw"), passed straight through to the renderedsizesattribute. Its presence is also what triggersbuild_srcset- there’s no separatesrcsetattribute to write by hand; every variant it names is generated on demand (decoded/resized/encoded, then cached) the first time some visitor’s browser actually requests it, exactly like the single base image already is. See [SRCSET_BREAKPOINTS].priority-loading="eager"+fetchpriority="high", for an LCP element (a hero image), plus a real resource hint: an inline<link rel="preload" as="image">immediately before the<img>itself (not injected into<head>- seetag’s own doc comment for why inline placement gets essentially the same preload timing as a<head>-placed one would for a response this framework always serves as one complete buffer, never streamed).loading-"lazy"(default) or"eager", overridden to"eager"automatically whenpriorityis set.quality- 1-100, defaults toDEFAULT_QUALITY.placeholder-Empty(default) orBlur, a background-image blur-up shown behind the real<img>while it loads. See [route]’s own doc comment for why this is a cached, separately generated thumbnail rather than Next.js’s build-time-computed inline base64 - and why a brand-new image’s very first view renders with no blur.unoptimized- servessrcexactly as-is, skipping the optimize route entirely. For the cases this crate’s own processing would actively break: an SVG (not a raster formatimagecan decode as a bitmap at all), an animated GIF (resize/re-encode would collapse it to one frame), or a already-tiny icon not worth a round trip to optimize.
Re-exported through larust_support::image (unconditionally - see
crates/larust-support/src/lib.rs) so generated apps depend only on
larust-support, never on this crate directly.
§Deliberately out of scope
- Remote images. See this module’s own opening paragraph.
- Static-import-time (build-time) optimization. Everything here is on-demand, at request time, cached after the first hit - there’s no separate build step that pre-generates optimized variants.
- Any
object-fitmode besidescoverforfill. A real, small follow-up (anobject_fitoption) if a caller ever needscontain/fill/none; not built speculatively ahead of that need.
Structs§
- Image
Options - Every
<Image ...>attribute, one field each - see this crate’s own doc comment for the full meaning of each one. OwnedStrings, not borrowed&strs, deliberately:larust-macros’ own codegen (which constructs this struct literal directly, one field per attribute, no builder calls needed there) hands it a:src="expr"dynamic attribute’s own value exactly as whatever type that expression produces (String,&str, anythingDisplay) - converted uniformly via.to_string()either way - rather than needing a lifetime parameter here just to borrow a value that’s just as often a literal as it is some other owned value computed on the spot.ImageOptions::new/ImageOptions::fillplus the builder-style setters below are for a hand-written Rust call site instead, and acceptimpl Into<String>so a plain&strliteral still needs no extra ceremony there either. - Image
Plugin - Optimize
Result optimize’s full result - the main resized/encoded image, plus (when asked for) a tiny blurred thumbnail generated from the same decode, so producing one never costs a second, separate decode of the source file. See [crate::route]’s own doc comment for why the blur thumbnail is generated here, as a side effect of an ordinary optimize request, rather than computed synchronously insidecrate::tag.- Optimized
Enums§
- Encoded
Format - Which format
optimizeactually produced - the caller needs this to pick the rightContent-Type/cache file extension, since it depends on the request’s ownAcceptheader, not just the input. - Format
Preference - Which format
optimizeshould try first, decided by the caller from the request’s ownAcceptheader -Avifwins overWebpwhen both are accepted (the ordinary case: a browser that accepts AVIF almost always lists it ahead of WebP inAccept, and AVIF compresses better at equal quality). Each lossy tier falls back toEncodedFormat::Jpegon a real encode failure - seeoptimize’s own match arm for why that’s always safe to do silently. - Loading
"lazy"(default - load when entering the viewport) or"eager"(load immediately). SeeImageOptions::loading.- Optimize
Error - Placeholder
Empty(default - nothing shown while loading) orBlur(a cached blur-up thumbnail behind the image). SeeImageOptions::placeholder.- Resize
Target - How to resize the decoded source - see
optimize’s own doc comment for when each is used.
Constants§
- DEFAULT_
QUALITY - Default JPEG/AVIF quality (1-100) when a call site doesn’t pick one -
the same ballpark Next.js’s own default (
75) uses: a real size reduction with no visible artifacting for typical photographic content. - MAX_
DIMENSION - A conservative upper bound on any single dimension - not a real product limit, just a guard against a request accidentally (or maliciously) asking this crate to allocate and encode an enormous image. Four times a typical high-DPI viewport’s own largest dimension is generous for every real layout this crate is meant to serve.
Functions§
- build_
srcset srcset’s own value whensizesis set - one entry per [SRCSET_BREAKPOINTS] (capped atMAX_DIMENSION), each an aspect-ratio-preserving width-only variant (seeoptimized_url’s ownheight: Nonecase) of the same on-demand route the plainsrcalready uses - nothing here is pre-generated; a given breakpoint is decoded/resized/encoded (and cached) only the first time some visitor’s browser actually requests exactly that width.- optimize
- Decodes
sourceonce, resizes it pertargetfor the main result -preferred_format(the caller decides this from the request’s ownAcceptheader) when that format’s own encoder succeeds, JPEG otherwise - and, whengenerate_bluris set, also produces a tiny blurred-placeholder thumbnail from the same decode (always JPEG, regardless ofpreferred_format- it’s consumed directly by the browser’s own CSS decoder as an inline data URI, never served as a standalone resource a format negotiation could apply to). - optimized_
url - The URL
<Image ...>renders into itssrcattribute (or one entry of itssrcset) - your own app never calls this route directly, this is the one real entry point.srcis a path relative topublic/(e.g."images/hero.jpg"for a file atpublic/images/hero.jpg) - percent-encoded here so a path containing spaces or other reserved query-string characters still round-trips correctly.height: Nonerequests an aspect-ratio-preserving resize instead of a fixed box (seeResizeTarget::Width) - used for everyfill/sizes-driven variant, where only a target width is actually known. - tag
- A ready
<img>tag - what<Image ...>actually expands to. See this crate’s own doc comment for the full meaning of everyImageOptionsfield. Takesoptionsby reference - several fields (srcin particular) are read more than once below, andImageOptionsownsStrings rather than borrowing&strs (see that struct’s own doc comment for why), so a by-valueImageOptionswould mean the first read moved a field a later one still needed.