| 1 |
use std::collections::HashMap; |
| 2 |
|
| 3 |
use pulldown_cmark::{CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag, TagEnd, html}; |
| 4 |
|
| 5 |
use crate::syntax_highlight; |
| 6 |
|
| 7 |
pub fn render(raw: &str, repo_name: &str, ref_name: &str) -> String { |
| 8 |
let events: Vec<Event> = Parser::new_ext(raw, Options::all()).collect(); |
| 9 |
let events = link_headings(events); |
| 10 |
let events = highlight_code_blocks(events); |
| 11 |
let events = transform_media_and_links(events, repo_name, ref_name); |
| 12 |
|
| 13 |
let mut out = String::new(); |
| 14 |
html::push_html(&mut out, events.into_iter()); |
| 15 |
rewrite_raw_html_img_srcs(&out, repo_name, ref_name) |
| 16 |
} |
| 17 |
|
| 18 |
fn transform_media_and_links<'a>( |
| 19 |
events: Vec<Event<'a>>, |
| 20 |
repo_name: &str, |
| 21 |
ref_name: &str, |
| 22 |
) -> Vec<Event<'a>> { |
| 23 |
let mut output = Vec::with_capacity(events.len()); |
| 24 |
let mut i = 0; |
| 25 |
|
| 26 |
while i < events.len() { |
| 27 |
match &events[i] { |
| 28 |
|
| 29 |
Event::Start(Tag::Image { |
| 30 |
link_type, |
| 31 |
dest_url, |
| 32 |
title, |
| 33 |
id, |
| 34 |
}) => { |
| 35 |
let resolved_url = resolve_media_url(dest_url, repo_name, ref_name); |
| 36 |
|
| 37 |
|
| 38 |
let mut j = i + 1; |
| 39 |
let mut alt = String::new(); |
| 40 |
while j < events.len() { |
| 41 |
match &events[j] { |
| 42 |
Event::End(TagEnd::Image) => break, |
| 43 |
Event::Text(t) | Event::Code(t) => alt.push_str(t), |
| 44 |
_ => {} |
| 45 |
} |
| 46 |
j += 1; |
| 47 |
} |
| 48 |
|
| 49 |
if is_video_ext(&resolved_url) { |
| 50 |
output.push(Event::Html(CowStr::from(video_html(&resolved_url, false)))); |
| 51 |
i = (j + 1).min(events.len()); |
| 52 |
} else if is_github_asset_url(&resolved_url) { |
| 53 |
|
| 54 |
output.push(Event::Html(CowStr::from(github_asset_img_html( |
| 55 |
&resolved_url, |
| 56 |
&alt, |
| 57 |
)))); |
| 58 |
i = (j + 1).min(events.len()); |
| 59 |
} else { |
| 60 |
output.push(Event::Start(Tag::Image { |
| 61 |
link_type: *link_type, |
| 62 |
dest_url: CowStr::from(resolved_url), |
| 63 |
title: title.clone(), |
| 64 |
id: id.clone(), |
| 65 |
})); |
| 66 |
i += 1; |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
|
| 71 |
Event::Start(Tag::Link { |
| 72 |
link_type, |
| 73 |
dest_url, |
| 74 |
title, |
| 75 |
id, |
| 76 |
}) => { |
| 77 |
let url_str = dest_url.as_ref(); |
| 78 |
if is_video_ext(url_str) || is_github_asset_url(url_str) { |
| 79 |
let resolved_url = resolve_media_url(url_str, repo_name, ref_name); |
| 80 |
let mut j = i + 1; |
| 81 |
while j < events.len() && !matches!(events[j], Event::End(TagEnd::Link)) { |
| 82 |
j += 1; |
| 83 |
} |
| 84 |
output.push(Event::Html(CowStr::from(video_html( |
| 85 |
&resolved_url, |
| 86 |
is_github_asset_url(&resolved_url), |
| 87 |
)))); |
| 88 |
i = (j + 1).min(events.len()); |
| 89 |
} else { |
| 90 |
let resolved_url = resolve_link_url(url_str, repo_name, ref_name); |
| 91 |
output.push(Event::Start(Tag::Link { |
| 92 |
link_type: *link_type, |
| 93 |
dest_url: CowStr::from(resolved_url), |
| 94 |
title: title.clone(), |
| 95 |
id: id.clone(), |
| 96 |
})); |
| 97 |
i += 1; |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
|
| 102 |
Event::Text(text) => { |
| 103 |
let trimmed = text.trim(); |
| 104 |
if (trimmed.starts_with("https://") || trimmed.starts_with("http://")) |
| 105 |
&& !trimmed.contains(char::is_whitespace) |
| 106 |
&& (is_github_asset_url(trimmed) || is_video_ext(trimmed)) |
| 107 |
{ |
| 108 |
output.push(Event::Html(CowStr::from(video_html( |
| 109 |
trimmed, |
| 110 |
is_github_asset_url(trimmed), |
| 111 |
)))); |
| 112 |
} else { |
| 113 |
output.push(events[i].clone()); |
| 114 |
} |
| 115 |
i += 1; |
| 116 |
} |
| 117 |
|
| 118 |
_ => { |
| 119 |
output.push(events[i].clone()); |
| 120 |
i += 1; |
| 121 |
} |
| 122 |
} |
| 123 |
} |
| 124 |
|
| 125 |
output |
| 126 |
} |
| 127 |
|
| 128 |
fn is_relative_url(url: &str) -> bool { |
| 129 |
!url.is_empty() |
| 130 |
&& !url.starts_with("http://") |
| 131 |
&& !url.starts_with("https://") |
| 132 |
&& !url.starts_with("//") |
| 133 |
&& !url.starts_with('/') |
| 134 |
&& !url.starts_with('#') |
| 135 |
&& !url.starts_with("mailto:") |
| 136 |
&& !url.starts_with("data:") |
| 137 |
} |
| 138 |
|
| 139 |
|
| 140 |
fn resolve_media_url(url: &str, repo_name: &str, ref_name: &str) -> String { |
| 141 |
if is_relative_url(url) { |
| 142 |
let clean = url.trim_start_matches("./").trim_start_matches('/'); |
| 143 |
format!("/{repo_name}/raw/{clean}?h={ref_name}") |
| 144 |
} else { |
| 145 |
url.to_string() |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
|
| 150 |
fn resolve_link_url(url: &str, repo_name: &str, ref_name: &str) -> String { |
| 151 |
if is_relative_url(url) { |
| 152 |
let clean = url.trim_start_matches("./").trim_start_matches('/'); |
| 153 |
format!("/{repo_name}/tree/{clean}?h={ref_name}") |
| 154 |
} else { |
| 155 |
url.to_string() |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
fn is_video_ext(url: &str) -> bool { |
| 160 |
let path = url.split(['?', '#']).next().unwrap_or(url).to_lowercase(); |
| 161 |
path.ends_with(".mp4") |
| 162 |
|| path.ends_with(".webm") |
| 163 |
|| path.ends_with(".mov") |
| 164 |
|| path.ends_with(".ogv") |
| 165 |
|| path.ends_with(".m4v") |
| 166 |
} |
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
fn is_github_asset_url(url: &str) -> bool { |
| 173 |
url.starts_with("https://github.com/user-attachments/assets/") |
| 174 |
|| (url.starts_with("https://github.com/") && url.contains("/assets/")) |
| 175 |
} |
| 176 |
|
| 177 |
fn video_html(url: &str, fallback_to_img: bool) -> String { |
| 178 |
if fallback_to_img { |
| 179 |
format!( |
| 180 |
r#"<video class="readme-video" controls playsinline preload="metadata" src="{url}" onerror="const img=document.createElement('img');img.src=this.src;img.className='readme-img';this.replaceWith(img);"></video>"# |
| 181 |
) |
| 182 |
} else { |
| 183 |
format!( |
| 184 |
r#"<video class="readme-video" controls playsinline preload="metadata" src="{url}"></video>"# |
| 185 |
) |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
fn github_asset_img_html(url: &str, alt: &str) -> String { |
| 190 |
format!( |
| 191 |
r#"<img class="readme-img" src="{url}" alt="{alt}" onerror="const v=document.createElement('video');v.src=this.src;v.controls=true;v.playsInline=true;v.preload='metadata';v.className='readme-video';this.replaceWith(v);">"# |
| 192 |
) |
| 193 |
} |
| 194 |
|
| 195 |
|
| 196 |
fn rewrite_raw_html_img_srcs(html: &str, repo_name: &str, ref_name: &str) -> String { |
| 197 |
let mut result = String::with_capacity(html.len()); |
| 198 |
let mut rest = html; |
| 199 |
|
| 200 |
while let Some(idx) = rest.find("src=\"") { |
| 201 |
let (before, after_prefix) = rest.split_at(idx + 5); |
| 202 |
result.push_str(before); |
| 203 |
|
| 204 |
if let Some(end_quote) = after_prefix.find('"') { |
| 205 |
let src_val = &after_prefix[..end_quote]; |
| 206 |
let resolved = resolve_media_url(src_val, repo_name, ref_name); |
| 207 |
result.push_str(&resolved); |
| 208 |
rest = &after_prefix[end_quote..]; |
| 209 |
} else { |
| 210 |
rest = after_prefix; |
| 211 |
break; |
| 212 |
} |
| 213 |
} |
| 214 |
result.push_str(rest); |
| 215 |
result |
| 216 |
} |
| 217 |
|
| 218 |
fn highlight_code_blocks(events: Vec<Event<'_>>) -> Vec<Event<'_>> { |
| 219 |
let mut output = Vec::with_capacity(events.len()); |
| 220 |
let mut code_lang: Option<String> = None; |
| 221 |
let mut code_buf = String::new(); |
| 222 |
|
| 223 |
for event in events { |
| 224 |
match event { |
| 225 |
Event::Start(Tag::CodeBlock(kind)) => { |
| 226 |
let lang = match kind { |
| 227 |
CodeBlockKind::Fenced(lang) => { |
| 228 |
lang.split_whitespace().next().unwrap_or("").to_string() |
| 229 |
} |
| 230 |
CodeBlockKind::Indented => String::new(), |
| 231 |
}; |
| 232 |
code_lang = Some(lang); |
| 233 |
code_buf.clear(); |
| 234 |
} |
| 235 |
Event::Text(text) if code_lang.is_some() => { |
| 236 |
code_buf.push_str(&text); |
| 237 |
} |
| 238 |
Event::End(TagEnd::CodeBlock) => { |
| 239 |
if let Some(lang) = code_lang.take() { |
| 240 |
let highlighted = syntax_highlight::highlight_block(&code_buf, &lang); |
| 241 |
output.push(Event::Html(CowStr::from(highlighted))); |
| 242 |
} |
| 243 |
} |
| 244 |
other => output.push(other), |
| 245 |
} |
| 246 |
} |
| 247 |
|
| 248 |
output |
| 249 |
} |
| 250 |
|
| 251 |
fn link_headings(events: Vec<Event<'_>>) -> Vec<Event<'_>> { |
| 252 |
let mut output = Vec::with_capacity(events.len()); |
| 253 |
let mut seen: HashMap<String, usize> = HashMap::new(); |
| 254 |
let mut i = 0; |
| 255 |
|
| 256 |
while i < events.len() { |
| 257 |
if let Event::Start(Tag::Heading { |
| 258 |
level, |
| 259 |
classes, |
| 260 |
attrs, |
| 261 |
id: None, |
| 262 |
}) = &events[i] |
| 263 |
{ |
| 264 |
let level = *level; |
| 265 |
let classes = classes.clone(); |
| 266 |
let attrs = attrs.clone(); |
| 267 |
|
| 268 |
let mut j = i + 1; |
| 269 |
let mut text = String::new(); |
| 270 |
while j < events.len() { |
| 271 |
match &events[j] { |
| 272 |
Event::End(TagEnd::Heading(_)) => break, |
| 273 |
Event::Text(t) | Event::Code(t) => text.push_str(t), |
| 274 |
_ => {} |
| 275 |
} |
| 276 |
j += 1; |
| 277 |
} |
| 278 |
|
| 279 |
let mut slug = slugify(&text); |
| 280 |
if slug.is_empty() { |
| 281 |
slug = "section".to_string(); |
| 282 |
} |
| 283 |
let count = seen.entry(slug.clone()).or_insert(0); |
| 284 |
if *count > 0 { |
| 285 |
slug = format!("{slug}-{count}"); |
| 286 |
} |
| 287 |
*count += 1; |
| 288 |
|
| 289 |
output.push(Event::Start(Tag::Heading { |
| 290 |
level, |
| 291 |
id: Some(CowStr::from(slug.clone())), |
| 292 |
classes, |
| 293 |
attrs, |
| 294 |
})); |
| 295 |
output.push(Event::Start(Tag::Link { |
| 296 |
link_type: LinkType::Inline, |
| 297 |
dest_url: CowStr::from(format!("#{slug}")), |
| 298 |
title: CowStr::from(""), |
| 299 |
id: CowStr::from(""), |
| 300 |
})); |
| 301 |
|
| 302 |
output.extend_from_slice(&events[i + 1..j]); |
| 303 |
output.push(Event::End(TagEnd::Link)); |
| 304 |
output.push(events[j].clone()); |
| 305 |
i = j + 1; |
| 306 |
} else { |
| 307 |
output.push(events[i].clone()); |
| 308 |
i += 1; |
| 309 |
} |
| 310 |
} |
| 311 |
|
| 312 |
output |
| 313 |
} |
| 314 |
|
| 315 |
fn slugify(text: &str) -> String { |
| 316 |
let mut slug = String::new(); |
| 317 |
let mut last_was_dash = false; |
| 318 |
|
| 319 |
for c in text.to_lowercase().chars() { |
| 320 |
if c.is_alphanumeric() { |
| 321 |
slug.push(c); |
| 322 |
last_was_dash = false; |
| 323 |
} else if !last_was_dash { |
| 324 |
slug.push('-'); |
| 325 |
last_was_dash = true; |
| 326 |
} |
| 327 |
} |
| 328 |
|
| 329 |
slug.trim_matches('-').to_string() |
| 330 |
} |