moss_core/render/image.rs
1//! Image HTML synthesizer — the single entry point for emitting `<img>` /
2//! `<picture>` markup in moss output.
3//!
4//! See [`docs/architecture/structural-html-emission.md`](../../../../docs/architecture/structural-html-emission.md)
5//! for the architectural principle: structural HTML decisions are made at the
6//! typed-data layer (pulldown-cmark events, shortcode AST, typed component
7//! props), with all three call sites converging on the function in this
8//! module. Regex post-passes are reserved for non-markdown-origin attribute
9//! injection only.
10//!
11//! # Migration state (post-Step-7, 2026-05-16)
12//!
13//! Steps 1-7 of the structural-html-emission migration are complete:
14//! - Step 1: extracted `synthesize_image_html`
15//! - Step 2: routed markdown `Tag::Image` events
16//! - Step 3: routed `:::hero` shortcode image
17//! - Step 4: routed link-preview favicon
18//! - Step 6: routed every cover image path (folder cards, child summary
19//! cards, folder index hero, photo/video gallery thumbnails) through
20//! `render_cover_html`
21//! - Step 7: retired `wrap_img_in_picture` (the structural part of the
22//! legacy regex post-pass). The synthesizer now owns every `<picture>`
23//! wrap in moss output. `add_image_placeholder_attributes` survives as
24//! the attribute-injection seam for the documented carve-outs (see
25//! below).
26//!
27//! The byte-shape contract is captured by snapshot tests at the bottom of
28//! this file. They are the line of defense against accidental output
29//! drift; any future change to attribute order, quoting, or whitespace
30//! must update them deliberately.
31//!
32//! Later steps will:
33//! - Step 8: switch `MarkdownStandalone` to a `<figure class="moss-image">`
34//! wrapper (breaking change for user themes — staged separately)
35//! - Add AVIF `<source>` lines once the image pipeline produces AVIF
36//! - Drop the inline LQIP `style=` in favor of a wrapper CSS custom prop
37//!
38//! # Step-8 contract: synthesizer owns the outer `<figure>` (planned)
39//!
40//! `transform_events` currently wraps the synthesizer's `MarkdownStandalone`
41//! output in its own `<figure>` for the three caption-pattern branches
42//! (image+emphasis, separate-emphasis, implicit-figure). After Step 8 the
43//! synthesizer emits `<figure class="moss-image">` itself; if `transform_events`
44//! still wraps, the output will be `<figure><figure class="moss-image">...</figure>
45//! <figcaption>...</figcaption></figure>` — invalid double-wrap.
46//!
47//! The Step-8 contract: caption flows into the synthesizer via
48//! `MarkdownStandalone { caption: Option<&str> }` (or a richer
49//! `CaptionMarkdown` for emphasis-in-caption support), and the three
50//! caption-pattern branches collapse into a single `Event::Html(
51//! synthesize_image_html(..., MarkdownStandalone { caption }))` emission.
52//! The `<figcaption>` becomes the synthesizer's responsibility, NOT
53//! `transform_events`. Captures the spec at
54//! `docs/architecture/structural-html-emission.md#output-shape`.
55//!
56//! # Carve-outs: bare `<img>` emitters not routed through the synthesizer
57//!
58//! Four emission paths land bare `<img>` HTML in the output stream that
59//! does NOT flow through `synthesize_image_html`. They rely on the regex
60//! post-pass (`build/media/placeholder.rs::add_image_placeholder_attributes`)
61//! for attribute injection (dims/loading/decoding/LQIP). None of them
62//! are bugs — each has a documented architectural reason to stay outside
63//! the synthesizer:
64//!
65//! - **Site logo** (`build/components/nav.rs::render_logo`) — themed UI
66//! affordance, not content. The logo has its own CSS sizing
67//! (`.site-logo { height: 1.8em }`) and does not participate in
68//! LQIP/dims/WebP-variant rendering.
69//! - **RSS read-tracking pixel** (`build/feeds/rss.rs`) — 1×1 `<img>` not
70//! rendered visibly; the synthesizer's dims fallback (800×600) and LQIP
71//! would be wrong for this case.
72//! - **Email body images** (`infra/newsletter.rs`) — email clients (Gmail,
73//! Outlook, Apple Mail) do not consistently support `<picture>` or
74//! `data-placeholder-src`-driven hydration. Keep flat for cross-client
75//! degradation.
76//! - **Raw HTML `<img>` in markdown source** — author-written
77//! `<img src="...">` literally embedded in `.md` files. pulldown-cmark
78//! emits these as `Event::Html` opaque pass-through, so they never reach
79//! `Tag::Image` and are not a moss-controlled emitter. Treated as user
80//! input, the markdown HTML is opaque to the synthesizer and gets only
81//! the additive attribute injection pass.
82//!
83//! Photography/video gallery thumbnails — previously a carve-out — were
84//! folded into the synthesizer in Step 7's commit. The **review colophon
85//! cover** (`build/features/review.rs::render_colophon`) — also previously
86//! a carve-out — was folded in 2026-05-16. Both use
87//! `ImageContext::FolderCardCover` (container-bounded thumbnail semantics).
88//!
89//! These four remaining carve-outs are flagged here so future maintenance
90//! does not drop their attribute injection. Step 7 retired the structural
91//! part of the regex (`wrap_img_in_picture`); the surviving
92//! `add_image_placeholder_attributes` provides additive attrs only for
93//! these bare-img paths.
94
95use crate::asset_paths::to_webp;
96use crate::asset_snapshot::{AssetSnapshot, FALLBACK_HEIGHT, FALLBACK_WIDTH};
97// Same XML-safe escaping used everywhere else in moss for attribute values.
98use crate::media::html_escape;
99use std::collections::BTreeMap;
100use std::path::PathBuf;
101
102/// Where the image lives in the document, which determines the wrapper
103/// element and attribute set.
104///
105/// Step-1 implementation supports only `MarkdownInline` (the default emission
106/// shape from pulldown-cmark's serializer plus the legacy regex pair's added
107/// attributes). Other variants are scaffolded so the call sites in Steps 3-6
108/// can pass them without breaking the byte-shape contract; the synthesizer
109/// produces the same output for all variants until the wrapper-change step.
110///
111/// Step 8 (2026-05-17) made these contexts diverge structurally:
112/// - `MarkdownStandalone { caption }` → `<figure class="moss-image">…[<figcaption>]…</figure>` wrapper
113/// - `MarkdownInline` → bare `<img>` (or `<picture><img></picture>`)
114/// - `Hero` → bare `<img>` (the hero shortcode wraps with `<header>`)
115/// - `FolderCardCover` → bare `<img>` (`.moss-card-cover > ` wraps)
116/// - `LinkPreview` → bare `<img>` (link-preview anchor wraps)
117/// - `Favicon` → bare 16×16 `<img>` with no `<picture>`, no LQIP
118///
119/// Not `Copy` (the embedded `&str` caption would force a lifetime on
120/// every consumer); cloning is cheap (borrow) and the call sites pass by
121/// value through the synthesizer.
122#[derive(Debug, Clone, PartialEq, Eq)]
123pub enum ImageContext<'a> {
124 /// Image-only paragraph in markdown — emits `<figure class="moss-image">`
125 /// around the synthesized `<picture>`/`<img>` output. Used by
126 /// `transform_events`'s three caption-pattern branches:
127 ///
128 /// - **image+emphasis**: ` *caption*` — `caption = Some(emphasis_text)`
129 /// - **separate-emphasis**: image-only paragraph followed by emphasis-
130 /// only paragraph — `caption = Some(emphasis_text)`
131 /// - **implicit figure**: image-only paragraph with non-empty alt and
132 /// `[site].implicit_figure = true` — `caption = Some(alt_text)`
133 ///
134 /// `caption = None` means "figure wrap but no `<figcaption>`" (reserved
135 /// for future callers that want the wrapper structurally without prose).
136 ///
137 /// `width = Some("body|wide|page|screen")` emits `data-width="..."` on
138 /// the outer `<figure>` element per spec § P9. `None` omits the
139 /// attribute entirely so themes can target the absence via
140 /// `:not([data-width])`. `full` aliases to `screen` upstream — values
141 /// reaching this struct are already in canonical value-space.
142 MarkdownStandalone {
143 caption: Option<&'a str>,
144 width: Option<&'a str>,
145 /// Editorial runaround alignment, surfaced as a CSS class on the
146 /// outer `<figure>`. Phase 1 C1 (2026-05-25): Stage 2 dispatcher
147 /// passes `Some("moss-align-left")` / `Some("moss-align-right")`
148 /// when the markdown image's title carries `moss:align=left|right`.
149 /// `None` omits the class.
150 align: Option<&'a str>,
151 /// Arbitrary CSS class names from `moss:classes="foo bar"` title
152 /// params (Phase 1 C1). Each entry is appended to the figure's
153 /// `class="moss-image …"` attribute, space-separated. Empty slice
154 /// leaves the class list at its default (`moss-image`).
155 class_names: &'a [String],
156 /// Arbitrary `key="value"` HTML attributes from leftover
157 /// `moss:` title params (Phase 1 C1). The dispatcher passes
158 /// every param that isn't a known field (kind/width/align/classes)
159 /// through here so future params propagate without code changes.
160 /// Keys are emitted in BTreeMap order for stable byte shape.
161 /// Empty map emits no extra attributes.
162 extra_attrs: &'a BTreeMap<String, String>,
163 },
164 /// Image inside prose, a list, a table cell, or a callout body.
165 /// Always emits bare `<img>` or `<picture><img></picture>`.
166 MarkdownInline,
167 /// `:::hero` shortcode body image. The hero wrapper handles layout.
168 Hero,
169 /// Folder-card cover or child-summary cover image.
170 FolderCardCover,
171 /// External-link preview thumbnail image.
172 LinkPreview,
173 /// Favicon for a link-preview card. Bare 16×16 `<img>`, no `<picture>`,
174 /// no LQIP, no responsive variants.
175 Favicon,
176
177 /// Phase 2 scaffold (filled by Phase 2B agent): site-header / nav logo.
178 /// Bare `<img>` with `class="site-logo"`, no LQIP, no `<picture>`, no
179 /// `loading="lazy"` (logo is above-the-fold). CSS handles sizing
180 /// (`.site-logo { height: 1.8em }`).
181 SiteLogo,
182 /// Phase 2 scaffold (filled by Phase 2C agent): RSS read-tracking pixel.
183 /// 1×1 invisible `<img>`. No `loading="lazy"` (the pixel must fire on
184 /// read for tracking). No LQIP, no `<picture>`.
185 TrackingPixel,
186 /// Phase 2 scaffold (filled by Phase 2D agent): newsletter email body
187 /// image. Email-client-safe HTML subset: no `<picture>`, no `data-*`,
188 /// inline `style="display:block;max-width:100%;height:auto"` for
189 /// responsive email layouts. Explicit dims when known (callers pass
190 /// `Option<u32>` for width/height; missing → omit per email-client
191 /// tolerance).
192 EmailBody {
193 width: Option<u32>,
194 height: Option<u32>,
195 },
196
197 /// Phase 2E v5 PR3 (2026-05-26): `:::gallery` body image. Below-the-
198 /// fold thumbnail (`loading="lazy"`); same `<picture>`/dims/LQIP byte
199 /// shape as `MarkdownInline`. The outer `.moss-gallery-item` wrapper
200 /// is owned by the gallery shortcode's `DefaultHooks` impl in
201 /// `crates/moss-core/src/ast/hooks.rs`; this variant emits just the
202 /// inner `<picture><img></picture>` / `<img>` shape so the wrapper
203 /// can sit around it.
204 ///
205 /// Distinct from `MarkdownInline` so the gallery's per-item style
206 /// passthrough (object-position from `MediaAttrs`) has a typed home
207 /// to evolve into; today both contexts produce the same inner byte
208 /// shape via `synthesize_inner`.
209 GalleryThumb,
210
211 /// Phase 2E PR2 (2026-05-26): bare `<img>` emission with no `<picture>`
212 /// wrap, no `<source>`, no LQIP, no width/height, no `loading` attr.
213 /// Used by the hero typed-renderer fallback path
214 /// (`typed_renderers.rs::render_hero_html_typed`) when no manifest
215 /// (`MediaDimensionLookup`) is in scope — i.e. test / fragment-render
216 /// paths where `AssetRegistry::set_pending` has NOT been called for
217 /// the source's `.webp` companion.
218 ///
219 /// The asset-publish invariant (see `.claude/CLAUDE.md` § "Asset
220 /// publish invariant") requires us to NEVER emit a
221 /// `<source srcset="*.webp">` for an unregistered variant — the
222 /// preview server cannot return placeholder bytes for an URL that
223 /// AssetRegistry doesn't know about, and `<picture>` does not recover
224 /// from a chosen-source 404. `HeroBare` is the explicit opt-out for
225 /// code paths that run before set_pending.
226 ///
227 /// The byte shape mirrors the pre-Phase-2E fallback exactly:
228 /// `<img src="X" alt="Y"[ STYLE] />` where `STYLE` is the inline
229 /// style fragment (already escaped) threaded through
230 /// [`ImageRenderOptions::extra_attrs`] by the caller. The `class` and
231 /// `eager` options are ignored — the hero `<header>` wraps and CSS
232 /// handles loading priority.
233 HeroBare,
234}
235
236/// Optional rendering attributes a caller may pass.
237///
238/// The defaults preserve the current regex-pass byte shape:
239/// - `loading="lazy"` unless `eager=true` (which switches to `loading="eager"
240/// fetchpriority="high"`)
241/// - No extra inline style
242/// - No extra CSS classes on the inner `<img>`
243#[derive(Debug, Default, Clone)]
244pub struct ImageRenderOptions<'a> {
245 /// Above-the-fold loading hint. When true, emits
246 /// `loading="eager" fetchpriority="high"` instead of `loading="lazy"`.
247 pub eager: bool,
248 /// CSS classes to add to the inner `<img>`. Used by link-preview
249 /// favicons (`link-preview-favicon`) and similar UI affordances.
250 pub class: Option<&'a str>,
251 /// Raw extra HTML attribute fragment appended after the standard
252 /// attribute block (e.g., `style="object-fit:cover;object-position:50% 50%"`
253 /// for `:::hero` covers carrying `MediaAttrs`). The caller is responsible
254 /// for HTML-escaping values inside this fragment.
255 pub extra_attrs: Option<&'a str>,
256}
257
258/// Synthesize the HTML for an image reference.
259///
260/// `src` is the resolved URL as it should appear in `<img src=>` (already
261/// passed through the link resolver and dir_overrides for CJK sites).
262///
263/// `alt` is the accessible name. Empty string is permitted for decorative
264/// images; callers in WCAG-sensitive contexts should pass meaningful text.
265///
266/// `assets` is the [`AssetSnapshot`] holding pre-fetched per-path dimensions,
267/// LQIP data URIs, dominant colors, and registered variant kinds (WebP/AVIF).
268/// Phase 1 of the unified-image-emission migration (2026-05-25) replaced the
269/// prior `Option<&MediaDimensionLookup>` parameter with this typed contract —
270/// `MediaDimensionLookup` still populates the snapshot in `pipeline.rs`'s
271/// `build_asset_snapshot` boundary, but the synthesizer no longer probes it
272/// directly. Callers that don't have a populated snapshot (test/fragment-
273/// render paths) pass `&AssetSnapshot::new()`; the synthesizer then emits
274/// fallback dims (800×600) and no LQIP/color style.
275///
276/// `context` and `options` describe the call site. `Favicon` short-circuits
277/// to a 16×16 bare `<img>` (no manifest, no LQIP, no `<picture>`).
278///
279/// Byte-shape contract (preserved through Phase 1's data-source switch):
280///
281/// - With no `<picture>` wrap (non-raster):
282/// `<img src="X" width="W" height="H" loading="lazy" style="…" alt="Y" />`
283/// - Raster originals (png/jpg/jpeg):
284/// `<picture><source srcset="X.webp" type="image/webp"><img src="X" width="W" height="H" loading="lazy" style="…" alt="Y" /></picture>`
285/// - Inline style is `background-image:url(LQIP);background-size:cover` when
286/// the snapshot has LQIP; `background-color:#RRGGBB` when only dominant
287/// color is available; absent when neither.
288/// - For `eager: true`: `loading="eager" fetchpriority="high"` replaces
289/// `loading="lazy"`.
290pub fn synthesize_image_html(
291 src: &str,
292 alt: &str,
293 assets: &AssetSnapshot,
294 context: ImageContext<'_>,
295 options: &ImageRenderOptions<'_>,
296) -> String {
297 // Favicon short-circuit: hardcoded 16×16, no snapshot lookup, no <picture>.
298 // Matches the current emission shape in
299 // `build/markdown/typed_renderers.rs::render_link_preview`. `assets` is
300 // intentionally unused — favicons are UI affordances that never
301 // participate in the variant manifest.
302 if matches!(context, ImageContext::Favicon) {
303 let class_attr = options
304 .class
305 .map(|c| format!(r#" class="{}""#, html_escape(c)))
306 .unwrap_or_default();
307 return format!(
308 r#"<img{} src="{}" width="16" height="16" alt="{}">"#,
309 class_attr,
310 html_escape(src),
311 html_escape(alt),
312 );
313 }
314
315 // Phase 2 scaffold (filled by Phase 2 carve-out agents): the three former
316 // bare-<img> carve-outs become first-class synthesizer contexts. Each
317 // short-circuits before synthesize_inner (which assumes the standard
318 // <picture>/LQIP/dims pipeline that's wrong for these elements).
319 // Site-logo short-circuit (Phase 2B carve-out): bare `<img>` with
320 // `class="site-logo"`, no `<picture>`, no LQIP, no `loading="lazy"` —
321 // the logo is above-the-fold; CSS handles sizing
322 // (`.site-logo { height: 1.8em }`). Attribute order
323 // (`class`, `src`, `alt`, `aria-hidden`) preserves the pre-Phase-2
324 // byte shape emitted by `nav.rs::generate_navigation`.
325 if matches!(context, ImageContext::SiteLogo) {
326 return format!(
327 r#"<img class="site-logo" src="{}" alt="{}" aria-hidden="true">"#,
328 html_escape(src),
329 html_escape(alt),
330 );
331 }
332 if matches!(context, ImageContext::TrackingPixel) {
333 // Phase 2C: RSS read-tracking pixel. 1×1 invisible <img>.
334 // NO loading="lazy" — the pixel must fire on read for tracking.
335 // NO LQIP, NO <picture>, NO alt text (empty alt for invisible
336 // decoration). Self-closing form because this commonly lands in
337 // RSS feed XML (CDATA-wrapped <description>).
338 return format!(
339 r#"<img src="{}" alt="" width="1" height="1" />"#,
340 html_escape(src),
341 );
342 }
343 if matches!(context, ImageContext::HeroBare) {
344 // Phase 2E PR2 (2026-05-26): no-snapshot hero fallback. Byte
345 // shape matches the pre-PR2 emission at
346 // `typed_renderers.rs::render_hero_html_typed` lines 554-557:
347 // `<img src="X" alt="Y"[ STYLE] />`. `assets` is intentionally
348 // unused (the caller passes an empty snapshot via the no-
349 // manifest branch); the snapshot is part of the signature only
350 // for symmetry with the other contexts. `options.class` and
351 // `options.eager` are ignored — hero chrome (CSS / `<header>`)
352 // handles styling and loading priority.
353 //
354 // The inline `style=` fragment that the legacy fallback baked
355 // directly into `format!` is now threaded through
356 // `options.extra_attrs` (the caller pre-escapes the value and
357 // omits the leading space, matching the existing extra_attrs
358 // contract — the synthesizer prepends a single space).
359 let extra = options
360 .extra_attrs
361 .map(|s| format!(" {}", s))
362 .unwrap_or_default();
363 return format!(
364 r#"<img src="{}" alt="{}"{} />"#,
365 html_escape(src),
366 html_escape(alt),
367 extra,
368 );
369 }
370 if let ImageContext::EmailBody { width, height } = context {
371 // Phase 2D (2026-05-25): email-client-safe <img> for newsletter body
372 // images. Email clients do NOT support <picture>, do NOT support
373 // data-* attributes, and frequently strip <style> blocks — inline
374 // `style=` on <img> plus explicit width/height attrs is the
375 // cross-client minimum for responsive layouts. width/height are
376 // Option<u32>: omitted when unknown (e.g. remote URLs that aren't in
377 // AssetSnapshot). Email clients tolerate missing dims at the cost of
378 // a small layout shift.
379 let mut dims = String::new();
380 if let Some(w) = width {
381 dims.push_str(&format!(r#" width="{}""#, w));
382 }
383 if let Some(h) = height {
384 dims.push_str(&format!(r#" height="{}""#, h));
385 }
386 return format!(
387 r#"<img src="{}" alt="{}"{} style="display:block;max-width:100%;height:auto;" />"#,
388 html_escape(src),
389 html_escape(alt),
390 dims,
391 );
392 }
393
394 // Step 8: the inner `<img>` / `<picture>` is shape-equivalent across
395 // every non-favicon context. The wrapping `<figure class="moss-image">`
396 // and optional `<figcaption>` are the only context-dependent
397 // structure. Compute the inner first, then wrap if requested.
398 let inner = synthesize_inner(src, alt, assets, options);
399
400 match context {
401 ImageContext::MarkdownStandalone {
402 caption,
403 width,
404 align,
405 class_names,
406 extra_attrs,
407 } => wrap_in_figure_full(&inner, caption, width, align, class_names, extra_attrs),
408 // All other variants are "no outer wrapper" — caller-owned chrome
409 // (hero `<header>`, folder card container, link preview anchor)
410 // surrounds the bare img/picture output.
411 _ => inner,
412 }
413}
414
415/// Wrap an already-shaped image fragment in the standalone-image
416/// figure container.
417///
418/// `inner_html` is either:
419/// - The output of `synthesize_inner` (markdown `Tag::Image` flowing
420/// through `synthesize_image_html`), or
421/// - A resolve-phase `<img …>` / `<video …>` HTML string emitted by
422/// moss-core's wikilink-lowering (`![[file|display-params]]`).
423///
424/// Output shape:
425///
426/// - `caption = Some(text)`, `width = None`:
427/// ```html
428/// <figure class="moss-image"><picture>…<img …></picture>
429/// <figcaption>text</figcaption></figure>
430/// ```
431/// - `caption = None`, `width = Some("screen")`:
432/// ```html
433/// <figure class="moss-image" data-width="screen"><picture>…<img …></picture></figure>
434/// ```
435/// - `width = None` omits the attribute entirely so themes can target
436/// the absence via `:not([data-width])`. Per spec § P9, `data-width`
437/// sits on the wrapper element (here, `<figure>`) rather than the
438/// inner `<img>`.
439///
440/// Caption text is HTML-escaped at the boundary. Future work: allow
441/// markdown formatting inside the caption via an explicit
442/// `CaptionMarkdown` variant on `ImageContext`.
443///
444/// `pub(super)` so `build/markdown/pipeline.rs` can call this directly
445/// for the raw-HTML media branch of `emit_standalone_figure_image`
446/// without duplicating the wrapper byte shape. The synthesizer is the
447/// single source of truth for `<figure class="moss-image">` — when the
448/// wrapper class evolves (e.g. `moss-image moss-image--auto` per the
449/// Step-8 spec), only this function changes.
450pub fn wrap_in_figure(
451 inner_html: &str,
452 caption: Option<&str>,
453 width: Option<&str>,
454) -> String {
455 // 3-arg shorthand kept for the raw-HTML media branch in
456 // pipeline.rs::emit_standalone_figure_image (wikilink display-keyword
457 // images that don't carry moss: title params — no align / extra
458 // classes / extra attrs). Delegates to the canonical wrapper so the
459 // byte shape stays defined in exactly one place.
460 let empty_classes: &[String] = &[];
461 let empty_attrs: BTreeMap<String, String> = BTreeMap::new();
462 wrap_in_figure_full(inner_html, caption, width, None, empty_classes, &empty_attrs)
463}
464
465/// Canonical `<figure>`-wrapping function consumed by both `synthesize_image_html`
466/// for `MarkdownStandalone` and the 3-arg compatibility shim `wrap_in_figure`.
467///
468/// Class list assembly: `class="moss-image{ align_class?}{ class_names…}"`.
469/// Extra attrs render as `key="escaped_value"` in BTreeMap order, after
470/// `data-width=` and before the inner content.
471pub(super) fn wrap_in_figure_full(
472 inner_html: &str,
473 caption: Option<&str>,
474 width: Option<&str>,
475 align: Option<&str>,
476 class_names: &[String],
477 extra_attrs: &BTreeMap<String, String>,
478) -> String {
479 // `width` here is a closed-set &'static str from `match_width_token`
480 // ("body" | "wide" | "page" | "screen"). The `html_escape` call is
481 // defensive belt-and-braces — it never actually substitutes — and is
482 // kept for symmetry with the embed-renderer side's `html_escape_attr`.
483 let width_attr = width
484 .map(|w| format!(r#" data-width="{}""#, html_escape(w)))
485 .unwrap_or_default();
486
487 // Compose the class attribute: `moss-image` first (the structural
488 // hook), then the optional align class, then any author-supplied
489 // class names. Single space separator keeps the byte shape stable
490 // across the empty / align-only / class-only / both permutations.
491 let mut class_value = String::from("moss-image");
492 if let Some(a) = align {
493 class_value.push(' ');
494 class_value.push_str(a);
495 }
496 for cn in class_names {
497 if cn.is_empty() {
498 continue;
499 }
500 class_value.push(' ');
501 class_value.push_str(cn);
502 }
503 let class_attr = format!(r#" class="{}""#, html_escape(&class_value));
504
505 // Extra attrs are emitted in BTreeMap order (deterministic byte shape).
506 let mut extra = String::new();
507 for (k, v) in extra_attrs {
508 extra.push(' ');
509 extra.push_str(k);
510 extra.push_str(r#"=""#);
511 extra.push_str(&html_escape(v));
512 extra.push('"');
513 }
514
515 match caption {
516 Some(text) => format!(
517 r#"<figure{class}{w}{extra}>{inner}<figcaption>{cap}</figcaption></figure>"#,
518 class = class_attr,
519 w = width_attr,
520 extra = extra,
521 inner = inner_html,
522 cap = html_escape(text),
523 ),
524 None => format!(
525 r#"<figure{class}{w}{extra}>{inner}</figure>"#,
526 class = class_attr,
527 w = width_attr,
528 extra = extra,
529 inner = inner_html,
530 ),
531 }
532}
533
534/// Synthesize the inner `<img>` (or `<picture><img></picture>`) without
535/// the standalone-figure wrapper. Shared by every non-favicon context.
536fn synthesize_inner(
537 src: &str,
538 alt: &str,
539 assets: &AssetSnapshot,
540 options: &ImageRenderOptions<'_>,
541) -> String {
542 let img_tag = render_img_tag(src, alt, assets, options);
543
544 // For raster originals, always emit <picture><source srcset=X.webp>.
545 // The preview server's AssetRegistry intercept (preview/server/placeholder.rs)
546 // ensures the webp URL never 404s in preview mode — it returns LQIP bytes
547 // for Pending entries — and publish mode encodes variants synchronously
548 // before HTML ships (PluginMode::Blocking). So the URL is always live in
549 // both modes.
550 //
551 // We must never emit a <source> that might 404 because a chosen <source>
552 // 404 is non-recoverable inside <picture> per HTML spec §
553 // "update-the-source-set" + § "update-the-image-data": browser commits to
554 // the chosen URL, fetch fails, image state goes to broken, error fires —
555 // browser does NOT walk back to the inner <img>.
556 //
557 // For non-raster sources (svg, favicons via Favicon context), no variant
558 // exists; emit the bare <img>.
559 //
560 // Pattern: explicit promise model. See
561 // docs/plans/2026-05-20-image-variant-honest-mirror.md (Layer 3).
562 if is_raster_original(src) {
563 // to_webp(src) inherits the dir_overrides + relative-prefix already
564 // applied to `src` by the upstream renderer. Swapping the extension
565 // on `src` is what keeps the synthesizer's emitted URL aligned with
566 // the AssetRegistry's registered key (blocking.rs's set_pending loop
567 // uses the same to_webp(mapped) derivation).
568 let srcset_path = to_webp(src);
569 format!(
570 r#"<picture><source srcset="{}" type="image/webp">{}</picture>"#,
571 html_escape(&srcset_path),
572 img_tag,
573 )
574 } else {
575 img_tag
576 }
577}
578
579/// Returns true when `src` is a raster original that always gets a webp
580/// variant from moss's image pipeline. Restricted to the three formats that
581/// `should_skip` never filters out by content sniffing — png, jpg, jpeg. Gif
582/// is excluded because animated GIFs skip webp encoding (image.rs § should_skip,
583/// `is_animated_gif`); SVG is excluded as a vector format; webp originals are
584/// excluded because the variant URL would equal the src URL. Restricting here
585/// keeps the synthesizer's emitted `<source>` URL in lockstep with the
586/// AssetRegistry's `set_pending` registration in blocking.rs (which loops over
587/// `collect_images_for_conversion`'s output, also filtered by `should_skip`).
588fn is_raster_original(src: &str) -> bool {
589 let lower = src.to_ascii_lowercase();
590 lower.ends_with(".png") || lower.ends_with(".jpg") || lower.ends_with(".jpeg")
591}
592
593/// Try several path normalizations against `AssetSnapshot.dimensions` so the
594/// synthesizer matches the same set of input forms the prior
595/// `MediaDimensionLookup::get` handled. `src` may arrive as the resolved URL
596/// with a leading `/` (review colophon covers, cover.rs absolute paths) or
597/// with a `./` / `../` relative prefix (CJK dir_overrides); scan stores keys
598/// in plain relative form. The probe order mirrors the lookup's:
599///
600/// 1. exact match
601/// 2. leading-`/` stripped (absolute-to-relative)
602/// 3. leading `./` / `../` stripped (relative normalization)
603///
604/// Returns `None` when none of the variants is in the snapshot. The caller
605/// supplies the fallback (800×600 for dims, no style for LQIP / color).
606fn lookup_dims(assets: &AssetSnapshot, src: &str) -> Option<(u32, u32)> {
607 probe_paths(src, |p| assets.dims(&p))
608}
609
610fn lookup_lqip<'a>(assets: &'a AssetSnapshot, src: &str) -> Option<&'a str> {
611 probe_paths(src, |p| assets.lqip(&p))
612}
613
614fn lookup_color<'a>(assets: &'a AssetSnapshot, src: &str) -> Option<&'a String> {
615 probe_paths(src, |p| assets.dominant_color.get(&p))
616}
617
618fn probe_paths<T>(src: &str, mut probe: impl FnMut(PathBuf) -> Option<T>) -> Option<T> {
619 if let Some(v) = probe(PathBuf::from(src)) {
620 return Some(v);
621 }
622 let stripped = src.strip_prefix('/').unwrap_or(src);
623 if stripped != src {
624 if let Some(v) = probe(PathBuf::from(stripped)) {
625 return Some(v);
626 }
627 }
628 let mut s: &str = src;
629 while let Some(rest) = s.strip_prefix("./").or_else(|| s.strip_prefix("../")) {
630 s = rest;
631 }
632 if s != src {
633 if let Some(v) = probe(PathBuf::from(s)) {
634 return Some(v);
635 }
636 }
637 None
638}
639
640/// Emit just the `<img>` tag with all attributes. Internal helper for
641/// `synthesize_image_html` — exposed as `pub(crate)` only for snapshot tests
642/// that want to assert against the bare img output without the optional
643/// `<picture>` wrapper.
644pub(crate) fn render_img_tag(
645 src: &str,
646 alt: &str,
647 assets: &AssetSnapshot,
648 options: &ImageRenderOptions<'_>,
649) -> String {
650 // AssetSnapshot's `dims` is keyed by PathBuf; the src arrives as the
651 // resolved URL the upstream renderer baked (potentially absolute, e.g.
652 // `/image/cover.jpg`). Scan stores relative keys (`image/cover.jpg`),
653 // so the synthesizer probes both forms via `lookup_dims`. Snapshot
654 // lookups absent → fall back to the legacy 800×600 (matches the prior
655 // `MediaDimensionLookup::get` semantics before the Phase 1 B1 migration).
656 // Stem fallback (extension-mismatch — e.g. `.mov` vs `.mp4`) was
657 // previously handled in MediaDimensionLookup::get; since AssetSnapshot
658 // exposes only exact-path access, that case will need follow-up if
659 // production sites rely on it (likely only for video posters, which
660 // are out of this Tag::Image path).
661 let (width, height) = lookup_dims(assets, src).unwrap_or((FALLBACK_WIDTH, FALLBACK_HEIGHT));
662
663 let class_attr = options
664 .class
665 .map(|c| format!(r#" class="{}""#, html_escape(c)))
666 .unwrap_or_default();
667
668 let (loading_attr, fetchpriority_attr) = if options.eager {
669 (r#" loading="eager""#, r#" fetchpriority="high""#)
670 } else {
671 (r#" loading="lazy""#, "")
672 };
673
674 // Suppress LQIP / dominant-color style when extra_attrs already carries
675 // a style= attribute (e.g., `:::hero {attrs="cover-fit=contain"}` passes
676 // `style="object-fit:contain"` through extra_attrs). The browser would
677 // honor the LAST style= it sees and drop the LQIP, so emitting both
678 // produces malformed HTML and loses the placeholder. The legacy regex
679 // pass (`placeholder.rs:413-422`) had the same has_style guard; this
680 // preserves parity. Future work: merge the two declarations into a
681 // single style= via a typed `ImageRenderOptions::media_attrs` field so
682 // the synthesizer owns escaping end-to-end (impl-review item 9).
683 let extra_has_style = options
684 .extra_attrs
685 .map(|s| s.contains("style="))
686 .unwrap_or(false);
687
688 let style_attr = if extra_has_style {
689 String::new()
690 } else if let Some(lqip) = lookup_lqip(assets, src) {
691 format!(
692 r#" style="background-image:url({});background-size:cover""#,
693 lqip
694 )
695 } else if let Some(color) = lookup_color(assets, src) {
696 format!(r#" style="background-color:{}""#, color)
697 } else {
698 String::new()
699 };
700
701 let extra = options
702 .extra_attrs
703 .map(|s| format!(" {}", s))
704 .unwrap_or_default();
705
706 // `data-placeholder-src` removed 2026-05-20: the iframe-bridge handler
707 // now matches by URL substring against `src` / `srcset` (see
708 // frontend/bridge/iframe-bridge.ts, moss-asset-ready branch). The
709 // AssetRegistry's promise model + the preview server's URL-keyed lookup
710 // make the attribute redundant. See
711 // docs/plans/2026-05-20-image-variant-honest-mirror.md (Layer 3).
712 //
713 // Inline LQIP via `background-image: url(data:image/jpeg;base64,…)` is
714 // kept — legitimate production technique (cf. Vercel `blurDataURL`,
715 // nextjs.org/docs/app/api-reference/components/image). Shows a blurred
716 // preview instantly while the actual bytes are being decoded.
717 format!(
718 r#"<img{class_attr} src="{src_esc}" width="{w}" height="{h}"{loading}{fetch}{style} alt="{alt}"{extra} />"#,
719 class_attr = class_attr,
720 src_esc = html_escape(src),
721 w = width,
722 h = height,
723 loading = loading_attr,
724 fetch = fetchpriority_attr,
725 style = style_attr,
726 alt = html_escape(alt),
727 extra = extra,
728 )
729}
730
731#[cfg(test)]
732mod tests {
733 use super::*;
734 use crate::asset_snapshot::VariantKindSet;
735
736 /// Build an AssetSnapshot with a single entry — the per-test fixture
737 /// shape after the Phase 1 B1 migration (2026-05-25). Replaces the prior
738 /// `MediaDimensionLookup`-based `lookup(vec![img_meta(...)])` builder.
739 /// The snapshot keys are `PathBuf` per `AssetSnapshot`'s contract; the
740 /// stem-derived `variants` entry mirrors what
741 /// `AssetRegistry::iter_registered_variants` would populate when a WebP
742 /// variant is registered.
743 fn snapshot_with(
744 path: &str,
745 dims: Option<(u32, u32)>,
746 color: Option<&str>,
747 lqip: Option<&str>,
748 webp: bool,
749 ) -> AssetSnapshot {
750 let mut s = AssetSnapshot::new();
751 let key = PathBuf::from(path);
752 if let Some(d) = dims {
753 s.dimensions.insert(key.clone(), d);
754 }
755 if let Some(c) = color {
756 s.dominant_color.insert(key.clone(), c.to_string());
757 }
758 if let Some(l) = lqip {
759 s.lqip.insert(key.clone(), l.to_string());
760 }
761 if webp {
762 let stem = crate::asset_snapshot::path_strip_extension(&key);
763 s.variants.insert(
764 stem,
765 VariantKindSet {
766 webp: true,
767 avif: false,
768 },
769 );
770 }
771 s
772 }
773
774 fn snapshot_dims(path: &str, w: u32, h: u32) -> AssetSnapshot {
775 snapshot_with(path, Some((w, h)), None, None, false)
776 }
777
778 // --- <picture>-wrapped shape (raster originals always wrapped 2026-05-20) ---
779
780 #[test]
781 fn picture_wrap_for_raster_original_no_lqip() {
782 // After 2026-05-20: synthesizer always emits <picture> for png/jpg/jpeg
783 // originals. The preview server's AssetRegistry intercept ensures the
784 // webp URL resolves (LQIP bytes for Pending, real bytes for Ready);
785 // publish-mode synchronous encoding ensures it never 404s in
786 // production. data-placeholder-src is gone — iframe-bridge matches
787 // by URL substring now.
788 let s = snapshot_dims("photo.jpg", 800, 600);
789 let html = synthesize_image_html(
790 "photo.jpg",
791 "A cat",
792 &s,
793 ImageContext::MarkdownInline,
794 &ImageRenderOptions::default(),
795 );
796 assert_eq!(
797 html,
798 r#"<picture><source srcset="photo.webp" type="image/webp"><img src="photo.jpg" width="800" height="600" loading="lazy" alt="A cat" /></picture>"#
799 );
800 }
801
802 #[test]
803 fn picture_wrap_for_raster_original_with_lqip() {
804 // LQIP inline style is preserved (legitimate production technique;
805 // cf. Vercel `blurDataURL`). Shown to the user instantly while the
806 // actual bytes are being decoded.
807 let s = snapshot_with(
808 "photo.jpg",
809 Some((800, 600)),
810 None,
811 Some("data:image/jpeg;base64,abc"),
812 false,
813 );
814 let html = synthesize_image_html(
815 "photo.jpg",
816 "A cat",
817 &s,
818 ImageContext::MarkdownInline,
819 &ImageRenderOptions::default(),
820 );
821 assert_eq!(
822 html,
823 r#"<picture><source srcset="photo.webp" type="image/webp"><img src="photo.jpg" width="800" height="600" loading="lazy" style="background-image:url(data:image/jpeg;base64,abc);background-size:cover" alt="A cat" /></picture>"#
824 );
825 }
826
827 #[test]
828 fn bare_img_with_dominant_color_no_lqip() {
829 let s = snapshot_with(
830 "photo.jpg",
831 Some((800, 600)),
832 Some("#aabbcc"),
833 None,
834 false,
835 );
836 let html = synthesize_image_html(
837 "photo.jpg",
838 "Cat",
839 &s,
840 ImageContext::MarkdownInline,
841 &ImageRenderOptions::default(),
842 );
843 assert!(
844 html.contains(r#"style="background-color:#aabbcc""#),
845 "Got: {html}"
846 );
847 }
848
849 // --- <picture> wrap (WebP variant present) ----------------------------
850
851 #[test]
852 fn picture_wrap_when_webp_exists() {
853 let s = snapshot_with("photo.jpg", Some((800, 600)), None, None, true);
854 let html = synthesize_image_html(
855 "photo.jpg",
856 "Cat",
857 &s,
858 ImageContext::MarkdownInline,
859 &ImageRenderOptions::default(),
860 );
861 // Outer: <picture>...</picture> with <source> first
862 assert!(
863 html.starts_with(r#"<picture><source srcset="photo.webp" type="image/webp"><img"#),
864 "Got: {html}"
865 );
866 assert!(html.ends_with(r#"alt="Cat" /></picture>"#), "Got: {html}");
867 }
868
869 #[test]
870 fn picture_srcset_uses_to_webp_of_src_not_stored_variant() {
871 // CJK-path case: <img src> already carries dir_overrides + relative
872 // prefix (e.g. ../assets/photo.jpg). srcset must derive from src
873 // (../assets/photo.webp), not the manifest's stored value.
874 // See wrap_img_in_picture's rationale at placeholder.rs:660.
875 let s = snapshot_with("../assets/photo.jpg", Some((800, 600)), None, None, true);
876 let html = synthesize_image_html(
877 "../assets/photo.jpg",
878 "",
879 &s,
880 ImageContext::MarkdownInline,
881 &ImageRenderOptions::default(),
882 );
883 assert!(
884 html.contains(r#"srcset="../assets/photo.webp""#),
885 "srcset should inherit src's prefix; got: {html}"
886 );
887 }
888
889 // --- eager loading ----------------------------------------------------
890
891 #[test]
892 fn eager_swaps_loading_attr_and_adds_fetchpriority() {
893 let s = snapshot_dims("photo.jpg", 1, 1);
894 let html = synthesize_image_html(
895 "photo.jpg",
896 "Hero",
897 &s,
898 ImageContext::Hero,
899 &ImageRenderOptions {
900 eager: true,
901 ..Default::default()
902 },
903 );
904 assert!(
905 html.contains(r#"loading="eager" fetchpriority="high""#),
906 "Got: {html}"
907 );
908 assert!(!html.contains(r#"loading="lazy""#), "Got: {html}");
909 }
910
911 // --- favicon short-circuit --------------------------------------------
912
913 #[test]
914 fn favicon_is_bare_16x16_with_class() {
915 // No manifest data for the favicon URL — synthesizer must NOT probe
916 // the snapshot (favicons are not registered as moss assets).
917 let s = AssetSnapshot::new();
918 let html = synthesize_image_html(
919 "https://example.com/favicon.ico",
920 "",
921 &s,
922 ImageContext::Favicon,
923 &ImageRenderOptions {
924 class: Some("link-preview-favicon"),
925 ..Default::default()
926 },
927 );
928 assert_eq!(
929 html,
930 r#"<img class="link-preview-favicon" src="https://example.com/favicon.ico" width="16" height="16" alt="">"#
931 );
932 }
933
934 // --- site-logo short-circuit (Phase 2B carve-out) --------------------
935
936 #[test]
937 fn synthesize_site_logo_basic_shape() {
938 let html = synthesize_image_html(
939 "assets/logo.png",
940 "",
941 &AssetSnapshot::new(),
942 ImageContext::SiteLogo,
943 &ImageRenderOptions::default(),
944 );
945 assert_eq!(
946 html,
947 r#"<img class="site-logo" src="assets/logo.png" alt="" aria-hidden="true">"#
948 );
949 }
950
951 #[test]
952 fn synthesize_site_logo_escapes_src() {
953 let html = synthesize_image_html(
954 r#"logo "with quotes".png"#,
955 "",
956 &AssetSnapshot::new(),
957 ImageContext::SiteLogo,
958 &ImageRenderOptions::default(),
959 );
960 assert!(
961 html.contains(r#"logo "with quotes".png"#),
962 "got: {html}"
963 );
964 }
965
966 #[test]
967 fn synthesize_site_logo_does_not_emit_picture_or_lqip() {
968 // Even when the snapshot would normally drive LQIP/<picture> for a
969 // png, SiteLogo must short-circuit and emit a bare <img>.
970 let mut snap = AssetSnapshot::new();
971 snap.lqip
972 .insert("logo.png".into(), "data:image/jpeg;base64,xxx".into());
973 let html = synthesize_image_html(
974 "logo.png",
975 "moss",
976 &snap,
977 ImageContext::SiteLogo,
978 &ImageRenderOptions::default(),
979 );
980 assert!(!html.contains("<picture"), "logo should not get picture wrap: {html}");
981 assert!(
982 !html.contains("background-image"),
983 "logo should not get LQIP: {html}"
984 );
985 assert!(
986 !html.contains("loading="),
987 "logo above-the-fold, no lazy-load: {html}"
988 );
989 }
990
991 // --- HTML-escape contract --------------------------------------------
992
993 #[test]
994 fn alt_with_quotes_is_escaped() {
995 let s = snapshot_dims("photo.jpg", 1, 1);
996 let html = synthesize_image_html(
997 "photo.jpg",
998 r#"Quote: "hi""#,
999 &s,
1000 ImageContext::MarkdownInline,
1001 &ImageRenderOptions::default(),
1002 );
1003 // moss_core::media::html_escape escapes " → " — never leave a
1004 // raw quote inside an attribute value.
1005 assert!(html.contains(r#"alt="Quote: "hi"""#), "Got: {html}");
1006 }
1007
1008 #[test]
1009 fn extra_attrs_passed_through_verbatim() {
1010 // :::hero passes `style="object-fit:cover;object-position:50% 50%"`
1011 // via MediaAttrs::to_inline_style — the caller pre-escapes, so we
1012 // just append.
1013 let s = snapshot_dims("hero.jpg", 1920, 1080);
1014 let html = synthesize_image_html(
1015 "hero.jpg",
1016 "",
1017 &s,
1018 ImageContext::Hero,
1019 &ImageRenderOptions {
1020 eager: true,
1021 extra_attrs: Some(r#"data-cover-fit="cover""#),
1022 ..Default::default()
1023 },
1024 );
1025 assert!(html.contains(r#"data-cover-fit="cover""#), "Got: {html}");
1026 // Extra attrs come AFTER alt — matches the current regex-pass order
1027 // where the regex preserves the original post-src attributes.
1028 let alt_pos = html.find("alt=").unwrap();
1029 let extra_pos = html.find("data-cover-fit=").unwrap();
1030 assert!(extra_pos > alt_pos, "extra attrs should come after alt");
1031 }
1032
1033 /// Regression test for impl-review finding 2026-05-16: when extra_attrs
1034 /// already carries a `style=` attribute (the `:::hero {attrs=...}` case
1035 /// when MediaAttrs::to_inline_style() returns Some), the synthesizer
1036 /// must NOT also emit its own LQIP-derived `style=`. The legacy regex
1037 /// pass had a `has_style` guard at `placeholder.rs:413-422` that did the
1038 /// same suppression. Without this, browsers see two `style=` attributes
1039 /// on one element, honor the last one, and drop the LQIP placeholder.
1040 #[test]
1041 fn lqip_style_suppressed_when_extra_attrs_has_style() {
1042 let s = snapshot_with(
1043 "hero.jpg",
1044 Some((1920, 1080)),
1045 None,
1046 Some("data:image/jpeg;base64,abc"),
1047 false,
1048 );
1049 let html = synthesize_image_html(
1050 "hero.jpg",
1051 "",
1052 &s,
1053 ImageContext::Hero,
1054 &ImageRenderOptions {
1055 eager: true,
1056 extra_attrs: Some(r#"style="object-fit:cover;object-position:50% 50%""#),
1057 ..Default::default()
1058 },
1059 );
1060 // Exactly one `style=` substring — the one the caller passed.
1061 assert_eq!(
1062 html.matches("style=").count(),
1063 1,
1064 "expected exactly one style= attribute; got: {html}"
1065 );
1066 // Confirm the caller's style is what survived (not the LQIP).
1067 assert!(
1068 html.contains(r#"style="object-fit:cover"#),
1069 "caller-supplied style must survive; got: {html}"
1070 );
1071 assert!(
1072 !html.contains(r#"background-image:url(data:"#),
1073 "LQIP must be suppressed when extra_attrs carries style=; got: {html}"
1074 );
1075 }
1076
1077 // --- Step 8: figure wrapper for MarkdownStandalone --------------------
1078
1079 /// Phase 1 C1 test helper: build an empty extras BTreeMap.
1080 fn empty_extras() -> std::collections::BTreeMap<String, String> {
1081 std::collections::BTreeMap::new()
1082 }
1083
1084 #[test]
1085 fn markdown_standalone_no_caption_wraps_in_figure() {
1086 // No caption → `<figure class="moss-image">…</figure>` around the
1087 // synthesized `<picture>`/`<img>` with no `<figcaption>`.
1088 let s = snapshot_dims("photo.jpg", 800, 600);
1089 let extras = empty_extras();
1090 let html = synthesize_image_html(
1091 "photo.jpg",
1092 "Alt text",
1093 &s,
1094 ImageContext::MarkdownStandalone {
1095 caption: None,
1096 width: None,
1097 align: None,
1098 class_names: &[],
1099 extra_attrs: &extras,
1100 },
1101 &ImageRenderOptions::default(),
1102 );
1103 assert!(html.starts_with(r#"<figure class="moss-image">"#));
1104 assert!(html.ends_with("</figure>"));
1105 assert!(!html.contains("<figcaption>"));
1106 assert!(html.contains("<img"));
1107 }
1108
1109 #[test]
1110 fn markdown_standalone_with_caption_adds_figcaption() {
1111 let s = snapshot_dims("photo.jpg", 800, 600);
1112 let extras = empty_extras();
1113 let html = synthesize_image_html(
1114 "photo.jpg",
1115 "Alt text",
1116 &s,
1117 ImageContext::MarkdownStandalone {
1118 caption: Some("A nice photo"),
1119 width: None,
1120 align: None,
1121 class_names: &[],
1122 extra_attrs: &extras,
1123 },
1124 &ImageRenderOptions::default(),
1125 );
1126 assert!(html.starts_with(r#"<figure class="moss-image">"#));
1127 assert!(html.contains("<figcaption>A nice photo</figcaption>"));
1128 assert!(html.ends_with("</figure>"));
1129 }
1130
1131 #[test]
1132 fn markdown_standalone_caption_is_html_escaped() {
1133 let s = snapshot_dims("photo.jpg", 800, 600);
1134 let extras = empty_extras();
1135 let html = synthesize_image_html(
1136 "photo.jpg",
1137 "",
1138 &s,
1139 ImageContext::MarkdownStandalone {
1140 caption: Some(r#"Q&A "best" of <em>2024</em>"#),
1141 width: None,
1142 align: None,
1143 class_names: &[],
1144 extra_attrs: &extras,
1145 },
1146 &ImageRenderOptions::default(),
1147 );
1148 assert!(
1149 html.contains("<figcaption>Q&A "best" of <em>2024</em></figcaption>"),
1150 "caption text must be HTML-escaped at the boundary; got: {html}"
1151 );
1152 }
1153
1154 #[test]
1155 fn markdown_standalone_wraps_picture_when_webp_present() {
1156 // When the manifest carries a WebP variant, the synthesizer emits
1157 // a `<picture>` wrap inside the figure: the structural figure
1158 // and the responsive picture compose without conflict.
1159 let s = snapshot_with("photo.jpg", Some((1200, 800)), None, None, true);
1160 let extras = empty_extras();
1161 let html = synthesize_image_html(
1162 "photo.jpg",
1163 "Alt",
1164 &s,
1165 ImageContext::MarkdownStandalone {
1166 caption: Some("Cap"),
1167 width: None,
1168 align: None,
1169 class_names: &[],
1170 extra_attrs: &extras,
1171 },
1172 &ImageRenderOptions::default(),
1173 );
1174 // Structural order: figure > picture > source + img > figcaption
1175 let fig_idx = html.find(r#"<figure class="moss-image">"#).expect("figure");
1176 let pic_idx = html.find("<picture>").expect("picture");
1177 let src_idx = html.find("<source").expect("source");
1178 let img_idx = html.find("<img").expect("img");
1179 let cap_idx = html.find("<figcaption>").expect("figcaption");
1180 let fig_close = html.find("</figure>").expect("figure close");
1181 assert!(fig_idx < pic_idx, "<picture> must be inside <figure>");
1182 assert!(pic_idx < src_idx);
1183 assert!(src_idx < img_idx);
1184 assert!(img_idx < cap_idx, "<figcaption> follows <picture>");
1185 assert!(cap_idx < fig_close);
1186 }
1187
1188 #[test]
1189 fn markdown_inline_does_not_wrap_in_figure() {
1190 // Inline images NEVER get a figure wrapper — they sit in prose.
1191 let s = snapshot_dims("photo.jpg", 800, 600);
1192 let html = synthesize_image_html(
1193 "photo.jpg",
1194 "Alt",
1195 &s,
1196 ImageContext::MarkdownInline,
1197 &ImageRenderOptions::default(),
1198 );
1199 assert!(!html.contains("<figure"));
1200 assert!(!html.contains("<figcaption>"));
1201 }
1202
1203 // --- spec § P9 width: `data-width` on the figure wrapper -------------
1204
1205 #[test]
1206 fn markdown_standalone_width_screen_emits_data_width_on_figure() {
1207 // Width pipe-alias `![[photo.jpg|full]]` → `screen` lands on the
1208 // figure wrapper, not the inner img. The image-side test below
1209 // pins the "absent by default" half of the contract.
1210 let s = snapshot_dims("photo.jpg", 800, 600);
1211 let extras = empty_extras();
1212 let html = synthesize_image_html(
1213 "photo.jpg",
1214 "",
1215 &s,
1216 ImageContext::MarkdownStandalone {
1217 caption: None,
1218 width: Some("screen"),
1219 align: None,
1220 class_names: &[],
1221 extra_attrs: &extras,
1222 },
1223 &ImageRenderOptions::default(),
1224 );
1225 assert!(
1226 html.starts_with(r#"<figure class="moss-image" data-width="screen">"#),
1227 "data-width must sit on the figure wrapper; got: {html}"
1228 );
1229 // The inner img must NOT carry data-width — the attribute is the
1230 // wrapper's responsibility per spec.
1231 assert!(
1232 !html.contains(r#"<img"#) || !html[html.find("<img").unwrap()..].contains("data-width="),
1233 "inner <img> must not carry data-width; got: {html}"
1234 );
1235 }
1236
1237 #[test]
1238 fn markdown_standalone_width_wide_with_caption() {
1239 // width + caption compose: both attributes / children appear in
1240 // the wrapper.
1241 let s = snapshot_dims("photo.jpg", 800, 600);
1242 let extras = empty_extras();
1243 let html = synthesize_image_html(
1244 "photo.jpg",
1245 "Alt",
1246 &s,
1247 ImageContext::MarkdownStandalone {
1248 caption: Some("A nice photo"),
1249 width: Some("wide"),
1250 align: None,
1251 class_names: &[],
1252 extra_attrs: &extras,
1253 },
1254 &ImageRenderOptions::default(),
1255 );
1256 assert!(html.contains(r#"data-width="wide""#), "got: {html}");
1257 assert!(
1258 html.contains("<figcaption>A nice photo</figcaption>"),
1259 "got: {html}"
1260 );
1261 }
1262
1263 #[test]
1264 fn markdown_standalone_width_none_omits_data_width() {
1265 // Negative test: the default (no width) must not emit the attribute,
1266 // so theme authors can target the absence via `:not([data-width])`.
1267 let s = snapshot_dims("photo.jpg", 800, 600);
1268 let extras = empty_extras();
1269 let html = synthesize_image_html(
1270 "photo.jpg",
1271 "",
1272 &s,
1273 ImageContext::MarkdownStandalone {
1274 caption: None,
1275 width: None,
1276 align: None,
1277 class_names: &[],
1278 extra_attrs: &extras,
1279 },
1280 &ImageRenderOptions::default(),
1281 );
1282 assert!(!html.contains("data-width="), "got: {html}");
1283 }
1284
1285 #[test]
1286 fn wrap_in_figure_width_emits_data_width_attribute() {
1287 // Direct-call contract test: `wrap_in_figure` is the single source
1288 // of truth for the figure wrapper byte shape; the raw-HTML branch
1289 // of `emit_standalone_figure_image` calls it with the lifted width.
1290 let html = wrap_in_figure(r#"<img src="x" />"#, None, Some("page"));
1291 assert_eq!(
1292 html,
1293 r#"<figure class="moss-image" data-width="page"><img src="x" /></figure>"#
1294 );
1295 }
1296
1297 #[test]
1298 fn wrap_in_figure_width_with_caption() {
1299 let html = wrap_in_figure(r#"<img src="x" />"#, Some("hello"), Some("screen"));
1300 assert_eq!(
1301 html,
1302 r#"<figure class="moss-image" data-width="screen"><img src="x" /><figcaption>hello</figcaption></figure>"#
1303 );
1304 }
1305
1306 #[test]
1307 fn wrap_in_figure_no_width_no_attribute() {
1308 let html = wrap_in_figure(r#"<img src="x" />"#, None, None);
1309 assert_eq!(
1310 html,
1311 r#"<figure class="moss-image"><img src="x" /></figure>"#
1312 );
1313 }
1314
1315 #[test]
1316 fn markdown_standalone_no_manifest_still_wraps_in_figure() {
1317 // The wrapper is structural identity (Step 8 contract), not
1318 // manifest-dependent. Even with an empty AssetSnapshot (test/
1319 // fragment-render path), `<figure class="moss-image">` still wraps
1320 // the synthesized `<img>`. The Phase 1 B1 migration (2026-05-25)
1321 // replaced the `Option<&MediaDimensionLookup>` parameter with
1322 // `&AssetSnapshot`; the empty-snapshot path is now the test
1323 // equivalent of the prior `None` lookup.
1324 let s = AssetSnapshot::new();
1325 let extras = empty_extras();
1326 let html = synthesize_image_html(
1327 "photo.jpg",
1328 "Alt",
1329 &s,
1330 ImageContext::MarkdownStandalone {
1331 caption: Some("Cap"),
1332 width: None,
1333 align: None,
1334 class_names: &[],
1335 extra_attrs: &extras,
1336 },
1337 &ImageRenderOptions::default(),
1338 );
1339 assert!(html.starts_with(r#"<figure class="moss-image">"#));
1340 assert!(html.contains("<img"));
1341 assert!(html.contains("<figcaption>Cap</figcaption>"));
1342 assert!(html.ends_with("</figure>"));
1343 }
1344
1345 // --- size fallback ----------------------------------------------------
1346
1347 #[test]
1348 fn missing_dimensions_fall_back_to_800x600() {
1349 let s = AssetSnapshot::new();
1350 let html = synthesize_image_html(
1351 "ghost.jpg",
1352 "",
1353 &s,
1354 ImageContext::MarkdownInline,
1355 &ImageRenderOptions::default(),
1356 );
1357 // FALLBACK_WIDTH / FALLBACK_HEIGHT (still 800×600, sourced from
1358 // `moss_core::asset_snapshot::FALLBACK_WIDTH` so the synthesizer and
1359 // the surviving regex pass agree on the absent-dims default).
1360 assert!(html.contains(r#"width="800" height="600""#), "Got: {html}");
1361 }
1362
1363 // --- regex-pass idempotency on synthesizer output ----------------------
1364 //
1365 // Phase 2E v5 PR5 (2026-05-26) retired the Stage 3 regex post-pass; the
1366 // image synthesizer in this module is now the sole emitter of width /
1367 // height / loading / LQIP / dominant-color attributes for moss-emitted
1368 // <img> tags. The three idempotency tests at
1369 // `src-tauri/tests/image_synth_regex_parity.rs` that guarded the
1370 // regex+synth byte-shape parity were deleted alongside the regex.
1371
1372 // --- TrackingPixel (Phase 2C, 2026-05-25) ---
1373 //
1374 // The RSS read-tracking pixel is a 1×1 invisible <img>. It must fire on
1375 // read (so NO loading="lazy"), carry empty alt (decorative), and never
1376 // be wrapped in <picture> / decorated with LQIP. Self-closing form
1377 // because the call site embeds it in CDATA-wrapped RSS XML.
1378
1379 #[test]
1380 fn synthesize_tracking_pixel_basic() {
1381 let html = synthesize_image_html(
1382 "https://api.mosspub.com/pixel.gif?u=abc",
1383 "",
1384 &AssetSnapshot::new(),
1385 ImageContext::TrackingPixel,
1386 &ImageRenderOptions::default(),
1387 );
1388 assert_eq!(
1389 html,
1390 r#"<img src="https://api.mosspub.com/pixel.gif?u=abc" alt="" width="1" height="1" />"#
1391 );
1392 }
1393
1394 #[test]
1395 fn synthesize_tracking_pixel_escapes_url() {
1396 let html = synthesize_image_html(
1397 r#"x.gif?u=a&b="c""#,
1398 "",
1399 &AssetSnapshot::new(),
1400 ImageContext::TrackingPixel,
1401 &ImageRenderOptions::default(),
1402 );
1403 assert!(html.contains("&"), "& must be escaped");
1404 assert!(html.contains("""), "\" must be escaped");
1405 }
1406
1407 #[test]
1408 fn synthesize_tracking_pixel_no_lazy_no_lqip() {
1409 // Even when the snapshot contains LQIP / dimensions for the pixel
1410 // path, the TrackingPixel short-circuit must ignore them — pixels
1411 // are tracking beacons, not images.
1412 let mut snap = AssetSnapshot::new();
1413 snap.lqip.insert(
1414 "pixel.gif".into(),
1415 "data:image/jpeg;base64,xxx".into(),
1416 );
1417 let html = synthesize_image_html(
1418 "pixel.gif",
1419 "",
1420 &snap,
1421 ImageContext::TrackingPixel,
1422 &ImageRenderOptions::default(),
1423 );
1424 assert!(
1425 !html.contains("loading=\"lazy\""),
1426 "must NOT lazy-load (must fire on read)"
1427 );
1428 assert!(
1429 !html.contains("background-image"),
1430 "must NOT carry LQIP"
1431 );
1432 assert!(
1433 !html.contains("<picture"),
1434 "must NOT wrap in picture"
1435 );
1436 }
1437
1438 // --- ImageContext::EmailBody (Phase 2D, 2026-05-25) -------------------
1439 //
1440 // Email-client-safe carve-out: no <picture>, no data-*, no loading=lazy.
1441 // Inline `style="display:block;max-width:100%;height:auto;"` is the
1442 // cross-client responsive pattern. width/height attrs are Option<u32>:
1443 // emitted when known, omitted when None.
1444
1445 #[test]
1446 fn synthesize_email_body_with_dims() {
1447 let html = synthesize_image_html(
1448 "https://media.example.com/photo.jpg",
1449 "Cover",
1450 &AssetSnapshot::new(),
1451 ImageContext::EmailBody {
1452 width: Some(600),
1453 height: Some(400),
1454 },
1455 &ImageRenderOptions::default(),
1456 );
1457 assert!(html.contains(r#"width="600""#));
1458 assert!(html.contains(r#"height="400""#));
1459 assert!(html.contains(r#"style="display:block;max-width:100%;height:auto;""#));
1460 }
1461
1462 #[test]
1463 fn synthesize_email_body_without_dims() {
1464 let html = synthesize_image_html(
1465 "x.jpg",
1466 "alt",
1467 &AssetSnapshot::new(),
1468 ImageContext::EmailBody {
1469 width: None,
1470 height: None,
1471 },
1472 &ImageRenderOptions::default(),
1473 );
1474 assert!(!html.contains("width="), "width should be omitted when None");
1475 assert!(!html.contains("height="), "height should be omitted when None");
1476 }
1477
1478 #[test]
1479 fn synthesize_email_body_no_picture_no_data() {
1480 let html = synthesize_image_html(
1481 "photo.jpg",
1482 "alt",
1483 &AssetSnapshot::new(),
1484 ImageContext::EmailBody {
1485 width: None,
1486 height: None,
1487 },
1488 &ImageRenderOptions::default(),
1489 );
1490 assert!(!html.contains("<picture"), "email images must not use <picture>");
1491 assert!(!html.contains("<source"), "no <source>");
1492 assert!(!html.contains("data-"), "no data-* (email clients strip)");
1493 assert!(!html.contains("loading="), "email clients ignore loading attr");
1494 assert!(
1495 !html.contains("background-image"),
1496 "email clients strip inline style URLs"
1497 );
1498 }
1499
1500 #[test]
1501 fn synthesize_email_body_escapes() {
1502 let html = synthesize_image_html(
1503 r#"https://x.com/photo.jpg?a=1&b=2"#,
1504 r#"alt with "quotes""#,
1505 &AssetSnapshot::new(),
1506 ImageContext::EmailBody {
1507 width: None,
1508 height: None,
1509 },
1510 &ImageRenderOptions::default(),
1511 );
1512 assert!(html.contains("&"), "& must be escaped");
1513 assert!(html.contains("""), "\" must be escaped");
1514 }
1515
1516 // --- ImageContext::GalleryThumb (Phase 2E v5 PR3, 2026-05-26) ---------
1517 //
1518 // Gallery body images: below-the-fold thumbnail, same inner byte
1519 // shape as MarkdownInline (`<picture><source srcset=*.webp><img
1520 // loading="lazy" ...></picture>` for raster, bare `<img>` for
1521 // non-raster). The outer `.moss-gallery-item` wrapper is owned by
1522 // `DefaultHooks::render_shortcode`'s Gallery arm; this variant
1523 // emits only the inner image. Distinguishing it from
1524 // MarkdownInline at the type level keeps per-item passthrough
1525 // attributes (object-position from MediaAttrs) typed for future
1526 // evolution.
1527
1528 #[test]
1529 fn synthesize_gallery_thumb_emits_picture_with_lazy() {
1530 let p = ImageRenderOptions::default();
1531 let mut snap = AssetSnapshot::new();
1532 snap.dimensions
1533 .insert(PathBuf::from("photo.jpg"), (1200, 800));
1534 let out = synthesize_image_html(
1535 "photo.jpg",
1536 "alt",
1537 &snap,
1538 ImageContext::GalleryThumb,
1539 &p,
1540 );
1541 assert!(out.contains("<picture"), "{out}");
1542 assert!(out.contains(r#"srcset="photo.webp""#), "{out}");
1543 assert!(out.contains(r#"loading="lazy""#), "{out}");
1544 assert!(out.contains(r#"width="1200""#), "{out}");
1545 assert!(out.contains(r#"height="800""#), "{out}");
1546 assert!(out.contains(r#"alt="alt""#), "{out}");
1547 }
1548
1549 #[test]
1550 fn synthesize_gallery_thumb_non_raster_bare_img() {
1551 // SVG / .webp originals don't trigger the <picture> wrap (no
1552 // variant exists). Falls back to bare <img> with lazy loading +
1553 // dims from the snapshot.
1554 let p = ImageRenderOptions::default();
1555 let mut snap = AssetSnapshot::new();
1556 snap.dimensions
1557 .insert(PathBuf::from("icon.svg"), (64, 64));
1558 let out = synthesize_image_html(
1559 "icon.svg",
1560 "",
1561 &snap,
1562 ImageContext::GalleryThumb,
1563 &p,
1564 );
1565 assert!(!out.contains("<picture"), "{out}");
1566 assert!(!out.contains("<source"), "{out}");
1567 assert!(out.contains(r#"loading="lazy""#), "{out}");
1568 assert!(out.contains(r#"width="64""#), "{out}");
1569 }
1570
1571 #[test]
1572 fn synthesize_gallery_thumb_threads_extra_attrs() {
1573 // The Gallery hook builds a `style="object-position:..."` fragment
1574 // from MediaAttrs and passes it via extra_attrs. The synthesizer
1575 // suppresses its own LQIP-derived style= when extra_attrs already
1576 // carries one — verify that suppression engages here too
1577 // (parity with Hero / MarkdownInline).
1578 let snap = snapshot_with(
1579 "photo.jpg",
1580 Some((1200, 800)),
1581 None,
1582 Some("data:image/jpeg;base64,abc"),
1583 false,
1584 );
1585 let opts = ImageRenderOptions {
1586 extra_attrs: Some(r#"style="object-position:50% 50%""#),
1587 ..Default::default()
1588 };
1589 let out = synthesize_image_html(
1590 "photo.jpg",
1591 "",
1592 &snap,
1593 ImageContext::GalleryThumb,
1594 &opts,
1595 );
1596 assert_eq!(
1597 out.matches("style=").count(),
1598 1,
1599 "expected exactly one style= attribute; got: {out}"
1600 );
1601 assert!(
1602 out.contains(r#"style="object-position:50% 50%""#),
1603 "caller-supplied style must survive; got: {out}"
1604 );
1605 }
1606
1607 // --- ImageContext::HeroBare (Phase 2E PR2, 2026-05-26) ----------------
1608 //
1609 // The no-snapshot hero fallback. Emits a bare `<img>` with no
1610 // `<picture>`, no `<source>`, no LQIP, no dims, no `loading` attr.
1611 // The asset-publish invariant rules out emitting a
1612 // `<source srcset="*.webp">` for an unregistered variant — this
1613 // variant is the explicit opt-out for code paths that run before
1614 // `AssetRegistry::set_pending` has been called for the source's
1615 // `.webp` companion (test/fragment-render paths). The byte shape
1616 // mirrors the pre-PR2 fallback at
1617 // `typed_renderers.rs::render_hero_html_typed` lines 554-557.
1618
1619 #[test]
1620 fn synthesize_hero_bare_basic_shape() {
1621 let out = synthesize_image_html(
1622 "cover.jpg",
1623 "",
1624 &AssetSnapshot::new(),
1625 ImageContext::HeroBare,
1626 &ImageRenderOptions::default(),
1627 );
1628 // No <picture>, no <source>, no class, no loading, no LQIP, no
1629 // width/height attrs. Exact byte shape with empty alt.
1630 assert_eq!(out, r#"<img src="cover.jpg" alt="" />"#, "got: {}", out);
1631 }
1632
1633 #[test]
1634 fn synthesize_hero_bare_with_style_via_extra_attrs() {
1635 // The legacy fallback passed an inline `style="..."` fragment
1636 // built from MediaAttrs::to_inline_style(). PR2 threads that
1637 // fragment through `ImageRenderOptions::extra_attrs` — the
1638 // synthesizer prepends a single space, matching the legacy byte
1639 // shape.
1640 let out = synthesize_image_html(
1641 "cover.jpg",
1642 "",
1643 &AssetSnapshot::new(),
1644 ImageContext::HeroBare,
1645 &ImageRenderOptions {
1646 extra_attrs: Some(r#"style="object-fit:cover;object-position:50% 50%""#),
1647 ..Default::default()
1648 },
1649 );
1650 assert_eq!(
1651 out,
1652 r#"<img src="cover.jpg" alt="" style="object-fit:cover;object-position:50% 50%" />"#,
1653 "got: {}",
1654 out
1655 );
1656 }
1657
1658 #[test]
1659 fn synthesize_hero_bare_with_lqip_in_snapshot_still_bare() {
1660 // Even when the snapshot has LQIP / dims for the source path,
1661 // the HeroBare variant must ignore them — the no-snapshot signal
1662 // is structural (this variant exists precisely because no
1663 // AssetRegistry has been primed), not data-driven.
1664 let mut snap = AssetSnapshot::new();
1665 snap.lqip
1666 .insert("cover.jpg".into(), "data:image/jpeg;base64,xxx".into());
1667 snap.dimensions.insert("cover.jpg".into(), (1920, 1080));
1668 let out = synthesize_image_html(
1669 "cover.jpg",
1670 "",
1671 &snap,
1672 ImageContext::HeroBare,
1673 &ImageRenderOptions::default(),
1674 );
1675 assert!(!out.contains("<picture"), "got: {}", out);
1676 assert!(!out.contains("<source"), "got: {}", out);
1677 assert!(!out.contains("background-image"), "got: {}", out);
1678 assert!(!out.contains("width="), "got: {}", out);
1679 assert!(!out.contains("height="), "got: {}", out);
1680 assert!(!out.contains("loading="), "got: {}", out);
1681 }
1682
1683 #[test]
1684 fn synthesize_hero_bare_escapes_url() {
1685 // The synthesizer's html_escape covers `&` and `"`; the legacy
1686 // fallback used the same `html_escape` from build::media::cover.
1687 let out = synthesize_image_html(
1688 r#"x.jpg?a=1&b="c""#,
1689 "",
1690 &AssetSnapshot::new(),
1691 ImageContext::HeroBare,
1692 &ImageRenderOptions::default(),
1693 );
1694 assert!(out.contains("&"), "& must be escaped; got: {}", out);
1695 assert!(out.contains("""), "\" must be escaped; got: {}", out);
1696 }
1697
1698 #[test]
1699 fn synthesize_hero_bare_byte_shape_matches_legacy_fallback() {
1700 // Pin the byte shape against a literal reconstruction of the
1701 // pre-PR2 emission so a future "tidy" of the synthesizer's
1702 // HeroBare branch can't drift away from the legacy fallback
1703 // without flipping this assertion deliberately.
1704 //
1705 // Legacy line:
1706 // format!("<img src=\"{}\" alt=\"\"{} />", html_escape(href), style)
1707 // where `style` was `""` or ` style="..."` (with leading space).
1708 let href = "covers/img.jpg";
1709 let style_fragment = r#" style="object-fit:contain""#;
1710 let legacy = format!(
1711 "<img src=\"{}\" alt=\"\"{} />",
1712 html_escape(href),
1713 style_fragment,
1714 );
1715
1716 // PR2 path: thread the style through extra_attrs minus the leading
1717 // space (matches typed_renderers.rs migration).
1718 let pr2 = synthesize_image_html(
1719 href,
1720 "",
1721 &AssetSnapshot::new(),
1722 ImageContext::HeroBare,
1723 &ImageRenderOptions {
1724 extra_attrs: Some(style_fragment.trim_start()),
1725 ..Default::default()
1726 },
1727 );
1728 assert_eq!(pr2, legacy, "byte shape divergence: pr2={} legacy={}", pr2, legacy);
1729 }
1730}