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