1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
//! Image HTML synthesizer — the single entry point for emitting `<img>` /
//! `<picture>` markup in moss output.
//!
//! See [`docs/reference/structural-html-emission.md`](../../../../docs/reference/structural-html-emission.md)
//! for the architectural principle: structural HTML decisions are made at the
//! typed-data layer (pulldown-cmark events, shortcode AST, typed component
//! props), with all three call sites converging on the function in this
//! module. Regex post-passes are reserved for non-markdown-origin attribute
//! injection only.
//!
//! # Migration state (post-Step-7, 2026-05-16)
//!
//! Steps 1-7 of the structural-html-emission migration are complete:
//! - Step 1: extracted `synthesize_image_html`
//! - Step 2: routed markdown `Tag::Image` events
//! - Step 3: routed `:::hero` shortcode image
//! - Step 4: routed link-preview favicon
//! - Step 6: routed every cover image path (folder cards, child summary
//! cards, folder index hero, photo/video gallery thumbnails) through
//! `render_cover_html`
//! - Step 7: retired `wrap_img_in_picture` (the structural part of the
//! legacy regex post-pass). The synthesizer now owns every `<picture>`
//! wrap in moss output. `add_image_placeholder_attributes` survives as
//! the attribute-injection seam for the documented carve-outs (see
//! below).
//!
//! The byte-shape contract is captured by snapshot tests at the bottom of
//! this file. They are the line of defense against accidental output
//! drift; any future change to attribute order, quoting, or whitespace
//! must update them deliberately.
//!
//! Later steps will:
//! - Step 8: switch `MarkdownStandalone` to a `<figure class="moss-image">`
//! wrapper (breaking change for user themes — staged separately)
//! - Add AVIF `<source>` lines once the image pipeline produces AVIF
//! - Drop the inline LQIP `style=` in favor of a wrapper CSS custom prop
//!
//! # Step-8 contract: synthesizer owns the outer `<figure>` (planned)
//!
//! `transform_events` currently wraps the synthesizer's `MarkdownStandalone`
//! output in its own `<figure>` for the three caption-pattern branches
//! (image+emphasis, separate-emphasis, implicit-figure). After Step 8 the
//! synthesizer emits `<figure class="moss-image">` itself; if `transform_events`
//! still wraps, the output will be `<figure><figure class="moss-image">...</figure>
//! <figcaption>...</figcaption></figure>` — invalid double-wrap.
//!
//! The Step-8 contract: caption flows into the synthesizer via
//! `MarkdownStandalone { caption: Option<&str> }` (or a richer
//! `CaptionMarkdown` for emphasis-in-caption support), and the three
//! caption-pattern branches collapse into a single `Event::Html(
//! synthesize_image_html(..., MarkdownStandalone { caption }))` emission.
//! The `<figcaption>` becomes the synthesizer's responsibility, NOT
//! `transform_events`. Captures the spec at
//! `docs/reference/structural-html-emission.md#output-shape`.
//!
//! # Carve-outs: bare `<img>` emitters not routed through the synthesizer
//!
//! Four emission paths land bare `<img>` HTML in the output stream that
//! does NOT flow through `synthesize_image_html`. They rely on the regex
//! post-pass (`build/media/placeholder.rs::add_image_placeholder_attributes`)
//! for attribute injection (dims/loading/decoding/LQIP). None of them
//! are bugs — each has a documented architectural reason to stay outside
//! the synthesizer:
//!
//! - **Site logo** (`build/components/nav.rs::render_logo`) — themed UI
//! affordance, not content. The logo has its own CSS sizing
//! (`.site-logo { height: 1.8em }`) and does not participate in
//! LQIP/dims/WebP-variant rendering.
//! - **RSS read-tracking pixel** (`build/feeds/rss.rs`) — 1×1 `<img>` not
//! rendered visibly; the synthesizer's dims fallback (800×600) and LQIP
//! would be wrong for this case.
//! - **Email body images** (`infra/newsletter.rs`) — email clients (Gmail,
//! Outlook, Apple Mail) do not consistently support `<picture>` or
//! `data-placeholder-src`-driven hydration. Keep flat for cross-client
//! degradation.
//! - **Raw HTML `<img>` in markdown source** — author-written
//! `<img src="...">` literally embedded in `.md` files. pulldown-cmark
//! emits these as `Event::Html` opaque pass-through, so they never reach
//! `Tag::Image` and are not a moss-controlled emitter. Treated as user
//! input, the markdown HTML is opaque to the synthesizer and gets only
//! the additive attribute injection pass.
//!
//! Photography/video gallery thumbnails — previously a carve-out — were
//! folded into the synthesizer in Step 7's commit. The **review colophon
//! cover** (`build/features/review.rs::render_colophon`) — also previously
//! a carve-out — was folded in 2026-05-16. Both use
//! `ImageContext::FolderCardCover` (container-bounded thumbnail semantics).
//!
//! These four remaining carve-outs are flagged here so future maintenance
//! does not drop their attribute injection. Step 7 retired the structural
//! part of the regex (`wrap_img_in_picture`); the surviving
//! `add_image_placeholder_attributes` provides additive attrs only for
//! these bare-img paths.
use crate;
use crate;
use cratesizes as ctx_sizes;
// Same XML-safe escaping used everywhere else in moss for attribute values.
use cratehtml_escape;
use BTreeMap;
use PathBuf;
/// Where the image lives in the document, which determines the wrapper
/// element and attribute set.
///
/// Step-1 implementation supports only `MarkdownInline` (the default emission
/// shape from pulldown-cmark's serializer plus the legacy regex pair's added
/// attributes). Other variants are scaffolded so the call sites in Steps 3-6
/// can pass them without breaking the byte-shape contract; the synthesizer
/// produces the same output for all variants until the wrapper-change step.
///
/// Step 8 (2026-05-17) made these contexts diverge structurally:
/// - `MarkdownStandalone { caption }` → `<figure class="moss-image">…[<figcaption>]…</figure>` wrapper
/// - `MarkdownInline` → bare `<img>` (or `<picture><img></picture>`)
/// - `Hero` → bare `<img>` (the hero shortcode wraps with `<header>`)
/// - `FolderCardCover` → bare `<img>` (`.moss-card-cover > ` wraps)
/// - `LinkPreview` → bare `<img>` (link-preview anchor wraps)
/// - `Favicon` → bare 16×16 `<img>` with no `<picture>`, no LQIP
///
/// Not `Copy` (the embedded `&str` caption would force a lifetime on
/// every consumer); cloning is cheap (borrow) and the call sites pass by
/// value through the synthesizer.
/// Optional rendering attributes a caller may pass.
///
/// The defaults preserve the current regex-pass byte shape:
/// - `loading="lazy"` unless `eager=true` (which switches to `loading="eager"
/// fetchpriority="high"`)
/// - No extra inline style
/// - No extra CSS classes on the inner `<img>`
/// Synthesize the HTML for an image reference.
///
/// `src` is the resolved URL as it should appear in `<img src=>` (already
/// passed through the link resolver and dir_overrides for CJK sites).
///
/// `alt` is the accessible name. Empty string is permitted for decorative
/// images; callers in WCAG-sensitive contexts should pass meaningful text.
///
/// `assets` is the [`AssetSnapshot`] holding pre-fetched per-path dimensions,
/// LQIP data URIs, dominant colors, and registered variant kinds (WebP/AVIF).
/// Phase 1 of the unified-image-emission migration (2026-05-25) replaced the
/// prior `Option<&MediaDimensionLookup>` parameter with this typed contract —
/// `MediaDimensionLookup` still populates the snapshot in `pipeline.rs`'s
/// `build_asset_snapshot` boundary, but the synthesizer no longer probes it
/// directly. Callers that don't have a populated snapshot (test/fragment-
/// render paths) pass `&AssetSnapshot::new()`; the synthesizer then emits
/// fallback dims (800×600) and no LQIP/color style.
///
/// `context` and `options` describe the call site. `Favicon` short-circuits
/// to a 16×16 bare `<img>` (no manifest, no LQIP, no `<picture>`).
///
/// Byte-shape contract (preserved through Phase 1's data-source switch):
///
/// - With no `<picture>` wrap (non-raster):
/// `<img src="X" width="W" height="H" loading="lazy" style="…" alt="Y" />`
/// - Raster originals (png/jpg/jpeg):
/// `<picture><source srcset="X.webp" type="image/webp"><img src="X" width="W" height="H" loading="lazy" style="…" alt="Y" /></picture>`
/// - Inline style is `background-image:url(LQIP);background-size:cover` when
/// the snapshot has LQIP; `background-color:#RRGGBB` when only dominant
/// color is available; absent when neither.
/// - For `eager: true`: `loading="eager" fetchpriority="high"` replaces
/// `loading="lazy"`.
/// Wrap an already-shaped image fragment in the standalone-image
/// figure container.
///
/// `inner_html` is either:
/// - The output of `synthesize_inner` (markdown `Tag::Image` flowing
/// through `synthesize_image_html`), or
/// - A resolve-phase `<img …>` / `<video …>` HTML string emitted by
/// moss-core's wikilink-lowering (`![[file|display-params]]`).
///
/// Output shape:
///
/// - `caption = Some(text)`, `width = None`:
/// ```html
/// <figure class="moss-image"><picture>…<img …></picture>
/// <figcaption>text</figcaption></figure>
/// ```
/// - `caption = None`, `width = Some("screen")`:
/// ```html
/// <figure class="moss-image" data-width="screen"><picture>…<img …></picture></figure>
/// ```
/// - `width = None` omits the attribute entirely so themes can target
/// the absence via `:not([data-width])`. Per spec § P9, `data-width`
/// sits on the wrapper element (here, `<figure>`) rather than the
/// inner `<img>`.
///
/// Caption text is HTML-escaped at the boundary. Future work: allow
/// markdown formatting inside the caption via an explicit
/// `CaptionMarkdown` variant on `ImageContext`.
///
/// `pub(super)` so `build/markdown/pipeline.rs` can call this directly
/// for the raw-HTML media branch of `emit_standalone_figure_image`
/// without duplicating the wrapper byte shape. The synthesizer is the
/// single source of truth for `<figure class="moss-image">` — when the
/// wrapper class evolves (e.g. `moss-image moss-image--auto` per the
/// Step-8 spec), only this function changes.
/// Canonical `<figure>`-wrapping function consumed by both `synthesize_image_html`
/// for `MarkdownStandalone` and the 3-arg compatibility shim `wrap_in_figure`.
///
/// Class list assembly: `class="moss-image{ align_class?}{ class_names…}"`.
/// Extra attrs render as `key="escaped_value"` in BTreeMap order, after
/// `data-width=` and before the inner content.
pub
/// Synthesize the inner `<img>` (or `<picture><img></picture>`) without
/// the standalone-figure wrapper. Shared by every non-favicon context.
///
/// `sizes_value` is the context-resolved `sizes=` attribute value
/// (`contract::sizes`); it is only emitted when the source is wide enough
/// to have ladder rungs — narrow/unknown-dims sources keep the legacy
/// single-URL `<source>` byte shape.
/// Returns true when `src` is a raster original that always gets a webp
/// variant from moss's image pipeline. EMISSION side of the shared ladder
/// gate: extracts `src`'s extension and delegates membership to
/// [`is_ladder_source_ext`] — the ONE predicate the pipeline census sites
/// (registration/encode/sweep/heal) also consume.
///
/// After Phase B (Task 12) this also matches webp, so `synthesize_inner`
/// checks [`is_webp_source`] FIRST and routes webp to the `<img srcset>`
/// branch — a webp reaching THIS predicate's `<picture>` branch would emit a
/// useless `<source>` identical to the inner `<img>`. Reaching here therefore
/// means png/jpg/jpeg in practice (the webp branch already returned).
///
/// Note: this check is extension-only. `collect_images_for_conversion` applies
/// additional content-based filters (e.g. `SkipReason::NotAnImage` for files
/// whose magic bytes don't match the declared format). A file that passes
/// `is_raster_original` here but is filtered by `NotAnImage` will NOT have
/// `set_pending` called for it — the synthesizer still emits a `<picture>`, but
/// its `<source>` webp URL is unregistered, so the preview server falls through
/// to ServeDir and the variant 404s. It does NOT serve the LQIP placeholder —
/// that path is reserved for `set_pending` (Pending) entries. Benign in
/// practice: this only occurs for genuinely corrupt files (e.g. an HTML 404
/// page saved as .png) that are not referenced from content.
/// Returns true when `src` is a webp SOURCE (extension `.webp`, case-
/// insensitive). EMISSION side of the webp-vs-conversion split: a webp source
/// carries the responsive ladder directly on `<img srcset>` (no `<picture>`),
/// so `synthesize_inner` tests this before [`is_raster_original`]. Delegates
/// to [`is_webp_source_ext`] — the single extension gate in `asset_paths`.
/// Try several path normalizations against `AssetSnapshot.dimensions` so the
/// synthesizer matches the same set of input forms the prior
/// `MediaDimensionLookup::get` handled. `src` may arrive as the resolved URL
/// with a leading `/` (review colophon covers, cover.rs absolute paths) or
/// with a `./` / `../` relative prefix (CJK dir_overrides); scan stores keys
/// in plain relative form. The probe order mirrors the lookup's:
///
/// 1. exact match
/// 2. leading-`/` stripped (absolute-to-relative)
/// 3. leading `./` / `../` stripped (relative normalization)
///
/// Returns `None` when none of the variants is in the snapshot. The caller
/// supplies the fallback (800×600 for dims, no style for LQIP / color).
/// Whether `src` is a scan-flagged animated source. Probes the SAME path
/// normalizations as [`lookup_dims`] against `AssetSnapshot.animated` (keyed
/// identically to `dimensions`, both populated per-source in
/// `build_asset_snapshot`), so a webp found for dims is found for animation
/// too. Missing everywhere → `false` (test/fragment-render paths with an empty
/// snapshot treat sources as non-animated). Only the webp ladder branch
/// consults this — png/jpg/jpeg are never animated through the `<picture>`
/// path (see `asset_paths::ladder_rungs` census doc).
/// Resolve the responsive ladder for `src`: the rung widths (strictly below the
/// deployed base) and the deployed base WIDTH — or `None` when dims are unknown
/// (snapshot miss) or the ladder is empty (small/animated source). Shared by
/// BOTH emission paths (webp `<img srcset>` and png/jpg `<picture><source>`) so
/// the `lookup_dims → ladder_rungs → is_empty → deployed_width` derivation
/// CANNOT drift between them — and it must agree with registration/encode,
/// which call the identical `ladder_rungs`/`deployed_width` (see the
/// deterministic-agreement contract on [`crate::asset_paths::ladder_rungs`],
/// including its EXIF-orientation agreement).
/// Assemble a `srcset` value: one `to_webp_rung(src, w) {w}w` candidate per
/// rung, then the base descriptor `{base_url} {base_w}w`. Shared by BOTH
/// emission paths so the rung-URL derivation and descriptor shape cannot drift
/// between them (and must agree with what registration/encode name). The ONLY
/// difference is `base_url`: a webp SOURCE passes `src` itself (the served base
/// IS the source — `to_webp(src) == src`); a png/jpg/jpeg source passes
/// `to_webp(src)` (the converted `<picture>` base). Rung URLs derive from `src`
/// in both cases. Caller HTML-escapes the returned value.
/// Percent-encode literal commas (`,` → `%2C`) in one `srcset` candidate URL.
///
/// `srcset` is a comma-delimited candidate list, so a literal comma inside a
/// URL — which a comma-named source (`a,b.jpg`) produces, since
/// `percent_encode_path_segments` keeps `,` literal by design — would mis-split
/// the list in browsers AND in `html_post`'s `rewrite_srcset_candidates`.
/// Comma is the ONLY char touched (`src` was already encoded upstream and never
/// carries a `%2C`, so no double-encode); applied ONLY to `srcset` candidates —
/// the base `<img src>` keeps its single, unambiguous literal comma. The
/// deployed file has a literal comma on disk; a static server decodes `%2C` → `,`
/// when resolving (verified for the preview server in `router.rs`'s `%2C` test).
/// Probe `src` plus its leading-`/` and leading-`./`/`../`-stripped forms.
/// Percent-decode `%XX` byte sequences in a URL path (pure, zero-I/O).
/// The single implementation lives next to the encoder it inverts; see
/// [`crate::resolve::fuzzy_path::percent_decode_path`].
/// Emit just the `<img>` tag with all attributes. Internal helper for
/// `synthesize_image_html` — exposed as `pub(crate)` only for snapshot tests
/// that want to assert against the bare img output without the optional
/// `<picture>` wrapper.
///
/// `srcset_sizes` is `Some((srcset, sizes))` ONLY for the Phase-B webp ladder
/// (Task 12), which carries the responsive candidates on the `<img>` itself
/// rather than a `<source>`. When `Some`, ` srcset="…" sizes="…"` is emitted
/// immediately after `src=` (both values HTML-escaped, matching the
/// `<picture>` path's escaping). When `None` — every other caller and every
/// non-laddered webp — the output is BYTE-IDENTICAL to the pre-Task-12 shape.
pub