use std::borrow::Cow;
#[cfg(any(feature = "metadata", feature = "inline-images"))]
use std::collections::BTreeMap;
use crate::converter::Context;
use crate::converter::dom_context::DomContext;
use crate::converter::handlers::srcset::{Descriptor, parse_descriptor, srcset_candidates};
use crate::converter::inline::link::{append_url_destination, escape_markdown_title};
use crate::converter::main_helpers::tag_name_eq;
use crate::converter::media::is_inline_data;
use crate::converter::utility::attributes::decoded_attribute;
use crate::converter::utility::escaping::escape_link_label;
use crate::converter::utility::preprocessing::sanitize_markdown_url;
use crate::options::{ConversionOptions, InlineDataMedia};
#[cfg(feature = "inline-images")]
use crate::converter::media::handle_inline_data_image;
#[cfg(feature = "visitor")]
use crate::converter::utility::serialization::serialize_node;
#[cfg(feature = "metadata")]
type ImageMetadataPayload = (BTreeMap<String, String>, Option<u32>, Option<u32>);
#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_lines)]
#[cfg_attr(not(feature = "visitor"), allow(unused_variables))]
pub fn handle_img(
node_handle: &tl::NodeHandle,
tag: &tl::HTMLTag,
parser: &tl::Parser,
output: &mut String,
options: &ConversionOptions,
ctx: &Context,
depth: usize,
dom_ctx: &DomContext,
) {
let src: Cow<'_, str> = {
let skip_inline_data = options.inline_data_media != InlineDataMedia::Keep;
let mut effective_src = resolve_effective_src(tag, skip_inline_data);
if skip_inline_data && is_inline_data(&effective_src) {
if let Some(source_src) = picture_source_src(node_handle, parser, dom_ctx) {
effective_src = Cow::Owned(source_src);
}
}
let base_resolved = ctx.resolve_url(&effective_src);
Cow::Owned(sanitize_markdown_url(base_resolved.as_deref().unwrap_or(&effective_src)).into_owned())
};
let alt = decoded_attribute(tag, "alt").unwrap_or(Cow::Borrowed(""));
let title = decoded_attribute(tag, "title").filter(|v| !v.is_empty());
#[cfg(feature = "metadata")]
#[allow(clippy::useless_let_if_seq)]
let mut metadata_payload: Option<ImageMetadataPayload> = None;
#[cfg(feature = "metadata")]
if ctx.metadata_wants_images {
let mut attributes_map = BTreeMap::new();
let mut width: Option<u32> = None;
let mut height: Option<u32> = None;
for (key, value_opt) in tag.attributes().iter() {
let key_str = key.to_string();
if key_str == "src" {
continue;
}
let value = value_opt.map(|v| v.to_string()).unwrap_or_default();
if key_str == "width" {
if let Ok(parsed) = value.parse::<u32>() {
width = Some(parsed);
}
} else if key_str == "height" {
if let Ok(parsed) = value.parse::<u32>() {
height = Some(parsed);
}
}
attributes_map.insert(key_str, value);
}
metadata_payload = Some((attributes_map, width, height));
}
#[cfg(feature = "inline-images")]
if let Some(ref collector_ref) = ctx.inline_collector {
if is_inline_data(&src) {
let mut attributes_map = BTreeMap::new();
for (key, value_opt) in tag.attributes().iter() {
let key_str = key.to_string();
let keep = key_str == "width"
|| key_str == "height"
|| key_str == "filename"
|| key_str == "aria-label"
|| key_str.starts_with("data-");
if keep {
let value = value_opt.map(|value| value.to_string()).unwrap_or_default();
attributes_map.insert(key_str, value);
}
}
handle_inline_data_image(
collector_ref,
src.as_ref(),
alt.as_ref(),
title.as_deref(),
attributes_map,
);
}
}
let keep_as_markdown = (ctx.in_heading && ctx.heading_allow_inline_images)
|| ctx.cell_allow_inline_images
|| ctx.link_allow_inline_images;
let inline_data = ctx.inline_data_treatment(options.inline_data_media, &src);
let should_use_alt_text = inline_data == InlineDataMedia::AltTextOnly
|| (!keep_as_markdown && (ctx.convert_as_inline || (ctx.in_heading && !ctx.heading_allow_inline_images)));
let render = || {
(inline_data != InlineDataMedia::DropElement).then(|| {
format_image_markdown(
&src,
&alt,
title.as_deref(),
should_use_alt_text,
options.link_style,
options.url_escape_style,
ctx.reference_collector.as_ref(),
)
})
};
#[cfg(feature = "visitor")]
let image_output = if let Some(ref visitor_handle) = ctx.visitor {
use crate::visitor::{NodeContext, NodeType, VisitResult};
let node_id = node_handle.get_inner();
let parent_tag = dom_ctx.parent_tag_name(node_id, parser);
let index_in_parent = dom_ctx.get_sibling_index(node_id).unwrap_or(0);
let node_ctx = NodeContext::with_lazy_attributes(
NodeType::Image,
Cow::Borrowed("img"),
tag,
depth,
index_in_parent,
parent_tag.map(Cow::Borrowed),
true,
);
let visit_result = {
let mut visitor = visitor_handle.lock().expect("visitor mutex poisoned");
visitor.visit_image(&node_ctx, &src, &alt, title.as_deref())
};
match visit_result {
VisitResult::Continue => render(),
VisitResult::Custom(custom) => Some(custom),
VisitResult::Skip => None,
VisitResult::Error(err) => {
if ctx.visitor_error.borrow().is_none() {
*ctx.visitor_error.borrow_mut() = Some(err);
}
None
}
VisitResult::PreserveHtml => Some(serialize_node(node_handle, parser)),
}
} else {
render()
};
#[cfg(not(feature = "visitor"))]
let image_output = render();
if !options.skip_images {
if let Some(img_text) = image_output {
output.push_str(&img_text);
}
}
#[cfg(feature = "metadata")]
if ctx.metadata_wants_images {
if let Some(ref collector) = ctx.metadata_collector {
if let Some((attributes_map, width, height)) = metadata_payload {
if !src.is_empty() {
let dimensions = match (width, height) {
(Some(w), Some(h)) => Some(crate::metadata::ImageDimensions { width: w, height: h }),
_ => None,
};
collector.borrow_mut().add_image(
src.to_string(),
if alt.is_empty() { None } else { Some(alt.to_string()) },
title.as_deref().map(std::string::ToString::to_string),
dimensions,
attributes_map,
);
}
}
}
}
if let Some(ref sc) = ctx.structure_collector {
if inline_data != InlineDataMedia::DropElement {
let src_opt = if src.is_empty() || inline_data == InlineDataMedia::AltTextOnly {
None
} else {
Some(src.as_ref())
};
let alt_opt = if alt.is_empty() { None } else { Some(alt.as_ref()) };
sc.borrow_mut().push_image(src_opt, alt_opt);
}
}
}
const LAZY_SINGLE_URL_ATTRIBUTES: [&str; 3] = ["data-src", "data-lazy-src", "data-original"];
fn resolve_effective_src<'a>(tag: &'a tl::HTMLTag<'a>, skip_inline_data: bool) -> Cow<'a, str> {
let raw_src = decoded_attribute(tag, "src").unwrap_or(Cow::Borrowed(""));
if !raw_src.trim().is_empty() && !is_inline_data(&raw_src) {
return raw_src;
}
skip_inline_data
.then(|| fallback_src(tag, true))
.flatten()
.or_else(|| fallback_src(tag, false))
.unwrap_or(raw_src)
}
fn picture_source_src(node_handle: &tl::NodeHandle, parser: &tl::Parser, dom_ctx: &DomContext) -> Option<String> {
let parent_id = dom_ctx.parent_of(node_handle.get_inner())?;
let Some(tl::Node::Tag(picture)) = dom_ctx.node_handle(parent_id)?.get(parser) else {
return None;
};
if !tag_name_eq(picture.name().as_utf8_str(), "picture") {
return None;
}
picture
.children()
.top()
.iter()
.take_while(|child| child.get_inner() != node_handle.get_inner())
.filter_map(|child| match child.get(parser) {
Some(tl::Node::Tag(source)) if tag_name_eq(source.name().as_utf8_str(), "source") => Some(source),
_ => None,
})
.find_map(|source| {
let srcset = decoded_attribute(source, "srcset")?;
pick_best_srcset_candidate(&srcset, true).map(str::to_owned)
})
}
fn fallback_src<'a>(tag: &'a tl::HTMLTag<'a>, skip_inline_data: bool) -> Option<Cow<'a, str>> {
let is_placeholder = |value: &str| value.trim().is_empty() || (skip_inline_data && is_inline_data(value));
for attr_name in LAZY_SINGLE_URL_ATTRIBUTES {
if let Some(value) = decoded_attribute(tag, attr_name) {
if !is_placeholder(&value) {
return Some(value);
}
}
}
for attr_name in ["data-srcset", "srcset"] {
if let Some(value) = decoded_attribute(tag, attr_name) {
if let Some(candidate) = pick_best_srcset_candidate(&value, skip_inline_data) {
return Some(Cow::Owned(candidate.to_string()));
}
}
}
None
}
fn pick_best_srcset_candidate(value: &str, skip_inline_data: bool) -> Option<&str> {
let mut widest: Option<(&str, f64)> = None;
let mut densest: Option<(&str, f64)> = None;
for (url, descriptor) in srcset_candidates(value) {
let (best, score) = match parse_descriptor(descriptor) {
Some(Descriptor::Width(width)) => (&mut widest, width),
Some(Descriptor::Density(density)) => (&mut densest, density),
None => continue,
};
if skip_inline_data && is_inline_data(url) {
continue;
}
if best.is_none_or(|(_, best_score)| score > best_score) {
*best = Some((url, score));
}
}
widest.or(densest).map(|(url, _)| url)
}
fn format_image_markdown(
src: &str,
alt: &str,
title: Option<&str>,
use_alt_only: bool,
link_style: crate::options::validation::LinkStyle,
url_escape_style: crate::options::validation::UrlEscapeStyle,
reference_collector: Option<&crate::converter::reference_collector::ReferenceCollectorHandle>,
) -> String {
if use_alt_only {
return alt.to_string();
}
let escaped_alt = escape_link_label(alt);
if link_style == crate::options::validation::LinkStyle::Reference {
if let Some(collector) = reference_collector {
let ref_num = collector.borrow_mut().get_or_insert(src, title);
let mut buf = String::with_capacity(escaped_alt.len() + 10);
buf.push_str("![");
buf.push_str(&escaped_alt);
buf.push_str("][");
buf.push_str(&ref_num.to_string());
buf.push(']');
return buf;
}
}
let mut buf = String::with_capacity(src.len() + escaped_alt.len() + 10);
buf.push_str(";
append_url_destination(&mut buf, src, url_escape_style, title.is_some());
if let Some(title_text) = title {
buf.push_str(" \"");
buf.push_str(&escape_markdown_title(title_text));
buf.push('"');
}
buf.push(')');
buf
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::validation::{LinkStyle, UrlEscapeStyle};
#[test]
fn a_srcset_skips_data_candidates_only_when_asked() {
let srcset = "real.png 1x, data:x 3x";
assert_eq!(pick_best_srcset_candidate(srcset, false), Some("data:x"));
assert_eq!(pick_best_srcset_candidate(srcset, true), Some("real.png"));
assert_eq!(pick_best_srcset_candidate("DATA:x 1x", true), None);
}
#[test]
fn format_image_markdown_angle_wraps_space() {
let result = format_image_markdown(
"/img (1).png",
"alt",
None,
false,
LinkStyle::Inline,
UrlEscapeStyle::Angle,
None,
);
assert_eq!(result, ".png>)");
}
#[test]
fn format_image_markdown_percent_encodes_space_and_parens() {
let result = format_image_markdown(
"/img (1).png",
"alt",
None,
false,
LinkStyle::Inline,
UrlEscapeStyle::Percent,
None,
);
assert_eq!(result, "");
}
#[test]
fn format_image_markdown_escapes_link_shaped_alt_text() {
let result = format_image_markdown(
"uri3",
"[foo](uri2)",
None,
false,
LinkStyle::Inline,
UrlEscapeStyle::Angle,
None,
);
assert_eq!(result, "](uri3)");
}
#[test]
fn format_image_markdown_percent_encodes_angle_brackets() {
let result = format_image_markdown(
"/img (1) <draft>.png",
"alt",
None,
false,
LinkStyle::Inline,
UrlEscapeStyle::Percent,
None,
);
assert_eq!(result, "");
}
#[test]
fn format_image_markdown_angle_plain_url_unchanged() {
let result = format_image_markdown(
"https://example.com/img.png",
"photo",
None,
false,
LinkStyle::Inline,
UrlEscapeStyle::Angle,
None,
);
assert_eq!(result, "");
}
#[test]
fn should_escape_alt_text_that_would_close_the_image_and_open_a_new_link() {
let result = format_image_markdown(
"x.png",
"a](https://evil.example/payload)",
None,
false,
LinkStyle::Inline,
UrlEscapeStyle::Angle,
None,
);
assert_eq!(result, "](x.png)");
}
#[test]
fn should_escape_alt_text_in_reference_style_images_too() {
let collector = crate::converter::reference_collector::ReferenceCollector::new();
let handle = std::rc::Rc::new(std::cell::RefCell::new(collector));
let result = format_image_markdown(
"x.png",
"a](https://evil.example/payload)",
None,
false,
LinkStyle::Reference,
UrlEscapeStyle::Angle,
Some(&handle),
);
assert_eq!(result, "][1]");
}
#[test]
fn should_escape_a_quote_in_the_title_that_would_open_a_real_link_after_it() {
let result = format_image_markdown(
"a.png",
"photo",
Some("x\" [click](https://evil.example)"),
false,
LinkStyle::Inline,
UrlEscapeStyle::Angle,
None,
);
assert_eq!(result, "\")");
}
#[test]
fn a_comma_inside_a_parenthesised_descriptor_does_not_start_a_candidate() {
assert_eq!(
pick_best_srcset_candidate("a.png (x, b.png 3x ), c.png 2x", false),
Some("c.png")
);
assert_eq!(
pick_best_srcset_candidate("a.png 1x (x, y.png 9x ), b.png 2x", false),
Some("b.png")
);
}
#[test]
fn a_comma_inside_a_candidate_url_stays_in_the_url() {
assert_eq!(
pick_best_srcset_candidate("a.png?x=1,2 2x, b.png 1x", false),
Some("a.png?x=1,2")
);
assert_eq!(
pick_best_srcset_candidate("data:image/gif;base64,R0lG 2x, b.png 1x", false),
Some("data:image/gif;base64,R0lG")
);
assert_eq!(pick_best_srcset_candidate("a.png,b.png 2x", false), Some("a.png,b.png"));
assert_eq!(pick_best_srcset_candidate("a.png,2x", false), Some("a.png,2x"));
}
#[test]
fn commas_around_candidates_separate_them() {
assert_eq!(
pick_best_srcset_candidate(",,, a.png 2x, b.png 1x", false),
Some("a.png")
);
assert_eq!(pick_best_srcset_candidate("a.png,, b.png 2x,,", false), Some("b.png"));
assert_eq!(pick_best_srcset_candidate("a.png, b.png", false), Some("a.png"));
assert_eq!(pick_best_srcset_candidate("", false), None);
assert_eq!(pick_best_srcset_candidate(" , ,, ", false), None);
}
#[test]
fn the_largest_descriptor_of_one_kind_wins() {
assert_eq!(pick_best_srcset_candidate("a.png", false), Some("a.png"));
assert_eq!(pick_best_srcset_candidate("a.png, b.png 2x", false), Some("b.png"));
assert_eq!(
pick_best_srcset_candidate("a.png 480w, b.png 1200w", false),
Some("b.png")
);
assert_eq!(pick_best_srcset_candidate("a.png 800w, b.png 2x", false), Some("a.png"));
}
#[test]
fn only_the_five_ascii_whitespace_characters_separate_a_descriptor() {
assert_eq!(
pick_best_srcset_candidate("a.png\t1x,\nb.png\x0C2x", false),
Some("b.png")
);
assert_eq!(
pick_best_srcset_candidate("a.png\r\n3x ,\tb.png 2x", false),
Some("a.png")
);
assert_eq!(
pick_best_srcset_candidate("a.png\u{a0}3x, b.png 2x", false),
Some("b.png")
);
assert_eq!(
pick_best_srcset_candidate("a.png \u{a0}9x, b.png 2x", false),
Some("b.png")
);
assert_eq!(
pick_best_srcset_candidate("a\u{a0}b.png 2x", false),
Some("a\u{a0}b.png")
);
}
#[test]
fn a_candidate_with_invalid_descriptors_is_never_chosen() {
assert_eq!(pick_best_srcset_candidate("a.png foo", false), None);
assert_eq!(pick_best_srcset_candidate("a.png foo, b.png", false), Some("b.png"));
assert_eq!(
pick_best_srcset_candidate("a.png 1x 2x, b.png 0.5x", false),
Some("b.png")
);
assert_eq!(
pick_best_srcset_candidate("a.png 3x 900w, b.png 1x", false),
Some("b.png")
);
assert_eq!(pick_best_srcset_candidate("a.png 0w, b.png 10w", false), Some("b.png"));
assert_eq!(pick_best_srcset_candidate("a.png 0w", false), None);
assert_eq!(
pick_best_srcset_candidate("a.png -1x, b.png 0.5x", false),
Some("b.png")
);
assert_eq!(pick_best_srcset_candidate("a.png 0x, b.png 0.5x", false), Some("b.png"));
assert_eq!(pick_best_srcset_candidate("a.png 0x", false), Some("a.png"));
}
#[test]
fn descriptor_numbers_follow_the_spec_grammar() {
assert_eq!(pick_best_srcset_candidate("a.png NaNx, b.png 2x", false), Some("b.png"));
assert_eq!(pick_best_srcset_candidate("a.png infx, b.png 2x", false), Some("b.png"));
assert_eq!(pick_best_srcset_candidate("a.png +3x, b.png 2x", false), Some("b.png"));
assert_eq!(pick_best_srcset_candidate("a.png 3.x, b.png 2x", false), Some("b.png"));
assert_eq!(
pick_best_srcset_candidate("a.png 1e400x, b.png 2x", false),
Some("b.png")
);
assert_eq!(pick_best_srcset_candidate("a.png 1.5w, b.png 1w", false), Some("b.png"));
assert_eq!(pick_best_srcset_candidate("a.png +5w, b.png 1w", false), Some("b.png"));
assert_eq!(pick_best_srcset_candidate("a.png 1e1x, b.png 2x", false), Some("a.png"));
assert_eq!(
pick_best_srcset_candidate("a.png .5x, b.png 0.25x", false),
Some("a.png")
);
assert_eq!(
pick_best_srcset_candidate("a.png 2.5E-1x, b.png 0.2x", false),
Some("a.png")
);
}
#[test]
fn widths_and_densities_are_not_compared_on_one_scale() {
assert_eq!(
pick_best_srcset_candidate("a.png 900x, b.png 800w", false),
Some("b.png")
);
assert_eq!(pick_best_srcset_candidate("a.png, b.png 10w", false), Some("b.png"));
assert_eq!(pick_best_srcset_candidate("a.png, b.png 0.5x", false), Some("a.png"));
assert_eq!(
pick_best_srcset_candidate("a.png 1x, b.png 2x, c.png 2x", false),
Some("b.png")
);
assert_eq!(
pick_best_srcset_candidate("a.png 900w, b.png 900w", false),
Some("a.png")
);
}
#[test]
fn a_height_descriptor_needs_a_width() {
assert_eq!(
pick_best_srcset_candidate("a.png 50h 100w, b.png 90w", false),
Some("a.png")
);
assert_eq!(
pick_best_srcset_candidate("a.png 100w 50h, b.png 90w", false),
Some("a.png")
);
assert_eq!(
pick_best_srcset_candidate("a.png 2x 50h, b.png 1x", false),
Some("b.png")
);
assert_eq!(
pick_best_srcset_candidate("a.png 50h, b.png 0.5x", false),
Some("b.png")
);
assert_eq!(
pick_best_srcset_candidate("a.png 100w 50h 60h, b.png 90w", false),
Some("b.png")
);
assert_eq!(
pick_best_srcset_candidate("a.png 100w 0h, b.png 90w", false),
Some("b.png")
);
}
#[test]
fn should_reject_out_of_order_parens_in_src_like_append_markdown_link_does() {
let result = format_image_markdown(
"a)(b.png",
"alt",
None,
false,
LinkStyle::Inline,
UrlEscapeStyle::Angle,
None,
);
assert_eq!(result, "\\(b.png)");
}
}