index : gitrs
A lightweight web interface for browsing Git repositories, implemented in Rust
about summary refs log tree commit diff
gitrs / src / markdown.rs
-rw-r--r-- blob ed0c6ce524efc795e59baaf9b7a9c4d2fd918be7 12219 bytes (plain)
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
            // 1. Markdown image `![alt](url)`
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
                // Collect alt text inside Start(Image) .. End(Image)
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
                    // GitHub user-attachments URLs have no file extension; render <img> that falls back to <video> if it's a video
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
            // 2. Markdown link `[text](url)` or `<url>` pointing to a video or GitHub asset
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
            // 3. Bare URL on its own in text (how GitHub embeds drag-and-dropped videos in READMEs)
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
/// Resolves relative image/video paths (e.g. `docs/screenshots/tree.png`) to `/<repo>/raw/<path>?h=<ref>`.
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
/// Resolves relative repository links (e.g. `docs/screenshots/` or `LICENSE`) to `/<repo>/tree/<path>?h=<ref>`.
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
/// Matches GitHub uploaded asset URLs:
169
/// - `https://github.com/user-attachments/assets/<uuid>`
170
/// - `https://github.com/<owner>/<repo>/assets/<user_id>/<uuid>`
171
/// - `https://private-user-images.githubusercontent.com/...`
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 escape_attr(s: &str) -> String {
178
    let mut out = String::with_capacity(s.len());
179
    for c in s.chars() {
180
        match c {
181
            '&' => out.push_str("&amp;"),
182
            '"' => out.push_str("&quot;"),
183
            '\'' => out.push_str("&#39;"),
184
            '<' => out.push_str("&lt;"),
185
            '>' => out.push_str("&gt;"),
186
            _ => out.push(c),
187
        }
188
    }
189
    out
190
}
191
192
fn video_html(url: &str, fallback_to_img: bool) -> String {
193
    let url = escape_attr(url);
194
    if fallback_to_img {
195
        format!(
196
            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>"#
197
        )
198
    } else {
199
        format!(
200
            r#"<video class="readme-video" controls playsinline preload="metadata" src="{url}"></video>"#
201
        )
202
    }
203
}
204
205
fn github_asset_img_html(url: &str, alt: &str) -> String {
206
    let url = escape_attr(url);
207
    let alt = escape_attr(alt);
208
    format!(
209
        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);">"#
210
    )
211
}
212
213
/// Also rewrites relative `<img src="...">` and `<video src="...">` inside raw HTML blocks in Markdown.
214
fn rewrite_raw_html_img_srcs(html: &str, repo_name: &str, ref_name: &str) -> String {
215
    let mut result = String::with_capacity(html.len());
216
    let mut rest = html;
217
218
    while let Some(idx) = rest.find("src=\"") {
219
        let (before, after_prefix) = rest.split_at(idx + 5);
220
        result.push_str(before);
221
222
        if let Some(end_quote) = after_prefix.find('"') {
223
            let src_val = &after_prefix[..end_quote];
224
            let resolved = resolve_media_url(src_val, repo_name, ref_name);
225
            result.push_str(&resolved);
226
            rest = &after_prefix[end_quote..];
227
        } else {
228
            rest = after_prefix;
229
            break;
230
        }
231
    }
232
    result.push_str(rest);
233
    result
234
}
235
236
fn highlight_code_blocks(events: Vec<Event<'_>>) -> Vec<Event<'_>> {
237
    let mut output = Vec::with_capacity(events.len());
238
    let mut code_lang: Option<String> = None;
239
    let mut code_buf = String::new();
240
241
    for event in events {
242
        match event {
243
            Event::Start(Tag::CodeBlock(kind)) => {
244
                let lang = match kind {
245
                    CodeBlockKind::Fenced(lang) => {
246
                        lang.split_whitespace().next().unwrap_or("").to_string()
247
                    }
248
                    CodeBlockKind::Indented => String::new(),
249
                };
250
                code_lang = Some(lang);
251
                code_buf.clear();
252
            }
253
            Event::Text(text) if code_lang.is_some() => {
254
                code_buf.push_str(&text);
255
            }
256
            Event::End(TagEnd::CodeBlock) => {
257
                if let Some(lang) = code_lang.take() {
258
                    let highlighted = syntax_highlight::highlight_block(&code_buf, &lang);
259
                    output.push(Event::Html(CowStr::from(highlighted)));
260
                }
261
            }
262
            other => output.push(other),
263
        }
264
    }
265
266
    output
267
}
268
269
fn link_headings(events: Vec<Event<'_>>) -> Vec<Event<'_>> {
270
    let mut output = Vec::with_capacity(events.len());
271
    let mut seen: HashMap<String, usize> = HashMap::new();
272
    let mut i = 0;
273
274
    while i < events.len() {
275
        if let Event::Start(Tag::Heading {
276
            level,
277
            classes,
278
            attrs,
279
            id: None,
280
        }) = &events[i]
281
        {
282
            let level = *level;
283
            let classes = classes.clone();
284
            let attrs = attrs.clone();
285
286
            let mut j = i + 1;
287
            let mut text = String::new();
288
            while j < events.len() {
289
                match &events[j] {
290
                    Event::End(TagEnd::Heading(_)) => break,
291
                    Event::Text(t) | Event::Code(t) => text.push_str(t),
292
                    _ => {}
293
                }
294
                j += 1;
295
            }
296
297
            let mut slug = slugify(&text);
298
            if slug.is_empty() {
299
                slug = "section".to_string();
300
            }
301
            let count = seen.entry(slug.clone()).or_insert(0);
302
            if *count > 0 {
303
                slug = format!("{slug}-{count}");
304
            }
305
            *count += 1;
306
307
            output.push(Event::Start(Tag::Heading {
308
                level,
309
                id: Some(CowStr::from(slug.clone())),
310
                classes,
311
                attrs,
312
            }));
313
            output.push(Event::Start(Tag::Link {
314
                link_type: LinkType::Inline,
315
                dest_url: CowStr::from(format!("#{slug}")),
316
                title: CowStr::from(""),
317
                id: CowStr::from(""),
318
            }));
319
320
            output.extend_from_slice(&events[i + 1..j]);
321
            output.push(Event::End(TagEnd::Link));
322
            output.push(events[j].clone()); // End(Heading)
323
            i = j + 1;
324
        } else {
325
            output.push(events[i].clone());
326
            i += 1;
327
        }
328
    }
329
330
    output
331
}
332
333
fn slugify(text: &str) -> String {
334
    let mut slug = String::new();
335
    let mut last_was_dash = false;
336
337
    for c in text.to_lowercase().chars() {
338
        if c.is_alphanumeric() {
339
            slug.push(c);
340
            last_was_dash = false;
341
        } else if !last_was_dash {
342
            slug.push('-');
343
            last_was_dash = true;
344
        }
345
    }
346
347
    slug.trim_matches('-').to_string()
348
}