​wit /
src / html.rs
206 commits
23-11-2026
1797 lines 57 kB
   1use crate::markdown::{is_markdown, write_markdown};
   2use crate::repo_info::{
   3    CommitDiff, CommitInfo, Dir, FileChange, Line, RefInfo, RepoInfo, TreeEntry, archive_name,
   4    join_path,
   5};
   6
   7use chrono::{DateTime, FixedOffset};
   8use std::{
   9    cmp::Reverse,
  10    collections::{HashMap, HashSet},
  11    fmt::Write,
  12};
  13
  14const BRAND: &str = "wit";
  15
  16const CLONE_URL_BASE: &str = "https://git.paramogi.world/";
  17
  18const NO_DESCRIPTION: &str = "[no description]";
  19
  20const BRIEF_COUNT: usize = 5;
  21
  22const DATE: &str = "%d-%m-%Y";
  23
  24pub const COMMITS_PER_PAGE: usize = 200;
  25
  26const SUMMARY_REF_COUNT: usize = 3;
  27
  28const BYTE_UNITS: [&str; 5] = ["B", "kB", "MB", "GB", "TB"];
  29
  30const README_NAMES: [&str; 2] = ["README.md", "README"];
  31
  32const MARKDOWN_BOX: &str = "box markdown-body";
  33
  34pub const ARCHIVE_FORMATS: [&str; 2] = ["zip", "tar.gz"];
  35
  36const REPO_FILES: [(&str, &str, [&str; 2]); 2] = [
  37    ("README", "book", README_NAMES),
  38    ("LICENSE", "law", ["LICENSE", "COPYING"]),
  39];
  40
  41const IMAGE_TYPES: [(&str, &str); 6] = [
  42    ("png", "image/png"),
  43    ("jpg", "image/jpeg"),
  44    ("jpeg", "image/jpeg"),
  45    ("gif", "image/gif"),
  46    ("webp", "image/webp"),
  47    ("svg", "image/svg+xml"),
  48];
  49
  50const REF_MENU_ROWS: usize = 8;
  51
  52const REF_CHIPS: usize = 2;
  53
  54const MAX_LINKS: usize = 40;
  55
  56const BASE64_CHARS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  57
  58const ICONS: [(&str, &str); 25] = [
  59    ("book", include_str!("icons/book.svg")),
  60    ("law", include_str!("icons/law.svg")),
  61    ("file-directory", include_str!("icons/file-directory.svg")),
  62    ("file", include_str!("icons/file.svg")),
  63    ("file-archive", include_str!("icons/file-archive.svg")),
  64    (
  65        "file-symlink-file",
  66        include_str!("icons/file-symlink-file.svg"),
  67    ),
  68    ("file-submodule", include_str!("icons/file-submodule.svg")),
  69    ("git-branch", include_str!("icons/git-branch.svg")),
  70    ("git-commit", include_str!("icons/git-commit.svg")),
  71    ("tag", include_str!("icons/tag.svg")),
  72    ("release", include_str!("icons/release.svg")),
  73    ("chevron-down", include_str!("icons/chevron-down.svg")),
  74    ("chevron-right", include_str!("icons/chevron-right.svg")),
  75    ("chevron-up", include_str!("icons/chevron-up.svg")),
  76    ("chevron-left", include_str!("icons/chevron-left.svg")),
  77    ("diff-added", include_str!("icons/diff-added.svg")),
  78    ("diff-removed", include_str!("icons/diff-removed.svg")),
  79    ("diff-modified", include_str!("icons/diff-modified.svg")),
  80    ("diff-renamed", include_str!("icons/diff-renamed.svg")),
  81    ("link", include_str!("icons/link.svg")),
  82    ("info", include_str!("icons/info.svg")),
  83    ("light-bulb", include_str!("icons/light-bulb.svg")),
  84    ("report", include_str!("icons/report.svg")),
  85    ("alert", include_str!("icons/alert.svg")),
  86    ("stop", include_str!("icons/stop.svg")),
  87];
  88
  89#[derive(Clone, Copy, PartialEq)]
  90enum Tab {
  91    Summary,
  92    Tree,
  93    Commits,
  94    Branches,
  95    Tags,
  96    Releases,
  97}
  98
  99const TABS: [Tab; 6] = [
 100    Tab::Summary,
 101    Tab::Tree,
 102    Tab::Commits,
 103    Tab::Branches,
 104    Tab::Tags,
 105    Tab::Releases,
 106];
 107
 108impl Tab {
 109    fn label(self) -> &'static str {
 110        match self {
 111            Tab::Summary => "summary",
 112            Tab::Tree => "tree",
 113            Tab::Commits => "commits",
 114            Tab::Branches => "branches",
 115            Tab::Tags => "tags",
 116            Tab::Releases => "releases",
 117        }
 118    }
 119
 120    fn main_class(self) -> &'static str {
 121        match self {
 122            Tab::Summary => "",
 123            Tab::Tree => "action-code",
 124            Tab::Commits => "action-commits",
 125            Tab::Branches => "action-branches",
 126            Tab::Tags => "",
 127            Tab::Releases => "action-releases",
 128        }
 129    }
 130
 131    fn href(self, git_ref: &str) -> String {
 132        match self {
 133            Tab::Summary => String::new(),
 134            Tab::Tree => format!("tree/{}/", percent_encode(git_ref)),
 135            Tab::Commits => format!("commits/{}/", percent_encode(git_ref)),
 136            Tab::Branches => "branches".to_string(),
 137            Tab::Tags => "tags".to_string(),
 138            Tab::Releases => "releases".to_string(),
 139        }
 140    }
 141}
 142
 143fn repo_tabs(repo: &RepoInfo) -> impl Iterator<Item = Tab> {
 144    TABS.into_iter().filter(move |&tab| match tab {
 145        Tab::Tags => !repo.tags.is_empty(),
 146        Tab::Releases => !repo.releases.is_empty(),
 147        _ => true,
 148    })
 149}
 150
 151struct RepoNav<'a> {
 152    repo: &'a RepoInfo,
 153    git_ref: &'a str,
 154    tab: Tab,
 155    depth: usize,
 156    path: &'a str,
 157    commits: usize,
 158}
 159
 160pub fn icon(name: &str) -> String {
 161    format!(
 162        "<svg width=\"16\" height=\"16\" aria-hidden=\"true\"><use href=\"#icon.{name}\"/></svg>"
 163    )
 164}
 165
 166fn ref_icon(git_ref: &RefInfo) -> String {
 167    if git_ref.is_tag() {
 168        icon("tag")
 169    } else {
 170        icon("git-branch")
 171    }
 172}
 173
 174pub fn escape_str(s: &str) -> String {
 175    let mut escaped_str = String::with_capacity(s.len());
 176    for c in s.chars() {
 177        match c {
 178            '&' => escaped_str.push_str("&amp;"),
 179            '<' => escaped_str.push_str("&lt;"),
 180            '>' => escaped_str.push_str("&gt;"),
 181            '"' => escaped_str.push_str("&quot;"),
 182            '\'' => escaped_str.push_str("&#39;"),
 183            _ => escaped_str.push(c),
 184        }
 185    }
 186    escaped_str
 187}
 188
 189fn format_bytes(bytes: usize) -> String {
 190    if bytes < 1000 {
 191        return format!("{bytes} B");
 192    }
 193    let round = |value: f64| (value * 10.0 + 0.5).floor() / 10.0;
 194    let mut value = bytes as f64;
 195    let mut unit = 0;
 196    while round(value) >= 999.5 && unit + 1 < BYTE_UNITS.len() {
 197        value /= 1000.0;
 198        unit += 1;
 199    }
 200    let value = round(value);
 201    if value < 10.0 {
 202        format!("{value:.1} {}", BYTE_UNITS[unit])
 203    } else {
 204        format!("{value:.0} {}", BYTE_UNITS[unit])
 205    }
 206}
 207
 208pub fn percent_encode(s: &str) -> String {
 209    let mut encoded = String::with_capacity(s.len());
 210    for b in s.bytes() {
 211        if b.is_ascii_alphanumeric() || b"-._~/".contains(&b) {
 212            encoded.push(b as char);
 213        } else {
 214            encoded.push_str(&format!("%{b:02X}"));
 215        }
 216    }
 217    encoded
 218}
 219
 220fn find_ref<'a>(repo: &'a RepoInfo, dir: &str) -> Option<&'a RefInfo> {
 221    repo.branches
 222        .iter()
 223        .chain(&repo.tags)
 224        .find(|git_ref| git_ref.dir == dir)
 225}
 226
 227fn root_dir(git_ref: &RefInfo) -> Option<&Dir> {
 228    git_ref.dirs.get("")
 229}
 230
 231fn repo_file<'a>(dir: &'a Dir, names: &[&str]) -> Option<&'a TreeEntry> {
 232    names
 233        .iter()
 234        .find_map(|name| dir.entry(name).filter(|e| !e.is_dir))
 235}
 236
 237fn file_links(nav: &RepoNav, repo_root: &str) -> Vec<(bool, String)> {
 238    let Some(git_ref) = find_ref(nav.repo, nav.git_ref) else {
 239        return Vec::new();
 240    };
 241    let Some(root) = root_dir(git_ref) else {
 242        return Vec::new();
 243    };
 244    REPO_FILES
 245        .iter()
 246        .filter_map(|(label, icon_name, names)| {
 247            let path = follow_links(git_ref, &repo_file(root, names)?.name)?;
 248            let href = path_href(git_ref, repo_root, &path)?;
 249            let current = path == nav.path;
 250            Some((
 251                current,
 252                format!(
 253                    "<a class=\"doc-link\"{} href=\"{}\">{}{label}</a>",
 254                    if current {
 255                        " aria-current=\"page\""
 256                    } else {
 257                        ""
 258                    },
 259                    escape_str(&href),
 260                    icon(icon_name)
 261                ),
 262            ))
 263        })
 264        .collect()
 265}
 266
 267fn write_readme(body: &mut String, repo: &RepoInfo, git_ref: &RefInfo, dir: &Dir, repo_root: &str) {
 268    let Some(path) = repo_file(dir, &README_NAMES)
 269        .and_then(|entry| follow_links(git_ref, &join_path(&dir.path, &entry.name)))
 270    else {
 271        return;
 272    };
 273    let Some(entry) = find_file(git_ref, &path) else {
 274        return;
 275    };
 276    let Some(blob) = entry
 277        .blob
 278        .filter(|_| entry.lines.is_some())
 279        .and_then(|id| repo.git.find_blob(id).ok())
 280    else {
 281        return;
 282    };
 283    body.push_str(
 284        "\
 285<div class=\"summary-readme\">\n\
 286<header class=\"subtitle\">\n\
 287<h2>readme</h2>\n\
 288</header>\n\
 289",
 290    );
 291    let content = blob.content();
 292    let markdown = is_markdown(&entry.name);
 293    write_file_head(body, entry, content, markdown);
 294    if markdown {
 295        let base = path.rsplit_once('/').map_or("", |(parent, _)| parent);
 296        write_markdown(body, MARKDOWN_BOX, repo, git_ref, base, repo_root, content);
 297        write_code(body, content);
 298    } else {
 299        body.push_str(&format!(
 300            "<pre class=\"white-space-bs\">{}</pre>\n",
 301            escape_str(&String::from_utf8_lossy(content))
 302        ));
 303    }
 304    body.push_str("</div>\n");
 305}
 306
 307fn icon_symbols(parts: &[&str]) -> String {
 308    let used: HashSet<&str> = parts
 309        .iter()
 310        .flat_map(|part| {
 311            part.match_indices("href=\"#icon.")
 312                .filter_map(|(at, found)| part[at + found.len()..].split('"').next())
 313        })
 314        .collect();
 315    let symbols: String = ICONS
 316        .iter()
 317        .filter(|(id, _)| used.contains(id))
 318        .map(|(id, svg)| {
 319            let view_box = svg
 320                .split("viewBox=\"")
 321                .nth(1)
 322                .and_then(|s| s.split('"').next());
 323            let start = svg.find('>').map_or(0, |i| i + 1);
 324            let end = svg.rfind("</svg>").unwrap_or(svg.len());
 325            format!(
 326                "<symbol id=\"icon.{id}\" viewBox=\"{}\">{}</symbol>",
 327                view_box.unwrap_or_default(),
 328                &svg[start..end]
 329            )
 330        })
 331        .collect();
 332    if symbols.is_empty() {
 333        String::new()
 334    } else {
 335        format!("<svg style=\"display: none\" aria-hidden=\"true\">{symbols}</svg>\n")
 336    }
 337}
 338
 339fn wrap_page(title: &str, nav: Option<&RepoNav>, body: &str) -> String {
 340    let (root, title) = match nav {
 341        Some(nav) => (
 342            "../".repeat(nav.depth + 1),
 343            format!("{} - {title}", nav.tab.label()),
 344        ),
 345        None => (String::new(), title.to_string()),
 346    };
 347    let mut header = String::from("<header class=\"topbar\">\n<div id=\"header\">\n");
 348    let (main_class, footer) = match nav {
 349        Some(nav) => {
 350            let repo_root = "../".repeat(nav.depth);
 351            let name = escape_str(&nav.repo.name);
 352            header.push_str(&format!(
 353                "\
 354<a class=\"brand\" href=\"{root}\">{BRAND}</a>\n\
 355<h1 id=\"site_path\"><a class=\"truncate\" href=\"{}\" title=\"{name}\">{name}</a></h1>\n\
 356</div>\n\
 357<nav class=\"repo-tabs\" aria-label=\"repository\">\n\
 358",
 359                here(repo_root.clone())
 360            ));
 361            let files = file_links(nav, &repo_root);
 362            let on_file = files.iter().any(|(current, _)| *current);
 363            for tab in repo_tabs(nav.repo) {
 364                let current = match (tab == nav.tab, on_file) {
 365                    (false, _) => "",
 366                    (true, false) => " aria-current=\"page\"",
 367                    (true, true) => " aria-current=\"true\"",
 368                };
 369                let count = match tab {
 370                    Tab::Commits => Some(nav.commits),
 371                    Tab::Branches => Some(nav.repo.branches.len()),
 372                    Tab::Tags => Some(nav.repo.tags.len()),
 373                    Tab::Releases => Some(nav.repo.releases.len()),
 374                    _ => None,
 375                };
 376                let label = tab.label();
 377                header.push_str(&format!(
 378                    "<a class=\"tab\"{current} href=\"{}\"><span class=\"tab-label\" data-label=\"{label}\">{label}</span>",
 379                    here(format!("{repo_root}{}", tab.href(nav.git_ref)))
 380                ));
 381                if let Some(count) = count {
 382                    header.push_str(&format!(
 383                        "<span class=\"tab-count\"><span class=\"vh\">, </span>{count}</span>"
 384                    ));
 385                }
 386                header.push_str("</a>\n");
 387            }
 388            header.push_str("</nav>\n");
 389            if !files.is_empty() {
 390                header.push_str("<nav class=\"repo-docs\" aria-label=\"documents\">\n");
 391                for (_, link) in &files {
 392                    header.push_str(link);
 393                    header.push('\n');
 394                }
 395                header.push_str("</nav>\n");
 396            }
 397            (
 398                nav.tab.main_class(),
 399                "<footer class=\"site-footer\">powered by <a href=\"#\">wit</a></footer>\n",
 400            )
 401        }
 402        None => {
 403            header.push_str(&format!(
 404                "<a class=\"brand\" aria-current=\"page\" href=\"./\">{BRAND}</a>\n</div>\n"
 405            ));
 406            ("action-index", "")
 407        }
 408    };
 409    header.push_str("</header>\n");
 410    let main = if main_class.is_empty() {
 411        "<main>".to_string()
 412    } else {
 413        format!("<main class=\"{main_class}\">")
 414    };
 415    let icons = icon_symbols(&[&header, body]);
 416    format!(
 417        "\
 418<!DOCTYPE html>\n\
 419<html lang=\"en\">\n\
 420<head>\n\
 421<meta charset=\"utf-8\">\n\
 422<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
 423<title>{}</title>\n\
 424<link rel=\"stylesheet\" href=\"{root}style.css\">\n\
 425<link rel=\"icon\" href=\"{root}favicon.ico\">\n\
 426</head>\n\
 427<body>\n\
 428{icons}\
 429{header}\
 430{main}\n\
 431{body}\
 432</main>\n\
 433{footer}\
 434</body>\n\
 435</html>\n\
 436",
 437        escape_str(&title)
 438    )
 439}
 440
 441fn description(repo: &RepoInfo) -> (&'static str, String) {
 442    if repo.description.is_empty() {
 443        (" empty", NO_DESCRIPTION.to_string())
 444    } else {
 445        ("", escape_str(&repo.description))
 446    }
 447}
 448
 449pub fn gen_index(repos: &[RepoInfo]) -> String {
 450    let mut sorted: Vec<&RepoInfo> = repos.iter().collect();
 451    sorted.sort_by_key(|repo| Reverse(repo.commit_list[0].committer_date));
 452
 453    let mut body = String::from("<h1 class=\"vh\">repositories</h1>\n<ul class=\"repo-list\">\n");
 454    for repo in sorted {
 455        let name = escape_str(&repo.name);
 456        let dir = percent_encode(&repo.name);
 457        let links: String = repo_tabs(repo)
 458            .map(|tab| {
 459                format!(
 460                    "<a href=\"{dir}/{}\">{}</a>",
 461                    tab.href(&repo.head_dir),
 462                    tab.label()
 463                )
 464            })
 465            .collect();
 466        let (empty, description) = description(repo);
 467        body.push_str(&format!(
 468            "\
 469<li class=\"repo-row\">\n\
 470<h2 class=\"flex repo-name\"><a class=\"truncate row-link\" href=\"{dir}/\">{name}</a></h2>\n\
 471<p class=\"repo-date\"><span class=\"repo-date-label\">last commit </span>{}</p>\n\
 472<p class=\"repo-desc{empty}\">{description}</p>\n\
 473<div class=\"repo-links\">{links}</div>\n\
 474</li>\n\
 475",
 476            repo.commit_list[0].committer_date.format(DATE),
 477        ));
 478    }
 479    body.push_str("</ul>\n");
 480
 481    wrap_page("repositories", None, &body)
 482}
 483
 484pub fn gen_summary(repo: &RepoInfo, last: &HashMap<String, &CommitInfo>) -> String {
 485    let nav = RepoNav {
 486        repo,
 487        git_ref: &repo.head_dir,
 488        tab: Tab::Summary,
 489        depth: 0,
 490        path: "",
 491        commits: repo.commit_list.len(),
 492    };
 493    let mut body = String::from("<div class=\"summary-layout\">\n<div class=\"summary-main\">\n");
 494    let head = find_ref(repo, &repo.head_dir);
 495    if let Some(head) = head
 496        && let Some(root) = root_dir(head)
 497    {
 498        body.push_str("<div class=\"summary-tree\">\n");
 499        body.push_str(&ref_bar(repo, head, "", "", repo.commit_list.len(), "true"));
 500        let tree_dir = format!("tree/{}/", repo.head_dir);
 501        write_listing(&mut body, head, root, "", &tree_dir, last);
 502        body.push_str("</div>\n");
 503        write_readme(&mut body, repo, head, root, "");
 504    }
 505    body.push_str("</div>\n<aside class=\"summary-side\">\n");
 506
 507    let meta_row = |key: &str, class: &str, val: &str| {
 508        let key = if key.is_empty() {
 509            String::new()
 510        } else {
 511            format!("<span class=\"summary-meta-key\">{key}</span>\n")
 512        };
 513        format!(
 514            "<div class=\"summary-meta-row border-b\">\n{key}<span class=\"summary-meta-val{class}\">{val}</span>\n</div>\n"
 515        )
 516    };
 517    let dot = "&nbsp;&centerdot;&nbsp;";
 518    let newest = &repo.commit_list[0];
 519    let (empty, description) = description(repo);
 520    body.push_str("<div class=\"box summary-meta-box\">\n");
 521    body.push_str(&meta_row("", empty, &description));
 522    if !repo.owner.is_empty() {
 523        body.push_str(&meta_row("owner", " truncate", &escape_str(&repo.owner)));
 524    }
 525    let last_commit = format!(
 526        "{}{dot}{}",
 527        short_id("", &newest.id),
 528        newest.committer_date.format(DATE)
 529    );
 530    body.push_str(&meta_row("last commit", "", &last_commit));
 531    if let Some(release) = repo.releases.first() {
 532        let link = format!(
 533            "<a href=\"{}\" class=\"release-id\">{}<span class=\"truncate\">{}</span></a>{dot}{}",
 534            Tab::Releases.href(""),
 535            icon("release"),
 536            escape_str(&release.tag),
 537            release.date.format(DATE)
 538        );
 539        body.push_str(&meta_row("latest release", "", &link));
 540    }
 541    let clone_url = format!("{CLONE_URL_BASE}{}.git", repo.name);
 542    body.push_str(&meta_row("clone url", "", &escape_str(&clone_url)));
 543    body.push_str("</div>\n");
 544
 545    write_briefs(&mut body, repo);
 546    if repo.branches.len() > 1 {
 547        let rows: String = repo
 548            .branches
 549            .iter()
 550            .take(SUMMARY_REF_COUNT)
 551            .map(|r| side_row(&ref_icon(r), &Tab::Tree.href(&r.dir), &r.name, &r.date))
 552            .collect();
 553        write_side_list(&mut body, Tab::Branches, &rows);
 554    }
 555    if !repo.tags.is_empty() {
 556        let rows: String = repo
 557            .tags
 558            .iter()
 559            .take(SUMMARY_REF_COUNT)
 560            .map(|r| side_row(&ref_icon(r), &Tab::Tree.href(&r.dir), &r.name, &r.date))
 561            .collect();
 562        write_side_list(&mut body, Tab::Tags, &rows);
 563    }
 564    if !repo.releases.is_empty() {
 565        let rows: String = repo
 566            .releases
 567            .iter()
 568            .take(SUMMARY_REF_COUNT)
 569            .enumerate()
 570            .map(|(n, release)| {
 571                let href = format!("{}#release-{}", Tab::Releases.href(""), n + 1);
 572                side_row(&icon("release"), &href, &release.tag, &release.date)
 573            })
 574            .collect();
 575        write_side_list(&mut body, Tab::Releases, &rows);
 576    }
 577    body.push_str("</aside>\n</div>\n");
 578
 579    wrap_page(&repo.name, Some(&nav), &body)
 580}
 581
 582fn side_row(icon: &str, href: &str, name: &str, date: &DateTime<FixedOffset>) -> String {
 583    format!(
 584        "\
 585<section class=\"flex items-center gap-2 px row tree-row border-b\">\n\
 586<div class=\"branch-name flex-1 flex items-center gap\">{icon}<a class=\"truncate row-link\" href=\"{href}\">{}</a></div>\n\
 587{}\
 588</section>\n\
 589",
 590        escape_str(name),
 591        date_cell(date)
 592    )
 593}
 594
 595fn write_side_list(body: &mut String, tab: Tab, rows: &str) {
 596    let label = tab.label();
 597    body.push_str(&format!(
 598        "\
 599<div>\n\
 600<header class=\"subtitle\">\n\
 601<h2>{label}</h2>\n\
 602</header>\n\
 603<div class=\"box p-0 side-list\">\n\
 604{rows}\
 605<div class=\"row side-all px\">\n\
 606<a class=\"row-link\" href=\"{}\">all {label}</a>\n\
 607</div>\n\
 608</div>\n\
 609</div>\n\
 610",
 611        tab.href("")
 612    ));
 613}
 614
 615pub fn gen_branches(repo: &RepoInfo, counts: &HashMap<String, usize>) -> String {
 616    let (head, others): (Vec<&RefInfo>, Vec<&RefInfo>) = repo
 617        .branches
 618        .iter()
 619        .partition(|git_ref| git_ref.dir == repo.head_dir);
 620    let mut body = String::new();
 621    write_refs(&mut body, "default branch", &head, counts);
 622    if !others.is_empty() {
 623        let heading = format!(
 624            "other branches <span class=\"count\">{}</span>",
 625            others.len()
 626        );
 627        write_refs(&mut body, &heading, &others, counts);
 628    }
 629    gen_refs(repo, Tab::Branches, &body)
 630}
 631
 632pub fn gen_tags(repo: &RepoInfo, counts: &HashMap<String, usize>) -> String {
 633    let tags: Vec<&RefInfo> = repo.tags.iter().collect();
 634    let heading = format!("tags <span class=\"count\">{}</span>", tags.len());
 635    let mut body = String::new();
 636    write_refs(&mut body, &heading, &tags, counts);
 637    gen_refs(repo, Tab::Tags, &body)
 638}
 639
 640fn gen_refs(repo: &RepoInfo, tab: Tab, body: &str) -> String {
 641    let nav = RepoNav {
 642        repo,
 643        git_ref: &repo.head_dir,
 644        tab,
 645        depth: 1,
 646        path: "",
 647        commits: repo.commit_list.len(),
 648    };
 649    wrap_page(&repo.name, Some(&nav), body)
 650}
 651
 652fn write_refs(
 653    body: &mut String,
 654    heading: &str,
 655    refs: &[&RefInfo],
 656    counts: &HashMap<String, usize>,
 657) {
 658    if refs.is_empty() {
 659        return;
 660    }
 661    body.push_str(&format!(
 662        "<header class=\"subtitle\"><h2>{heading}</h2></header>\n<div class=\"box mt-0 p-0\">\n"
 663    ));
 664    for git_ref in refs {
 665        body.push_str(&format!(
 666            "\
 667<div class=\"flex items-center gap-2 px row tree-row border-b branch-row\">\n\
 668<div class=\"flex-1 flex items-center gap branch-name\">{}<a class=\"truncate row-link\" href=\"../{}\">{}</a></div>\n\
 669<div class=\"tree-commit short-id branch-sha\">{}</div>\n\
 670{}\
 671{}\
 672<a class=\"branch-log\" href=\"../{}\">{}</a>\n\
 673</div>\n\
 674",
 675            ref_icon(git_ref),
 676            Tab::Tree.href(&git_ref.dir),
 677            escape_str(&git_ref.name),
 678            short_id("../", &git_ref.id),
 679            summary_cell("../", &git_ref.id, &git_ref.summary),
 680            date_cell(&git_ref.date),
 681            Tab::Commits.href(&git_ref.dir),
 682            commit_count(counts[&git_ref.dir])
 683        ));
 684    }
 685    body.push_str("</div>\n");
 686}
 687
 688pub fn gen_releases(repo: &RepoInfo, sums: &[Vec<(usize, String)>]) -> String {
 689    let nav = RepoNav {
 690        repo,
 691        git_ref: &repo.head_dir,
 692        tab: Tab::Releases,
 693        depth: 1,
 694        path: "",
 695        commits: repo.commit_list.len(),
 696    };
 697
 698    let mut body = format!(
 699        "<header class=\"subtitle\"><h2>releases <span class=\"count\">{}</span></h2></header>\n",
 700        repo.releases.len()
 701    );
 702    for (n, (release, sums)) in repo.releases.iter().zip(sums).enumerate() {
 703        let Some(tag) = repo.tags.iter().find(|t| t.name == release.tag) else {
 704            continue;
 705        };
 706        body.push_str(&format!(
 707            "\
 708<section id=\"release-{}\" class=\"box mt-0 p-0 rel\">\n\
 709<div class=\"flex items-center gap-2 px border-b rel-head\">\n\
 710<div class=\"flex-1 flex items-center gap rel-name\">{}<a class=\"truncate\" href=\"../{}\">{}</a></div>\n\
 711<div class=\"ml-auto flex items-center\">\n\
 712<div class=\"flex items-center tree-commit short-id\">{}</div>\n\
 713{}\
 714</div>\n\
 715</div>\n\
 716",
 717            n + 1,
 718            icon("release"),
 719            Tab::Tree.href(&format!("tags/{}", release.tag)),
 720            escape_str(&release.tag),
 721            short_id("../", &tag.id),
 722            date_cell(&release.date)
 723        ));
 724        if !release.notes.is_empty() {
 725            let notes = release.notes.as_bytes();
 726            write_markdown(
 727                &mut body,
 728                "markdown-body border-b",
 729                repo,
 730                tag,
 731                "",
 732                "../",
 733                notes,
 734            );
 735        }
 736        let dir = percent_encode(&release.tag);
 737        let (file_sums, archive_sums) = sums.split_at(release.files.len());
 738        for (name, sum) in release.files.iter().zip(file_sums) {
 739            let href = format!("{dir}/{}", percent_encode(name));
 740            body.push_str(&release_row("file", &href, name, name, sum));
 741        }
 742        let archive = archive_name(&repo.name, &release.tag);
 743        for (format, sum) in ARCHIVE_FORMATS.iter().zip(archive_sums) {
 744            let href = format!("../archive/{dir}.{format}");
 745            let download = format!("{archive}.{format}");
 746            body.push_str(&release_row(
 747                "file-archive",
 748                &href,
 749                &download,
 750                &download,
 751                sum,
 752            ));
 753        }
 754        body.push_str("</section>\n");
 755    }
 756
 757    wrap_page(&repo.name, Some(&nav), &body)
 758}
 759
 760fn release_row(
 761    icon_name: &str,
 762    href: &str,
 763    download: &str,
 764    label: &str,
 765    (bytes, sha256): &(usize, String),
 766) -> String {
 767    format!(
 768        "\
 769<div class=\"flex items-center gap-2 px row tree-row border-b rel-file\">\n\
 770<div class=\"flex-1 flex items-center gap rel-name\">{}<a class=\"truncate row-link\" download=\"{}\" href=\"{href}\">{}</a></div>\n\
 771<div class=\"truncate rel-sum\"><span class=\"rel-sum-label\">sha256</span> {sha256}</div>\n\
 772<div class=\"rel-size\">{}</div>\n\
 773</div>\n\
 774",
 775        icon(icon_name),
 776        escape_str(download),
 777        escape_str(label),
 778        format_bytes(*bytes)
 779    )
 780}
 781
 782fn summary_cell(repo_root: &str, id: &str, summary: &str) -> String {
 783    let summary = escape_str(summary);
 784    format!(
 785        "<div class=\"flex flex-2 tree-commit\"><a class=\"truncate\" href=\"{repo_root}commits/{id}\" title=\"{summary}\">{summary}</a></div>\n"
 786    )
 787}
 788
 789fn commit_cells(repo_root: &str, id: &str, summary: &str, date: &DateTime<FixedOffset>) -> String {
 790    format!(
 791        "\
 792{}\
 793<div class=\"ml-auto flex items-center\">\n\
 794<div class=\"flex items-center tree-commit short-id\">{}</div>\n\
 795{}\
 796</div>\n\
 797",
 798        summary_cell(repo_root, id, summary),
 799        short_id(repo_root, id),
 800        date_cell(date)
 801    )
 802}
 803
 804fn short_id(repo_root: &str, id: &str) -> String {
 805    format!(
 806        "<a href=\"{repo_root}commits/{id}\" class=\"commit-id\">{}{}</a>",
 807        icon("git-commit"),
 808        &id[..7]
 809    )
 810}
 811
 812fn date_cell(date: &DateTime<FixedOffset>) -> String {
 813    format!("<div class=\"tree-date\">{}</div>\n", date.format(DATE))
 814}
 815
 816fn format_zoned(date: &DateTime<FixedOffset>, format: &str) -> String {
 817    let seconds = date.offset().local_minus_utc();
 818    let sign = if seconds < 0 { '-' } else { '+' };
 819    let (hours, minutes) = (seconds.abs() / 3600, seconds.abs() % 3600 / 60);
 820    let zone = match (hours, minutes) {
 821        (0, 0) => String::new(),
 822        (_, 0) => format!("{sign}{hours}"),
 823        _ => format!("{sign}{hours}:{minutes:02}"),
 824    };
 825    format!("{}&nbsp;UTC{zone}", date.format(format))
 826}
 827
 828fn tree_depth(git_ref: &RefInfo, dir: &Dir) -> usize {
 829    1 + join_path(&git_ref.dir, &dir.path).split('/').count()
 830}
 831
 832fn last_details(repo_root: &str, last: &HashMap<String, &CommitInfo>, path: &str) -> String {
 833    last.get(path).map_or_else(String::new, |commit| {
 834        commit_cells(
 835            repo_root,
 836            &commit.id,
 837            &commit.summary,
 838            &commit.committer_date,
 839        )
 840    })
 841}
 842
 843pub fn gen_tree(
 844    repo: &RepoInfo,
 845    git_ref: &RefInfo,
 846    dir: &Dir,
 847    last: &HashMap<String, &CommitInfo>,
 848    commits: usize,
 849) -> String {
 850    let depth = tree_depth(git_ref, dir);
 851    let nav = RepoNav {
 852        repo,
 853        git_ref: &git_ref.dir,
 854        tab: Tab::Tree,
 855        depth,
 856        path: "",
 857        commits,
 858    };
 859    let repo_root = "../".repeat(depth);
 860
 861    let mut body = ref_bar(repo, git_ref, &dir.path, &repo_root, commits, "page");
 862    write_listing(&mut body, git_ref, dir, &repo_root, "", last);
 863    write_readme(&mut body, repo, git_ref, dir, &repo_root);
 864
 865    let title = format!("{}/{}", repo.name, git_ref.name);
 866    wrap_page(&title, Some(&nav), &body)
 867}
 868
 869pub fn gen_blob(
 870    repo: &RepoInfo,
 871    git_ref: &RefInfo,
 872    dir: &Dir,
 873    entry: &TreeEntry,
 874    content: &[u8],
 875    last: &HashMap<String, &CommitInfo>,
 876    commits: usize,
 877) -> String {
 878    let depth = tree_depth(git_ref, dir) + 1;
 879    let path = join_path(&dir.path, &entry.name);
 880    let nav = RepoNav {
 881        repo,
 882        git_ref: &git_ref.dir,
 883        tab: Tab::Tree,
 884        depth,
 885        path: &path,
 886        commits,
 887    };
 888    let repo_root = "../".repeat(depth);
 889    let details = last_details(&repo_root, last, &path);
 890
 891    let mut body = ref_bar(repo, git_ref, &path, &repo_root, commits, "page");
 892    if !details.is_empty() {
 893        body.push_str(&format!(
 894            "<div class=\"box joined flex items-center gap last-commit\">\n{details}</div>\n"
 895        ));
 896    }
 897    let views = has_source_view(entry);
 898    write_file_head(&mut body, entry, content, views);
 899    let text = entry.lines.is_some();
 900    match image_type(&entry.name) {
 901        Some(mime) => body.push_str(&format!(
 902            "<div class=\"box\"><img src=\"{}\" alt=\"{}\"></div>\n",
 903            data_uri(mime, content),
 904            escape_str(&entry.name)
 905        )),
 906        None if text && is_markdown(&entry.name) => write_markdown(
 907            &mut body,
 908            MARKDOWN_BOX,
 909            repo,
 910            git_ref,
 911            &dir.path,
 912            &repo_root,
 913            content,
 914        ),
 915        _ if text => write_code(&mut body, content),
 916        _ => body.push_str("binary file, cannot display\n"),
 917    }
 918    if views {
 919        write_code(&mut body, content);
 920    }
 921
 922    let title = format!("{}/{}/{path}", repo.name, git_ref.name);
 923    wrap_page(&title, Some(&nav), &body)
 924}
 925
 926fn write_file_head(body: &mut String, entry: &TreeEntry, content: &[u8], views: bool) {
 927    if views {
 928        body.push_str(
 929            "\
 930<input type=\"radio\" class=\"vh\" name=\"view\" id=\"view-source\">\n\
 931<input type=\"radio\" class=\"vh\" name=\"view\" id=\"view-rendered\" checked>\n\
 932<div class=\"buttons flex view-switch\"><label for=\"view-source\">source</label>\n\
 933<label for=\"view-rendered\">rendered</label></div>\n\
 934",
 935        );
 936    }
 937    let lines = entry
 938        .lines
 939        .map(|n| {
 940            let s = if n == 1 { "" } else { "s" };
 941            format!("<span>{n} line{s}</span>\n")
 942        })
 943        .unwrap_or_default();
 944    let bytes = entry.bytes.map(format_bytes).unwrap_or_default();
 945    let pixels = image_type(&entry.name)
 946        .and_then(|mime| image_size(mime, content))
 947        .map(|(width, height)| format!("<span>{width}x{height}px</span>\n"))
 948        .unwrap_or_default();
 949    body.push_str(&format!(
 950        "<div class=\"flex items-center file-head\">\n<div class=\"flex gap file-size\">\n{lines}<span>{bytes}</span>\n{pixels}</div>\n</div>\n"
 951    ));
 952}
 953
 954fn page_href(page: usize, to: usize) -> String {
 955    let up = if page == 1 { "" } else { "../" };
 956    here(if to == 1 {
 957        up.to_string()
 958    } else {
 959        format!("{up}{to}")
 960    })
 961}
 962
 963fn here(href: String) -> String {
 964    if href.is_empty() {
 965        "./".to_string()
 966    } else {
 967        href
 968    }
 969}
 970
 971pub fn commits_page(page: usize) -> String {
 972    if page == 1 {
 973        "index.html".to_string()
 974    } else {
 975        format!("{page}/index.html")
 976    }
 977}
 978
 979pub fn gen_commits(
 980    repo: &RepoInfo,
 981    git_ref: &RefInfo,
 982    all: &[CommitInfo],
 983    stats: &HashMap<String, String>,
 984    page: usize,
 985) -> String {
 986    let depth = 1 + git_ref.dir.split('/').count() + usize::from(page > 1);
 987    let nav = RepoNav {
 988        repo,
 989        git_ref: &git_ref.dir,
 990        tab: Tab::Commits,
 991        depth,
 992        path: "",
 993        commits: all.len(),
 994    };
 995    let repo_root = "../".repeat(depth);
 996    let total = all.len();
 997    let start = (page - 1) * COMMITS_PER_PAGE;
 998    let end = total.min(start + COMMITS_PER_PAGE);
 999    let commits = &all[start..end];
1000    let count = if page > 1 {
1001        format!(
1002            "<span class=\"font-bold\">{}&ndash;{end}</span> of {total} commits",
1003            start + 1
1004        )
1005    } else if end < total {
1006        format!("<span class=\"font-bold\">{end}</span> of {total} commits")
1007    } else {
1008        commit_count(total)
1009    };
1010
1011    let mut body = format!(
1012        "\
1013<div class=\"log\">\n\
1014<div class=\"box sticky flex items-center gap flex-wrap m-0\">\n\
1015{}\
1016<div>{count}</div>\n\
1017</div>\n\
1018",
1019        ref_menu(repo, git_ref, &repo_root, Tab::Commits, "", "page")
1020    );
1021    let mut day = String::new();
1022    let mut menus = 1;
1023    for commit in commits {
1024        let date = commit.committer_date.format(DATE).to_string();
1025        let joined = if date == day {
1026            " joined"
1027        } else {
1028            if !day.is_empty() {
1029                body.push_str("</div>\n");
1030            }
1031            body.push_str(&format!(
1032                "<div class=\"log-day\">\n<div class=\"text-xs log-date\">{date}</div>\n"
1033            ));
1034            ""
1035        };
1036        let labels = ref_labels(repo, &commit.id, &repo_root, &mut menus);
1037        write_commit_row(
1038            &mut body,
1039            commit,
1040            Some(&stats[&commit.id]),
1041            &labels,
1042            &repo_root,
1043            joined,
1044            &format_zoned(&commit.committer_date, "%H:%M"),
1045        );
1046        day = date;
1047    }
1048    body.push_str("</div>\n");
1049    let pages = total.div_ceil(COMMITS_PER_PAGE);
1050    if pages > 1 {
1051        body.push_str(&commits_pager(page, pages));
1052    }
1053    body.push_str("</div>\n");
1054
1055    let title = format!("{}/{}", repo.name, git_ref.name);
1056    wrap_page(&title, Some(&nav), &body)
1057}
1058
1059pub fn diff_stat(diff: &CommitDiff) -> String {
1060    if diff.files.is_empty() {
1061        return "no changes".to_string();
1062    }
1063    let s = if diff.files.len() == 1 { "" } else { "s" };
1064    format!(
1065        "<strong>{}</strong> file{s} changed,&nbsp;<span class=\"color-green\">+{}</span>, <span class=\"color-red\">-{}</span>",
1066        diff.files.len(),
1067        diff.files.iter().map(|f| f.added).sum::<usize>(),
1068        diff.files.iter().map(|f| f.removed).sum::<usize>()
1069    )
1070}
1071
1072pub fn gen_commit(
1073    repo: &RepoInfo,
1074    git_ref: &RefInfo,
1075    commit: &CommitInfo,
1076    diff: &CommitDiff,
1077    commits: usize,
1078) -> String {
1079    let nav = RepoNav {
1080        repo,
1081        git_ref: &git_ref.dir,
1082        tab: Tab::Commits,
1083        depth: 2,
1084        path: "",
1085        commits,
1086    };
1087    let short = &commit.id[..7];
1088    let parents: Vec<String> = diff
1089        .parents
1090        .iter()
1091        .map(|id| format!("<a href=\"../{id}\">{}</a>", &id[..7]))
1092        .collect();
1093    let parents = match parents.len() {
1094        0 => String::new(),
1095        1 => format!(
1096            "<div class=\"commit-parent\"><span>parent</span><span>{}</span></div>\n",
1097            parents[0]
1098        ),
1099        _ => format!(
1100            "<div class=\"commit-parent\"><span>parents</span><span>{}</span></div>\n",
1101            parents.join(", ")
1102        ),
1103    };
1104    let format = "%d-%m-%Y&nbsp;%H:%M";
1105    let rest = commit
1106        .message
1107        .trim()
1108        .split_once("\n\n")
1109        .map_or("", |(_, rest)| rest.trim());
1110    let message_body = if rest.is_empty() {
1111        String::new()
1112    } else {
1113        format!(
1114            "<div class=\"white-space-bs commit-body\">{}</div>\n",
1115            escape_str(rest)
1116        )
1117    };
1118
1119    let mut body = format!(
1120        "\
1121<div class=\"box commit-head\">\n\
1122<div class=\"flex gap commit-msg\">\n\
1123<div class=\"flex-1\">\n\
1124<div class=\"commit-title\"><span class=\"commit-id\">{}{short}</span>{}</div>\n\
1125{message_body}\
1126</div>\n\
1127<div>{}</div>\n\
1128</div>\n\
1129<div class=\"commit-meta\">\n\
1130<div>author</div>\n\
1131<div>{} &lt;{}&gt; on {}</div>\n\
1132<div>committer</div>\n\
1133<div>{} &lt;{}&gt; on {}</div>\n\
1134{parents}\
1135</div>\n\
1136</div>\n\
1137",
1138        icon("git-commit"),
1139        escape_str(&commit.summary),
1140        diff_stat(diff),
1141        escape_str(&commit.author_name),
1142        escape_str(&commit.author_email),
1143        format_zoned(&commit.author_date, format),
1144        escape_str(&commit.committer_name),
1145        escape_str(&commit.committer_email),
1146        format_zoned(&commit.committer_date, format)
1147    );
1148    if !diff.files.is_empty() {
1149        body.push_str("<div class=\"box joined commit-files\">\n");
1150        for (n, file) in diff.files.iter().enumerate() {
1151            body.push_str(&format!(
1152                "<div class=\"flex items-center gap\">{}<a href=\"#diff-{n}\">{}</a><div class=\"ml-auto diff-stat\">{}</div></div>\n",
1153                status_icon(file.status),
1154                change_path(file),
1155                file_stat(file)
1156            ));
1157        }
1158        body.push_str("</div>\n");
1159    }
1160    for (n, file) in diff.files.iter().enumerate() {
1161        body.push_str(&format!(
1162            "\
1163<div>\n\
1164<div id=\"diff-{n}\" class=\"box sticky flex items-center diff-head\">\n\
1165<div class=\"flex-1 flex items-center gap\">{}<a href=\"#diff-{n}\">{}</a></div>\n\
1166<div class=\"diff-stat\">{}</div>\n\
1167</div>\n\
1168",
1169            status_icon(file.status),
1170            change_path(file),
1171            file_stat(file)
1172        ));
1173        match file.binary {
1174            Some((old, new)) => {
1175                let sizes = match file.status {
1176                    'A' => format_bytes(new),
1177                    'D' => format_bytes(old),
1178                    _ => format!("{} &rarr; {}", format_bytes(old), format_bytes(new)),
1179                };
1180                body.push_str(&format!(
1181                    "<div class=\"box joined\">binary file, {sizes}</div>\n"
1182                ));
1183            }
1184            None if !file.lines.is_empty() => write_diff(&mut body, n, &file.lines),
1185            None if file.status == 'R' => {
1186                body.push_str("<div class=\"box joined\">renamed without changes</div>\n")
1187            }
1188            None => {}
1189        }
1190        body.push_str("</div>\n");
1191    }
1192
1193    let title = format!("{}/{short}: {}", repo.name, commit.summary);
1194    wrap_page(&title, Some(&nav), &body)
1195}
1196
1197fn status_icon(status: char) -> String {
1198    let (name, class, title) = match status {
1199        'A' => ("diff-added", " color-green", "added"),
1200        'D' => ("diff-removed", " color-red", "deleted"),
1201        'R' => ("diff-renamed", "", "renamed"),
1202        'T' => ("diff-modified", " color-orange", "type changed"),
1203        _ => ("diff-modified", " color-orange", "modified"),
1204    };
1205    format!(
1206        "<span class=\"flex{class}\" title=\"{title}\" role=\"img\" aria-label=\"{title}\">{}</span>",
1207        icon(name)
1208    )
1209}
1210
1211fn file_stat(file: &FileChange) -> String {
1212    format!(
1213        "<span class=\"color-green\">+{}</span>, <span class=\"color-red\">-{}</span>",
1214        file.added, file.removed
1215    )
1216}
1217
1218fn change_path(file: &FileChange) -> String {
1219    match &file.old_path {
1220        Some(old) => format!("{} &rarr; {}", escape_str(old), escape_str(&file.path)),
1221        None => escape_str(&file.path),
1222    }
1223}
1224
1225fn write_diff(body: &mut String, n: usize, lines: &[Line]) {
1226    let max = lines.iter().filter_map(|l| l.old.max(l.new)).max();
1227    let width = max.unwrap_or(0).to_string().len();
1228    let number = |body: &mut String, side: &str, num: Option<u32>| {
1229        let _ = match num {
1230            Some(num) => write!(
1231                body,
1232                "<a class=\"ln\" id=\"d{n}-{side}{num}\" href=\"#d{n}-{side}{num}\" tabindex=\"-1\">{num:>width$}</a>"
1233            ),
1234            None => write!(body, "<span class=\"ln\">{:width$}</span>", ""),
1235        };
1236    };
1237    body.push_str("<pre class=\"chroma joined\"><code>");
1238    for line in lines {
1239        let text = escape_str(&line.text);
1240        let (class, text, old, new) = match line.origin {
1241            '@' => ("", format!("<span class=\"gu\">{text}</span>"), None, None),
1242            '+' => (" gi", format!("+{text}"), None, line.new),
1243            '-' => (" gd", format!("-{text}"), line.old, None),
1244            ' ' => ("", format!(" {text}"), line.old, line.new),
1245            _ => ("", "\\ No newline at end of file\n".to_string(), None, None),
1246        };
1247        let _ = write!(body, "<span class=\"line{class}\">");
1248        number(body, "L", old);
1249        number(body, "R", new);
1250        body.push_str("<span class=\"cl\">");
1251        push_line(body, &text);
1252        body.push_str("</span></span>");
1253    }
1254    body.push_str("</code></pre>\n");
1255}
1256
1257fn commits_pager(page: usize, pages: usize) -> String {
1258    let arrow = |n: usize, label: &str, name: &str| {
1259        format!(
1260            "<a href=\"{}\" title=\"{label}\" aria-label=\"{label}\">{}</a>\n",
1261            page_href(page, n),
1262            icon(name)
1263        )
1264    };
1265    let mut pager =
1266        String::from("<nav class=\"buttons flex flex-wrap pager\" aria-label=\"pages\">\n");
1267    if page > 1 {
1268        pager.push_str(&arrow(page - 1, "previous page", "chevron-left"));
1269    }
1270    let mut shown = 0;
1271    for n in 1..=pages {
1272        if n != 1 && n != pages && n.abs_diff(page) > 1 {
1273            continue;
1274        }
1275        if n > shown + 1 {
1276            pager.push_str("<span class=\"pager-gap\">&hellip;</span>\n");
1277        }
1278        if n == page {
1279            pager.push_str(&format!("<span aria-current=\"page\">{n}</span>\n"));
1280        } else {
1281            pager.push_str(&format!("<a href=\"{}\">{n}</a>\n", page_href(page, n)));
1282        }
1283        shown = n;
1284    }
1285    if page < pages {
1286        pager.push_str(&arrow(page + 1, "next page", "chevron-right"));
1287    }
1288    pager.push_str("</nav>\n");
1289    pager
1290}
1291
1292fn has_source_view(entry: &TreeEntry) -> bool {
1293    entry.lines.is_some() && (image_type(&entry.name).is_some() || is_markdown(&entry.name))
1294}
1295
1296fn blob_href(git_ref: &RefInfo, path: &str) -> String {
1297    percent_encode(&format!("blob/{}/{path}", git_ref.dir))
1298}
1299
1300pub fn path_href(git_ref: &RefInfo, repo_root: &str, path: &str) -> Option<String> {
1301    let path = follow_links(git_ref, path)?;
1302    if git_ref.dirs.contains_key(&path) {
1303        let href = Tab::Tree.href(&join_path(&git_ref.dir, &path));
1304        return Some(format!("{repo_root}{href}"));
1305    }
1306    let entry = find_entry(git_ref, &path)?;
1307    if entry.blob.is_some() {
1308        return Some(format!("{repo_root}{}", blob_href(git_ref, &path)));
1309    }
1310    entry.commit.as_ref()?;
1311    git_ref
1312        .submodules
1313        .iter()
1314        .find(|(module, url)| *module == path && url.starts_with("https://"))
1315        .map(|(_, url)| url.clone())
1316}
1317
1318pub fn follow_links(git_ref: &RefInfo, path: &str) -> Option<String> {
1319    let mut path = path.to_string();
1320    let mut dir_only = false;
1321    for _ in 0..=MAX_LINKS {
1322        let dir = path.rsplit_once('/').map_or("", |(dir, _)| dir);
1323        let link = find_entry(git_ref, &path).and_then(|entry| entry.link.as_deref());
1324        match link {
1325            Some(target) if target.is_empty() || target.starts_with('/') => return None,
1326            Some(target) => {
1327                dir_only |= target.ends_with('/');
1328                path = resolve_path(dir, target)?;
1329            }
1330            None => {
1331                let is_dir = git_ref.dirs.contains_key(&path);
1332                return (is_dir || !dir_only).then_some(path);
1333            }
1334        }
1335    }
1336    None
1337}
1338
1339pub fn resolve_path(base: &str, path: &str) -> Option<String> {
1340    let mut parts: Vec<&str> = base.split('/').filter(|part| !part.is_empty()).collect();
1341    for part in path.split('/') {
1342        match part {
1343            "" | "." => {}
1344            ".." => {
1345                parts.pop()?;
1346            }
1347            _ => parts.push(part),
1348        }
1349    }
1350    Some(parts.join("/"))
1351}
1352
1353fn find_entry<'a>(git_ref: &'a RefInfo, path: &str) -> Option<&'a TreeEntry> {
1354    let (dir, name) = path.rsplit_once('/').unwrap_or(("", path));
1355    git_ref.dirs.get(dir)?.entry(name)
1356}
1357
1358pub fn find_file<'a>(git_ref: &'a RefInfo, path: &str) -> Option<&'a TreeEntry> {
1359    find_entry(git_ref, path).filter(|entry| entry.blob.is_some())
1360}
1361
1362pub fn data_uri(mime: &str, content: &[u8]) -> String {
1363    format!("data:{mime};base64,{}", base64(content))
1364}
1365
1366pub fn image_type(name: &str) -> Option<&'static str> {
1367    let (_, ext) = name.rsplit_once('.')?;
1368    IMAGE_TYPES
1369        .iter()
1370        .find(|(known, _)| ext.eq_ignore_ascii_case(known))
1371        .map(|(_, mime)| *mime)
1372}
1373
1374fn image_size(mime: &str, content: &[u8]) -> Option<(usize, usize)> {
1375    if mime != "image/svg+xml" {
1376        let size = imagesize::blob_size(content).ok()?;
1377        return Some((size.width, size.height));
1378    }
1379    let text = String::from_utf8_lossy(content);
1380    let start = text.find("<svg")?;
1381    let tag = &text[start..start + text[start..].find('>')?];
1382    let number = |value: &str| value.trim().trim_end_matches("px").parse::<f64>().ok();
1383    if let (Some(width), Some(height)) = (
1384        attr(tag, "width").and_then(number),
1385        attr(tag, "height").and_then(number),
1386    ) {
1387        return Some((width.round() as usize, height.round() as usize));
1388    }
1389    let view_box: Vec<f64> = attr(tag, "viewBox")?
1390        .split(|c: char| c.is_whitespace() || c == ',')
1391        .filter(|part| !part.is_empty())
1392        .map(str::parse)
1393        .collect::<Result<_, _>>()
1394        .ok()?;
1395    match view_box[..] {
1396        [_, _, width, height] => Some((width.round() as usize, height.round() as usize)),
1397        _ => None,
1398    }
1399}
1400
1401fn attr<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
1402    let mut from = 0;
1403    while let Some(i) = tag[from..].find(name).map(|i| from + i) {
1404        from = i + name.len();
1405        if !tag[..i].ends_with(|c: char| c.is_ascii_whitespace()) {
1406            continue;
1407        }
1408        let Some(value) = tag[from..].strip_prefix('=') else {
1409            continue;
1410        };
1411        let quote = value.chars().next().filter(|c| matches!(c, '"' | '\''))?;
1412        return value[1..].find(quote).map(|end| &value[1..1 + end]);
1413    }
1414    None
1415}
1416
1417fn base64(bytes: &[u8]) -> String {
1418    let mut encoded = String::with_capacity(bytes.len().div_ceil(3) * 4);
1419    for chunk in bytes.chunks(3) {
1420        let byte = |i: usize| chunk.get(i).copied().unwrap_or(0);
1421        let n = u32::from_be_bytes([0, byte(0), byte(1), byte(2)]);
1422        for i in 0..4 {
1423            if i <= chunk.len() {
1424                encoded.push(BASE64_CHARS[((n >> (18 - 6 * i)) & 63) as usize] as char);
1425            } else {
1426                encoded.push('=');
1427            }
1428        }
1429    }
1430    encoded
1431}
1432
1433fn ref_bar(
1434    repo: &RepoInfo,
1435    git_ref: &RefInfo,
1436    path: &str,
1437    repo_root: &str,
1438    commits: usize,
1439    current: &str,
1440) -> String {
1441    let mut bar =
1442        String::from("<div class=\"box sticky flex items-center gap flex-wrap ref-bar\">\n");
1443    bar.push_str(&ref_menu(
1444        repo,
1445        git_ref,
1446        repo_root,
1447        Tab::Tree,
1448        path,
1449        current,
1450    ));
1451    let mut parts = vec![(repo.name.as_str(), git_ref.dir.clone())];
1452    for part in path.split('/').filter(|p| !p.is_empty()) {
1453        let tree_path = format!("{}/{part}", parts[parts.len() - 1].1);
1454        parts.push((part, tree_path));
1455    }
1456    for (i, (part, tree_path)) in parts.iter().enumerate() {
1457        if i > 0 {
1458            bar.push_str("<span>/</span>\n");
1459        }
1460        if i == parts.len() - 1 {
1461            bar.push_str(&format!(
1462                "<span class=\"font-bold\">{}</span>\n",
1463                escape_str(part)
1464            ));
1465        } else {
1466            bar.push_str(&format!(
1467                "<a href=\"{repo_root}{}\">{}</a>\n",
1468                Tab::Tree.href(tree_path),
1469                escape_str(part)
1470            ));
1471        }
1472    }
1473    bar.push_str(&format!(
1474        "<a class=\"ref-bar-commits\" href=\"{repo_root}{}\">{}</a>\n</div>\n",
1475        Tab::Commits.href(&git_ref.dir),
1476        commit_count(commits)
1477    ));
1478    bar
1479}
1480
1481fn commit_count(commits: usize) -> String {
1482    let s = if commits == 1 { "" } else { "s" };
1483    format!("<span class=\"font-bold\">{commits}</span> commit{s}")
1484}
1485
1486fn menu_target(git_ref: &RefInfo, path: &str) -> (String, bool) {
1487    if find_file(git_ref, path).is_some() {
1488        return (blob_href(git_ref, path), true);
1489    }
1490    let mut dir = path;
1491    while !dir.is_empty() && !git_ref.dirs.contains_key(dir) {
1492        dir = dir.rsplit_once('/').map_or("", |(parent, _)| parent);
1493    }
1494    (Tab::Tree.href(&join_path(&git_ref.dir, dir)), dir == path)
1495}
1496
1497fn ref_menu(
1498    repo: &RepoInfo,
1499    git_ref: &RefInfo,
1500    repo_root: &str,
1501    tab: Tab,
1502    path: &str,
1503    current: &str,
1504) -> String {
1505    let name = escape_str(&git_ref.name);
1506    let mut menu = format!(
1507        "\
1508<div class=\"ref-menu\">\n\
1509<button type=\"button\" class=\"ref-btn\" popovertarget=\"ref-menu\" aria-label=\"{name}, switch branch or tag\">{}<span class=\"truncate\">{name}</span>{}{}</button>\n\
1510<div class=\"ref-menu-list\" id=\"ref-menu\" popover>\n\
1511",
1512        ref_icon(git_ref),
1513        icon("chevron-down"),
1514        icon("chevron-up")
1515    );
1516    let list = |class: &str, refs: &[RefInfo]| -> String {
1517        let long = if refs.len() > REF_MENU_ROWS {
1518            " long"
1519        } else {
1520            ""
1521        };
1522        let entries: String = refs
1523            .iter()
1524            .map(|r| {
1525                let active = if r.dir == git_ref.dir {
1526                    format!(" aria-current=\"{current}\"")
1527                } else {
1528                    String::new()
1529                };
1530                let (href, found) = match tab {
1531                    Tab::Tree => menu_target(r, path),
1532                    _ => (tab.href(&r.dir), true),
1533                };
1534                let kind = if r.is_tag() {
1535                    "tag"
1536                } else {
1537                    "branch"
1538                };
1539                let (missing, title) = if found {
1540                    ("", String::new())
1541                } else {
1542                    (" missing", format!(" title=\"not in this {kind}\""))
1543                };
1544                format!(
1545                    "<a class=\"flex items-center gap{missing}\"{title}{active} href=\"{repo_root}{href}\">{}{}</a>\n",
1546                    ref_icon(r),
1547                    escape_str(&r.name)
1548                )
1549            })
1550            .collect();
1551        format!("<div class=\"{class} buttons{long}\">\n{entries}</div>\n")
1552    };
1553    if !repo.tags.is_empty() {
1554        let (branches, tags) = if git_ref.is_tag() {
1555            ("", " checked")
1556        } else {
1557            (" checked", "")
1558        };
1559        menu.push_str(&format!(
1560            "\
1561<input type=\"radio\" class=\"vh\" name=\"ref-kind\" id=\"ref-branches\"{branches}>\n\
1562<input type=\"radio\" class=\"vh\" name=\"ref-kind\" id=\"ref-tags\"{tags}>\n\
1563<div class=\"ref-kinds buttons flex\"><label for=\"ref-branches\">branches</label><label for=\"ref-tags\">tags</label></div>\n\
1564{}\
1565",
1566            list("ref-tags", &repo.tags)
1567        ));
1568    }
1569    menu.push_str(&list("ref-branches", &repo.branches));
1570    menu.push_str("</div>\n</div>\n");
1571    menu
1572}
1573
1574fn write_code(body: &mut String, content: &[u8]) {
1575    let text = escape_str(&String::from_utf8_lossy(content));
1576    let lines: Vec<&str> = text.split_inclusive('\n').collect();
1577    let width = lines.len().to_string().len();
1578    let _ = write!(
1579        body,
1580        "<pre class=\"chroma\" style=\"--ln: {width}ch\"><code>"
1581    );
1582    for (i, line) in lines.iter().enumerate() {
1583        let n = i + 1;
1584        let (text, newline) = match line.strip_suffix('\n') {
1585            Some(text) => (text, "\n"),
1586            None => (*line, ""),
1587        };
1588        let _ = write!(
1589            body,
1590            "<a class=\"ln\" id=\"L{n}\" href=\"#L{n}\" tabindex=\"-1\">{n:>width$}</a><span class=\"cl\">"
1591        );
1592        push_line(body, text);
1593        body.push_str("</span>");
1594        body.push_str(newline);
1595    }
1596    body.push_str("</code></pre>\n");
1597}
1598
1599fn push_line(body: &mut String, text: &str) {
1600    for (i, piece) in text.split('\r').enumerate() {
1601        if i > 0 && !piece.starts_with('\n') {
1602            body.push('\n');
1603        }
1604        body.push_str(piece);
1605    }
1606}
1607
1608fn write_listing(
1609    body: &mut String,
1610    git_ref: &RefInfo,
1611    dir: &Dir,
1612    repo_root: &str,
1613    tree_dir: &str,
1614    last: &HashMap<String, &CommitInfo>,
1615) {
1616    body.push_str("<div class=\"box p-0 joined\">\n");
1617    let head = if dir.path.is_empty() {
1618        commit_cells(repo_root, &git_ref.id, &git_ref.summary, &git_ref.date)
1619    } else {
1620        last_details(repo_root, last, &dir.path)
1621    };
1622    if !head.is_empty() {
1623        body.push_str(&format!(
1624            "<div class=\"flex items-center gap px border-b last-commit\">\n{head}</div>\n"
1625        ));
1626    }
1627    if !dir.path.is_empty() {
1628        body.push_str(&format!(
1629            "\
1630<div class=\"flex items-center gap-2 px row tree-row border-b up-row\">\n\
1631<div class=\"flex-1 tree-path flex items-center gap\">\n\
1632{}\n\
1633<a class=\"truncate row-link\" href=\"../\" title=\"parent folder\">..</a>\n\
1634</div>\n\
1635</div>\n\
1636",
1637            icon("file-directory")
1638        ));
1639    }
1640    for entry in &dir.entries {
1641        let name = &entry.name;
1642        let path = join_path(&dir.path, name);
1643        let link = |href: String, text: String| {
1644            format!(
1645                "<a class=\"truncate row-link\" href=\"{}\">{text}</a>",
1646                escape_str(&href)
1647            )
1648        };
1649        let leads = |text: String| match path_href(git_ref, repo_root, &path) {
1650            Some(href) => link(href, text),
1651            None => format!("<span class=\"truncate\">{text}</span>"),
1652        };
1653        let last_change = match last.get(&path) {
1654            Some(commit) => format!(
1655                "{}{}",
1656                summary_cell(repo_root, &commit.id, &commit.summary),
1657                date_cell(&commit.committer_date)
1658            ),
1659            None => {
1660                "<div class=\"flex flex-2 tree-commit\"></div>\n<div class=\"tree-date\"></div>\n"
1661                    .to_string()
1662            }
1663        };
1664        let (icon_name, name) = if entry.is_dir {
1665            let href = percent_encode(&format!("{tree_dir}{name}/"));
1666            ("file-directory", link(href, escape_str(name)))
1667        } else if let Some(target) = &entry.link {
1668            let text = format!("{} &rarr; {}", escape_str(name), escape_str(target));
1669            ("file-symlink-file", leads(text))
1670        } else if let Some(commit) = &entry.commit {
1671            let text = format!("{} @ {}", escape_str(name), &commit[..7]);
1672            ("file-submodule", leads(text))
1673        } else {
1674            ("file", leads(escape_str(name)))
1675        };
1676        body.push_str(&format!(
1677            "\
1678<div class=\"flex items-center gap-2 px row tree-row border-b\">\n\
1679<div class=\"flex-1 tree-path flex items-center gap\">\n\
1680{}\n\
1681{name}\n\
1682</div>\n\
1683{last_change}\
1684</div>\n\
1685",
1686            icon(icon_name)
1687        ));
1688    }
1689    body.push_str("</div>\n");
1690}
1691
1692fn ref_labels(repo: &RepoInfo, id: &str, repo_root: &str, menus: &mut usize) -> String {
1693    let mut refs: Vec<&RefInfo> = repo
1694        .branches
1695        .iter()
1696        .chain(&repo.tags)
1697        .filter(|git_ref| git_ref.id == id)
1698        .collect();
1699    if refs.is_empty() {
1700        return String::new();
1701    }
1702    refs.sort_by(|a, b| RefInfo::newest_first(a, b));
1703    let link = |git_ref: &&RefInfo| {
1704        (
1705            format!("{repo_root}{}", Tab::Tree.href(&git_ref.dir)),
1706            format!("{}{}", ref_icon(git_ref), escape_str(&git_ref.name)),
1707        )
1708    };
1709    let chips: String = refs
1710        .iter()
1711        .take(REF_CHIPS)
1712        .map(|git_ref| {
1713            let (href, text) = link(git_ref);
1714            format!("<a class=\"chip flex\" href=\"{href}\"><code>{text}</code></a>\n")
1715        })
1716        .collect();
1717    let entries: String = refs
1718        .iter()
1719        .map(|git_ref| {
1720            let (href, text) = link(git_ref);
1721            format!("<a class=\"flex items-center gap\" href=\"{href}\">{text}</a>\n")
1722        })
1723        .collect();
1724    *menus += 1;
1725    let n = *menus;
1726    let s = if refs.len() == 1 { "" } else { "s" };
1727    format!(
1728        "\
1729<div class=\"chips text-xs\">\n{chips}</div>\n\
1730<div class=\"ref-menu ref-more text-xs\">\n\
1731<button type=\"button\" class=\"ref-btn\" popovertarget=\"ref-more-{n}\">{} ref{s}{}{}</button>\n\
1732<div class=\"ref-menu-list buttons\" id=\"ref-more-{n}\" popover>\n{entries}</div>\n\
1733</div>\n\
1734",
1735        refs.len(),
1736        icon("chevron-down"),
1737        icon("chevron-up")
1738    )
1739}
1740
1741fn write_commit_row(
1742    body: &mut String,
1743    commit: &CommitInfo,
1744    stat: Option<&str>,
1745    labels: &str,
1746    repo_root: &str,
1747    joined: &str,
1748    date: &str,
1749) {
1750    let href = format!("{repo_root}commits/{}", commit.id);
1751    let stat = stat
1752        .map(|stat| format!("<div class=\"commit-stat flex-1\"><div>{stat}</div></div>\n"))
1753        .unwrap_or_default();
1754    body.push_str(&format!(
1755        "\
1756<div class=\"box m-0 row commit-row{joined}\">\n\
1757<div class=\"flex flex-wrap items-center gap text-xs\">\n\
1758<a href=\"{href}\" class=\"commit-id row-link\">{}{}</a>\n\
1759<div class=\"flex items-center commit-by\">\n\
1760<span class=\"truncate\">{}</span>\n\
1761<span>&nbsp;&centerdot;&nbsp;</span>\n\
1762<span>{date}</span>\n\
1763</div>\n\
1764{stat}\
1765</div>\n\
1766<div class=\"flex items-center commit-line\">\n\
1767<div class=\"flex commit-summary\"><a class=\"truncate row-link\" href=\"{href}\">{}</a></div>\n\
1768{labels}\
1769</div>\n\
1770</div>\n\
1771",
1772        icon("git-commit"),
1773        &commit.id[..7],
1774        escape_str(&commit.author_name),
1775        escape_str(&commit.summary)
1776    ));
1777}
1778
1779fn write_briefs(body: &mut String, repo: &RepoInfo) {
1780    body.push_str("<div>\n<header class=\"subtitle\">\n<h2>commits</h2>\n</header>\n");
1781    let mut menus = 1;
1782    for (n, commit) in repo.commit_list.iter().take(BRIEF_COUNT).enumerate() {
1783        let joined = if n == 0 { "" } else { " joined" };
1784        let labels = ref_labels(repo, &commit.id, "", &mut menus);
1785        let date = commit.committer_date.format(DATE).to_string();
1786        write_commit_row(body, commit, None, &labels, "", joined, &date);
1787    }
1788    body.push_str(&format!(
1789        "\
1790<div class=\"box m-0 joined row side-all px\">\n\
1791<a class=\"row-link\" href=\"{}\">all commits</a>\n\
1792</div>\n\
1793</div>\n\
1794",
1795        Tab::Commits.href(&repo.head_dir)
1796    ));
1797}