feat: md renderer images and videos
4 files changed, 252 insertions(+), 6 deletions(-)
@@ -4,14 +4,215 @@
use crate::syntax_highlight;
pub fn render(raw: &str) -> String {
pub fn render(raw: &str, repo_name: &str, ref_name: &str) -> String {
let events: Vec<Event> = Parser::new_ext(raw, Options::all()).collect();
let events = link_headings(events);
let events = highlight_code_blocks(events);
let events = transform_media_and_links(events, repo_name, ref_name);
let mut out = String::new();
html::push_html(&mut out, events.into_iter());
out
rewrite_raw_html_img_srcs(&out, repo_name, ref_name)
}
fn transform_media_and_links<'a>(
events: Vec<Event<'a>>,
repo_name: &str,
ref_name: &str,
) -> Vec<Event<'a>> {
let mut output = Vec::with_capacity(events.len());
let mut i = 0;
while i < events.len() {
match &events[i] {
// 1. Markdown image ``
Event::Start(Tag::Image {
link_type,
dest_url,
title,
id,
}) => {
let resolved_url = resolve_media_url(dest_url, repo_name, ref_name);
// Collect alt text inside Start(Image) .. End(Image)
let mut j = i + 1;
let mut alt = String::new();
while j < events.len() {
match &events[j] {
Event::End(TagEnd::Image) => break,
Event::Text(t) | Event::Code(t) => alt.push_str(t),
_ => {}
}
j += 1;
}
if is_video_ext(&resolved_url) {
output.push(Event::Html(CowStr::from(video_html(&resolved_url, false))));
i = (j + 1).min(events.len());
} else if is_github_asset_url(&resolved_url) {
// GitHub user-attachments URLs have no file extension; render <img> that falls back to <video> if it's a video
output.push(Event::Html(CowStr::from(github_asset_img_html(
&resolved_url,
&alt,
))));
i = (j + 1).min(events.len());
} else {
output.push(Event::Start(Tag::Image {
link_type: *link_type,
dest_url: CowStr::from(resolved_url),
title: title.clone(),
id: id.clone(),
}));
i += 1;
}
}
// 2. Markdown link `[text](url)` or `<url>` pointing to a video or GitHub asset
Event::Start(Tag::Link {
link_type,
dest_url,
title,
id,
}) => {
let url_str = dest_url.as_ref();
if is_video_ext(url_str) || is_github_asset_url(url_str) {
let resolved_url = resolve_media_url(url_str, repo_name, ref_name);
let mut j = i + 1;
while j < events.len() && !matches!(events[j], Event::End(TagEnd::Link)) {
j += 1;
}
output.push(Event::Html(CowStr::from(video_html(
&resolved_url,
is_github_asset_url(&resolved_url),
))));
i = (j + 1).min(events.len());
} else {
let resolved_url = resolve_link_url(url_str, repo_name, ref_name);
output.push(Event::Start(Tag::Link {
link_type: *link_type,
dest_url: CowStr::from(resolved_url),
title: title.clone(),
id: id.clone(),
}));
i += 1;
}
}
// 3. Bare URL on its own in text (how GitHub embeds drag-and-dropped videos in READMEs)
Event::Text(text) => {
let trimmed = text.trim();
if (trimmed.starts_with("https://") || trimmed.starts_with("http://"))
&& !trimmed.contains(char::is_whitespace)
&& (is_github_asset_url(trimmed) || is_video_ext(trimmed))
{
output.push(Event::Html(CowStr::from(video_html(
trimmed,
is_github_asset_url(trimmed),
))));
} else {
output.push(events[i].clone());
}
i += 1;
}
_ => {
output.push(events[i].clone());
i += 1;
}
}
}
output
}
fn is_relative_url(url: &str) -> bool {
!url.is_empty()
&& !url.starts_with("http://")
&& !url.starts_with("https://")
&& !url.starts_with("//")
&& !url.starts_with('/')
&& !url.starts_with('#')
&& !url.starts_with("mailto:")
&& !url.starts_with("data:")
}
/// Resolves relative image/video paths (e.g. `docs/screenshots/tree.png`) to `/<repo>/raw/<path>?h=<ref>`.
fn resolve_media_url(url: &str, repo_name: &str, ref_name: &str) -> String {
if is_relative_url(url) {
let clean = url.trim_start_matches("./").trim_start_matches('/');
format!("/{repo_name}/raw/{clean}?h={ref_name}")
} else {
url.to_string()
}
}
/// Resolves relative repository links (e.g. `docs/screenshots/` or `LICENSE`) to `/<repo>/tree/<path>?h=<ref>`.
fn resolve_link_url(url: &str, repo_name: &str, ref_name: &str) -> String {
if is_relative_url(url) {
let clean = url.trim_start_matches("./").trim_start_matches('/');
format!("/{repo_name}/tree/{clean}?h={ref_name}")
} else {
url.to_string()
}
}
fn is_video_ext(url: &str) -> bool {
let path = url.split(['?', '#']).next().unwrap_or(url).to_lowercase();
path.ends_with(".mp4")
|| path.ends_with(".webm")
|| path.ends_with(".mov")
|| path.ends_with(".ogv")
|| path.ends_with(".m4v")
}
/// Matches GitHub uploaded asset URLs:
/// - `https://github.com/user-attachments/assets/<uuid>`
/// - `https://github.com/<owner>/<repo>/assets/<user_id>/<uuid>`
/// - `https://private-user-images.githubusercontent.com/...`
fn is_github_asset_url(url: &str) -> bool {
url.starts_with("https://github.com/user-attachments/assets/")
|| (url.starts_with("https://github.com/") && url.contains("/assets/"))
}
fn video_html(url: &str, fallback_to_img: bool) -> String {
if fallback_to_img {
format!(
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>"#
)
} else {
format!(
r#"<video class="readme-video" controls playsinline preload="metadata" src="{url}"></video>"#
)
}
}
fn github_asset_img_html(url: &str, alt: &str) -> String {
format!(
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);">"#
)
}
/// Also rewrites relative `<img src="...">` and `<video src="...">` inside raw HTML blocks in Markdown.
fn rewrite_raw_html_img_srcs(html: &str, repo_name: &str, ref_name: &str) -> String {
let mut result = String::with_capacity(html.len());
let mut rest = html;
while let Some(idx) = rest.find("src=\"") {
let (before, after_prefix) = rest.split_at(idx + 5);
result.push_str(before);
if let Some(end_quote) = after_prefix.find('"') {
let src_val = &after_prefix[..end_quote];
let resolved = resolve_media_url(src_val, repo_name, ref_name);
result.push_str(&resolved);
rest = &after_prefix[end_quote..];
} else {
rest = after_prefix;
break;
}
}
result.push_str(rest);
result
}
fn highlight_code_blocks(events: Vec<Event<'_>>) -> Vec<Event<'_>> {
@@ -741,6 +741,48 @@
.readme p {
font-size: 0.92rem;
color: var(--subtext1);
line-height: 1.6;
}
.readme ul,
.readme ol {
color: var(--subtext1);
padding-left: 1.5rem;
line-height: 1.6;
}
.readme blockquote {
margin: 0.75rem 0;
padding: 0.25rem 1rem;
border-left: 3px solid var(--peach);
background: var(--mantle);
color: var(--subtext0);
}
.readme img,
.readme video {
max-width: 100%;
height: auto;
border: 1px solid var(--surface0);
margin: 0.5rem 0;
}
.readme video {
display: block;
background: var(--crust);
}
.readme table {
width: auto;
border: 1px solid var(--surface1);
margin: 1rem 0;
}
.readme th,
.readme td {
border: 1px solid var(--surface1);
padding: 0.45rem 0.85rem;
white-space: normal;
}
.readme hr {
@@ -19,7 +19,9 @@
let repo = data.get_repo(&path)?;
let current_ref = Ref::resolve(&repo, &query)?;
let branch_names = repo.branch_names()?;
let readme_html = repo.readme().map(|raw| markdown::render(&raw));
let readme_html = repo
.readme()
.map(|raw| markdown::render(&raw, &repo.name, ¤t_ref.name));
render_html(&AboutPage {
repo,
@@ -55,9 +55,10 @@
let current_ref = Ref::resolve(&repo, &query)?;
match repo.read_raw_blob(¤t_ref, &path)? {
Some(bytes) => Ok(HttpResponse::Ok()
.content_type("text/plain; charset=utf-8")
.body(bytes)),
Some(bytes) => {
let mime = mime_guess::from_path(&path).first_or_text_plain();
Ok(HttpResponse::Ok().content_type(mime.as_ref()).body(bytes))
}
None => Ok(HttpResponse::BadRequest().body("path is a directory")),
}
}