| 1 | |
| 2 | |
| 3 | |
| 4 | pub mod commit_line; |
| 5 | pub mod commit_status; |
| 6 | pub mod diff; |
| 7 | pub mod find; |
| 8 | pub mod heatmap; |
| 9 | pub mod parts; |
| 10 | pub mod repo_list; |
| 11 | pub mod review_thread; |
| 12 | pub mod timeline; |
| 13 | |
| 14 | use std::collections::HashMap; |
| 15 | use std::sync::OnceLock; |
| 16 | |
| 17 | use forge_core::ci::RunState; |
| 18 | use forge_core::config::BannerConfig; |
| 19 | use forge_core::store::shell_activity::{ActorRun, ActorRuns, InboxKinds}; |
| 20 | use forge_core::store::user_prefs::SOUND; |
| 21 | use forge_core::token::hash_token; |
| 22 | use forge_core::{Config, Error as CoreError, Session, User}; |
| 23 | use hex::encode; |
| 24 | use http::header::{ |
| 25 | CONTENT_SECURITY_POLICY, REFERRER_POLICY, X_CONTENT_TYPE_OPTIONS, X_FRAME_OPTIONS, |
| 26 | }; |
| 27 | use http::{HeaderValue, Uri}; |
| 28 | use sha2::{Digest, Sha256}; |
| 29 | use topcoat::Result; |
| 30 | use topcoat::context::{Cx, try_context}; |
| 31 | use topcoat::cookie::{Cookies, cookies}; |
| 32 | use topcoat::router::request::uri; |
| 33 | use topcoat::router::response::{Response, response_headers}; |
| 34 | use topcoat::router::{Body, Next, layer}; |
| 35 | use topcoat::view::{Child, Unescaped, View, ViewExt, component, view}; |
| 36 | |
| 37 | use crate::i18n::admin::{self as ad, K as AK}; |
| 38 | use crate::i18n::authoring::{self as au, K as AuK}; |
| 39 | use crate::i18n::browse as br; |
| 40 | use crate::i18n::code::{self as g, K}; |
| 41 | use crate::i18n::community::{self as cm, K as CK}; |
| 42 | use crate::i18n::link::{self as lk, K as LinkKey}; |
| 43 | use crate::i18n::migrate::{self as mg, K as MGK}; |
| 44 | use crate::i18n::misc::{self as mi, K as MK}; |
| 45 | use crate::i18n::orgs::{self as o, K as OK}; |
| 46 | use crate::i18n::packages::{self as pk, K as PK}; |
| 47 | use crate::i18n::s; |
| 48 | use crate::i18n::{self, Key, Lang, t}; |
| 49 | use crate::render::highlight::highlight_css; |
| 50 | use crate::state::AppState; |
| 51 | |
| 52 | |
| 53 | |
| 54 | pub const STYLESHEET_HREF: &str = concat!("/assets/main.css?v=", env!("FORGE_MAIN_CSS_V")); |
| 55 | |
| 56 | |
| 57 | pub const FIGTREE_PRELOAD_HREF: &str = "/assets/fonts/figtree-5.3.0-latin-wght.woff2"; |
| 58 | |
| 59 | |
| 60 | |
| 61 | pub fn highlight_href() -> &'static str { |
| 62 | static HREF: OnceLock<String> = OnceLock::new(); |
| 63 | HREF.get_or_init(|| { |
| 64 | let version = encode(Sha256::digest(highlight_css_text().as_bytes())); |
| 65 | format!("/assets/highlight.css?v={}", &version[..12]) |
| 66 | }) |
| 67 | } |
| 68 | |
| 69 | |
| 70 | pub const NAV_SCRIPT_HREF: &str = concat!("/assets/nav.js?v=", env!("FORGE_NAV_JS_V")); |
| 71 | |
| 72 | const CSP: &str = "default-src 'self'; style-src 'self'; img-src 'self' data:; form-action 'self'; frame-ancestors 'none'"; |
| 73 | |
| 74 | |
| 75 | static APP_CSP: OnceLock<HeaderValue> = OnceLock::new(); |
| 76 | |
| 77 | |
| 78 | |
| 79 | fn origin_of(base: &str) -> Option<String> { |
| 80 | let uri: Uri = base.trim().parse().ok()?; |
| 81 | let scheme = uri.scheme_str()?; |
| 82 | if scheme != "http" && scheme != "https" { |
| 83 | return None; |
| 84 | } |
| 85 | let authority = uri.authority()?.as_str(); |
| 86 | if authority.contains('@') { |
| 87 | return None; |
| 88 | } |
| 89 | Some(format!("{scheme}://{authority}")) |
| 90 | } |
| 91 | |
| 92 | |
| 93 | fn csp_for(raw_origin: Option<&str>) -> String { |
| 94 | match raw_origin { |
| 95 | Some(origin) => format!( |
| 96 | "default-src 'self'; style-src 'self'; img-src 'self' data: {origin}; form-action 'self'; frame-ancestors 'none'" |
| 97 | ), |
| 98 | None => CSP.to_owned(), |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | |
| 103 | fn csp_header(base_url: &str) -> HeaderValue { |
| 104 | let policy = csp_for(origin_of(base_url).as_deref()); |
| 105 | HeaderValue::from_str(&policy).unwrap_or_else(|_| HeaderValue::from_static(CSP)) |
| 106 | } |
| 107 | |
| 108 | |
| 109 | const TOP_LEVEL_PAGES: &[&str] = &[ |
| 110 | "explore", |
| 111 | "notifications", |
| 112 | "settings", |
| 113 | "admin", |
| 114 | "new", |
| 115 | "snippets", |
| 116 | "login", |
| 117 | "logout", |
| 118 | "register", |
| 119 | "forgot", |
| 120 | "import", |
| 121 | "review-requests", |
| 122 | "setup", |
| 123 | "needs-you", |
| 124 | "verify", |
| 125 | "reset", |
| 126 | "org", |
| 127 | ]; |
| 128 | |
| 129 | |
| 130 | fn percent_decode(s: &str) -> String { |
| 131 | let bytes = s.as_bytes(); |
| 132 | let mut out = Vec::with_capacity(bytes.len()); |
| 133 | let mut i = 0; |
| 134 | while i < bytes.len() { |
| 135 | if bytes[i] == b'%' |
| 136 | && let Some(hex) = s.get(i + 1..i + 3) |
| 137 | && let Ok(byte) = u8::from_str_radix(hex, 16) |
| 138 | { |
| 139 | out.push(byte); |
| 140 | i += 3; |
| 141 | } else { |
| 142 | out.push(bytes[i]); |
| 143 | i += 1; |
| 144 | } |
| 145 | } |
| 146 | String::from_utf8_lossy(&out).into_owned() |
| 147 | } |
| 148 | |
| 149 | |
| 150 | fn crumb_label(part: &str) -> String { |
| 151 | if part.len() == 40 && part.bytes().all(|b| b.is_ascii_hexdigit()) { |
| 152 | part[..7].to_owned() |
| 153 | } else { |
| 154 | part.to_owned() |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | |
| 159 | fn step_label(lang: Lang, word: &str) -> String { |
| 160 | match word { |
| 161 | "new" => s(lang, "New", "Yeni").to_owned(), |
| 162 | "edit" => s(lang, "Edit", "Düzenle").to_owned(), |
| 163 | "history" => s(lang, "History", "Geçmiş").to_owned(), |
| 164 | "revisions" => s(lang, "Revisions", "Sürümler").to_owned(), |
| 165 | "files" => s(lang, "Files", "Dosyalar").to_owned(), |
| 166 | "commits" => g::t(lang, K::TabCommits).to_owned(), |
| 167 | other => crumb_label(other), |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | |
| 172 | |
| 173 | fn repo_section_label(lang: Lang, kind: &str) -> Option<String> { |
| 174 | match kind { |
| 175 | "issues" | "pulls" | "ci" | "commits" | "branches" | "tags" | "releases" |
| 176 | | "discussions" | "wiki" | "security" | "settings" => Some(tab_title(lang, kind, "")), |
| 177 | "milestones" => Some(s(lang, "Milestones", "Kilometre taşları").to_owned()), |
| 178 | "labels" => Some(s(lang, "Labels", "Etiketler").to_owned()), |
| 179 | _ => None, |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option<String>)> { |
| 189 | let parts: Vec<String> = path |
| 190 | .trim_matches('/') |
| 191 | .split('/') |
| 192 | .filter(|part| !part.is_empty()) |
| 193 | .map(percent_decode) |
| 194 | .collect(); |
| 195 | let Some(owner) = parts.first() else { |
| 196 | return Vec::new(); |
| 197 | }; |
| 198 | |
| 199 | let titled = title.rsplit_once(" · ").map(|(_, last)| last.to_owned()); |
| 200 | match parts |
| 201 | .iter() |
| 202 | .map(String::as_str) |
| 203 | .collect::<Vec<_>>() |
| 204 | .as_slice() |
| 205 | { |
| 206 | ["snippets", id, rest @ ..] => { |
| 207 | let mut segments = vec![( |
| 208 | cm::t(lang, CK::Snippets).to_owned(), |
| 209 | Some("/snippets".to_owned()), |
| 210 | )]; |
| 211 | match rest { |
| 212 | |
| 213 | [] => segments.push((title.to_owned(), None)), |
| 214 | |
| 215 | |
| 216 | [.., last] => { |
| 217 | let back = if *last == "revisions" { |
| 218 | title.to_owned() |
| 219 | } else { |
| 220 | s(lang, "Snippet", "Parçacık").to_owned() |
| 221 | }; |
| 222 | segments.push((back, Some(format!("/snippets/{}", enc(id))))); |
| 223 | segments.push((step_label(lang, last), None)); |
| 224 | } |
| 225 | } |
| 226 | return segments; |
| 227 | } |
| 228 | ["org", name, rest @ ..] if *name != "new" && !rest.is_empty() => { |
| 229 | let page = titled.unwrap_or_else(|| step_label(lang, rest[rest.len() - 1])); |
| 230 | return vec![((*name).to_owned(), Some(user_href(name))), (page, None)]; |
| 231 | } |
| 232 | _ => {} |
| 233 | } |
| 234 | if owner.starts_with('-') || TOP_LEVEL_PAGES.contains(&owner.as_str()) { |
| 235 | return Vec::new(); |
| 236 | } |
| 237 | let mut segments = vec![(owner.clone(), Some(user_href(owner)))]; |
| 238 | if let Some(repo) = parts.get(1) { |
| 239 | segments.push((repo.clone(), Some(repo_href(owner, repo, "", "")))); |
| 240 | match &parts[2..] { |
| 241 | [kind, git_ref, prefix @ ..] |
| 242 | if matches!(kind.as_str(), "tree" | "blob") && !prefix.is_empty() => |
| 243 | { |
| 244 | let mut at = git_ref.clone(); |
| 245 | for part in prefix { |
| 246 | at.push('/'); |
| 247 | at.push_str(part); |
| 248 | segments.push((crumb_label(part), Some(repo_href(owner, repo, "tree", &at)))); |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | [] => {} |
| 253 | [kind, rest @ ..] => { |
| 254 | |
| 255 | |
| 256 | |
| 257 | let full = format!("{owner}/{repo}"); |
| 258 | let mut tail = title.rsplit(" · "); |
| 259 | let named = match tail.next() { |
| 260 | Some(last) if last == full => None, |
| 261 | Some(last) if last.starts_with(&format!("{full} ")) => tail.next(), |
| 262 | last => last, |
| 263 | } |
| 264 | .map(str::to_owned); |
| 265 | let section = if kind == "commit" { |
| 266 | "commits" |
| 267 | } else { |
| 268 | kind.as_str() |
| 269 | }; |
| 270 | match (repo_section_label(lang, section), rest) { |
| 271 | |
| 272 | (None, [oid]) if kind == "scrub" => { |
| 273 | let short: String = oid.chars().take(7).collect(); |
| 274 | segments.push(( |
| 275 | g::t(lang, K::TabCommits).to_owned(), |
| 276 | Some(repo_href(owner, repo, "commits", "")), |
| 277 | )); |
| 278 | segments.push((short, Some(repo_href(owner, repo, "commit", oid)))); |
| 279 | segments.push((step_label(lang, "files"), None)); |
| 280 | } |
| 281 | |
| 282 | (None, rest) if matches!(kind.as_str(), "compare" | "search") => { |
| 283 | let word = if kind == "compare" { |
| 284 | s(lang, "Compare", "Karşılaştır") |
| 285 | } else { |
| 286 | s(lang, "Search", "Ara") |
| 287 | }; |
| 288 | if rest.is_empty() { |
| 289 | segments.push((word.to_owned(), None)); |
| 290 | } else { |
| 291 | segments |
| 292 | .push((word.to_owned(), Some(repo_href(owner, repo, kind, "")))); |
| 293 | segments.push((rest.join("/"), None)); |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | (None, _) | (Some(_), []) => { |
| 298 | let page = named.unwrap_or_else(|| { |
| 299 | parts[2..] |
| 300 | .iter() |
| 301 | .map(|part| crumb_label(part)) |
| 302 | .collect::<Vec<_>>() |
| 303 | .join("/") |
| 304 | }); |
| 305 | segments.push((page, None)); |
| 306 | } |
| 307 | (Some(label), rest) => { |
| 308 | segments.push((label, Some(repo_href(owner, repo, section, "")))); |
| 309 | let item = rest[0].as_str(); |
| 310 | let numbered = matches!(section, "issues" | "pulls" | "discussions") |
| 311 | && item.bytes().all(|b| b.is_ascii_digit()); |
| 312 | match (section, rest) { |
| 313 | ("ci", [runs, number]) if runs == "runs" => { |
| 314 | segments.push((format!("#{number}"), None)); |
| 315 | } |
| 316 | _ if numbered && rest.len() == 1 => { |
| 317 | segments.push((format!("#{item}"), None)); |
| 318 | } |
| 319 | _ if numbered => { |
| 320 | segments.push(( |
| 321 | format!("#{item}"), |
| 322 | Some(repo_href(owner, repo, section, item)), |
| 323 | )); |
| 324 | |
| 325 | |
| 326 | let step = if rest.iter().any(|part| part == "history") { |
| 327 | "history" |
| 328 | } else { |
| 329 | rest[rest.len() - 1].as_str() |
| 330 | }; |
| 331 | segments.push((step_label(lang, step), None)); |
| 332 | } |
| 333 | ("wiki", [dash, new]) if dash == "-" && new == "new" => { |
| 334 | segments.push((s(lang, "New page", "Yeni sayfa").to_owned(), None)); |
| 335 | } |
| 336 | ("wiki" | "settings", [page, more @ ..]) |
| 337 | if !more.is_empty() && page != "-" => |
| 338 | { |
| 339 | let page_label = match page.as_str() { |
| 340 | "hooks" => { |
| 341 | i18n::integrations::t(lang, i18n::integrations::K::Webhooks) |
| 342 | .to_owned() |
| 343 | } |
| 344 | other => crumb_label(other), |
| 345 | }; |
| 346 | segments.push(( |
| 347 | page_label, |
| 348 | Some(repo_href(owner, repo, section, page)), |
| 349 | )); |
| 350 | let last = more[more.len() - 1].as_str(); |
| 351 | segments.push((step_label(lang, last), None)); |
| 352 | } |
| 353 | _ => { |
| 354 | let page = named.unwrap_or_else(|| { |
| 355 | step_label(lang, rest[rest.len() - 1].as_str()) |
| 356 | }); |
| 357 | segments.push((page, None)); |
| 358 | } |
| 359 | } |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 | if let Some(last) = segments.last_mut() { |
| 366 | last.1 = None; |
| 367 | } |
| 368 | segments |
| 369 | } |
| 370 | |
| 371 | |
| 372 | struct PathCrumb { |
| 373 | label: String, |
| 374 | href: Option<String>, |
| 375 | class: &'static str, |
| 376 | } |
| 377 | |
| 378 | |
| 379 | struct StripRun { |
| 380 | pill_class: String, |
| 381 | row_class: String, |
| 382 | label: String, |
| 383 | |
| 384 | text: String, |
| 385 | href: String, |
| 386 | } |
| 387 | |
| 388 | |
| 389 | |
| 390 | struct LiveStrip { |
| 391 | runs: Vec<StripRun>, |
| 392 | summary_class: &'static str, |
| 393 | summary: String, |
| 394 | } |
| 395 | |
| 396 | |
| 397 | |
| 398 | fn live_strip(lang: Lang, runs: &ActorRuns) -> LiveStrip { |
| 399 | let mut rows = Vec::new(); |
| 400 | for run in &runs.running { |
| 401 | let job = run.current_job.as_deref().unwrap_or(""); |
| 402 | rows.push(strip_run( |
| 403 | "hot", |
| 404 | run, |
| 405 | if job.is_empty() { |
| 406 | String::new() |
| 407 | } else { |
| 408 | format!(" {job}") |
| 409 | }, |
| 410 | )); |
| 411 | } |
| 412 | for run in &runs.finished { |
| 413 | let (state, word) = match run.state { |
| 414 | RunState::Success => ("ok", mi::t(lang, MK::Passed)), |
| 415 | RunState::Failure | RunState::Error => ("bad", mi::t(lang, MK::Failed)), |
| 416 | RunState::Cancelled => ("off", mi::t(lang, MK::Cancelled)), |
| 417 | _ => continue, |
| 418 | }; |
| 419 | rows.push(strip_run(state, run, format!(" {word}"))); |
| 420 | } |
| 421 | let count = |pred: fn(RunState) -> bool| { |
| 422 | runs.finished.iter().filter(|run| pred(run.state)).count() as u64 |
| 423 | }; |
| 424 | let running = runs.running.len() as u64; |
| 425 | let failed = count(|state| matches!(state, RunState::Failure | RunState::Error)); |
| 426 | let passed = count(|state| matches!(state, RunState::Success)); |
| 427 | let cancelled = count(|state| matches!(state, RunState::Cancelled)); |
| 428 | let summary_class = if running > 0 { |
| 429 | "pill hot" |
| 430 | } else if failed > 0 { |
| 431 | "pill bad" |
| 432 | } else if passed > 0 { |
| 433 | "pill ok" |
| 434 | } else { |
| 435 | "pill off" |
| 436 | }; |
| 437 | let parts = [ |
| 438 | (running, mi::running_count as fn(Lang, u64) -> String), |
| 439 | (failed, mi::failed_count), |
| 440 | (passed, mi::passed_count), |
| 441 | (cancelled, mi::cancelled_count), |
| 442 | ]; |
| 443 | let summary = parts |
| 444 | .iter() |
| 445 | .filter(|(n, _)| *n > 0) |
| 446 | .map(|(n, phrase)| phrase(lang, *n)) |
| 447 | .collect::<Vec<_>>() |
| 448 | .join(" · "); |
| 449 | LiveStrip { |
| 450 | runs: rows, |
| 451 | summary_class, |
| 452 | summary, |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | fn strip_run(state: &str, run: &ActorRun, text: String) -> StripRun { |
| 457 | StripRun { |
| 458 | pill_class: format!("pill {state}"), |
| 459 | row_class: format!("strip-row {state}"), |
| 460 | label: format!("{} #{}", run.repo, run.number), |
| 461 | text, |
| 462 | href: repo_href(&run.owner, &run.repo, "ci", &format!("runs/{}", run.number)), |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | |
| 467 | fn count_template(phrase: &str, n: u64) -> String { |
| 468 | phrase.replacen(&n.to_string(), "{n}", 1) |
| 469 | } |
| 470 | |
| 471 | |
| 472 | fn no_runs() -> ActorRuns { |
| 473 | ActorRuns { |
| 474 | running: Vec::new(), |
| 475 | finished: Vec::new(), |
| 476 | failing: 0, |
| 477 | newest_failing: None, |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | |
| 482 | |
| 483 | #[derive(Clone)] |
| 484 | struct ProfileCorner { |
| 485 | username: String, |
| 486 | |
| 487 | name: String, |
| 488 | avatar: String, |
| 489 | csrf: String, |
| 490 | is_admin: bool, |
| 491 | |
| 492 | unread: u64, |
| 493 | |
| 494 | waiting: bool, |
| 495 | } |
| 496 | |
| 497 | |
| 498 | |
| 499 | |
| 500 | #[component] |
| 501 | async fn profile_corner(cx: &Cx, lang: Lang, corner: ProfileCorner) -> Result<impl View> { |
| 502 | let profile_href = user_href(&corner.username); |
| 503 | let profile_label = mi::t(lang, MK::YourProfile); |
| 504 | let settings_label = o::t(lang, OK::Settings); |
| 505 | let admin_label = ad::t(lang, AK::AdminArea); |
| 506 | let logout_label = t(lang, Key::LogOut); |
| 507 | let inbox_label = t(lang, Key::Notifications); |
| 508 | let class = if corner.unread > 0 || corner.waiting { |
| 509 | "corner waiting" |
| 510 | } else { |
| 511 | "corner" |
| 512 | }; |
| 513 | Ok(view! { |
| 514 | <details class=(class) data-unread-stream=""> |
| 515 | <summary class="corner-btn" aria-label=(corner.username.as_str())> |
| 516 | <img class="avatar corner-avatar" src=(corner.avatar.as_str()) alt="" width="32" height="32"> |
| 517 | </summary> |
| 518 | <div class="corner-menu"> |
| 519 | <a class="corner-who" href=(profile_href.as_str()) title=(profile_label)>(corner.name.as_str())</a> |
| 520 | <a class="corner-link corner-bell" href="/notifications"> |
| 521 | <span>(inbox_label)</span> |
| 522 | if corner.unread > 0 { |
| 523 | <span class="bell-count">(corner.unread.to_string())</span> |
| 524 | } |
| 525 | </a> |
| 526 | <div class="corner-sep"></div> |
| 527 | <a class="corner-link" href="/settings/profile">(settings_label)</a> |
| 528 | if corner.is_admin { |
| 529 | <a class="corner-link" href="/admin/users">(admin_label)</a> |
| 530 | } |
| 531 | <div class="corner-sep"></div> |
| 532 | <form data-hard="true" method="post" action="/logout"> |
| 533 | <input type="hidden" name="csrf" value=(corner.csrf.as_str())> |
| 534 | <button type="submit" class="corner-link link-button">(logout_label)</button> |
| 535 | </form> |
| 536 | </div> |
| 537 | </details> |
| 538 | }) |
| 539 | } |
| 540 | |
| 541 | |
| 542 | |
| 543 | |
| 544 | |
| 545 | |
| 546 | #[component] |
| 547 | pub async fn shell( |
| 548 | cx: &Cx, |
| 549 | title: &str, |
| 550 | viewer: Option<&(User, Session)>, |
| 551 | #[default] extra_stylesheet: Option<&str>, |
| 552 | #[default] parents: Vec<(String, String)>, |
| 553 | #[default] child: Child<'_>, |
| 554 | ) -> Result<impl View> { |
| 555 | let full_title = format!("{title} \u{b7} forge"); |
| 556 | |
| 557 | |
| 558 | let (unread, inbox, runs) = match viewer { |
| 559 | Some((user, _)) => match try_context::<AppState>(cx) { |
| 560 | Some(state) => ( |
| 561 | state.store.unread_count(&user.id).await?, |
| 562 | state.store.inbox_kind_counts(&user.id).await?, |
| 563 | state.store.actor_runs(&user.id, 120).await?, |
| 564 | ), |
| 565 | None => (0, InboxKinds::default(), no_runs()), |
| 566 | }, |
| 567 | None => (0, InboxKinds::default(), no_runs()), |
| 568 | }; |
| 569 | let signed_in = viewer.is_some(); |
| 570 | |
| 571 | |
| 572 | |
| 573 | let theme_csrf = viewer.map(|(_, session)| session.csrf_token.clone()); |
| 574 | let back = uri(cx).path_and_query().map(|p| p.as_str().to_owned()); |
| 575 | let lang = i18n::lang(cx, viewer.map(|(user, _)| user)); |
| 576 | |
| 577 | |
| 578 | let prefs = match (viewer, try_context::<AppState>(cx)) { |
| 579 | (Some((user, _)), Some(state)) => Some(state.store.user_prefs(&user.id).await?), |
| 580 | _ => None, |
| 581 | }; |
| 582 | let banner = current_banner(cx, prefs.as_ref()); |
| 583 | let sound_attr = sound_attr(prefs.as_ref()); |
| 584 | let banner_back = back.clone().unwrap_or_else(|| "/".to_owned()); |
| 585 | let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss); |
| 586 | |
| 587 | let section = if signed_in { |
| 588 | section_for(lang, uri(cx).path()) |
| 589 | } else { |
| 590 | None |
| 591 | }; |
| 592 | let width = page_width(uri(cx).path()); |
| 593 | let theme_attr = crate::theme::data_theme(cx, viewer.map(|(user, _)| user)); |
| 594 | |
| 595 | let rel_words_attr = rel_words(lang); |
| 596 | let rel_now_attr = now_unix().to_string(); |
| 597 | |
| 598 | |
| 599 | |
| 600 | let (stored_accent_light, stored_accent_dark, stored_base_light, stored_base_dark) = |
| 601 | match viewer { |
| 602 | Some((user, _)) => ( |
| 603 | user.accent.as_str(), |
| 604 | user.accent_dark.as_str(), |
| 605 | user.base_light.as_str(), |
| 606 | user.base_dark.as_str(), |
| 607 | ), |
| 608 | None => ( |
| 609 | crate::accent_palette::DEFAULT, |
| 610 | crate::accent_palette::DEFAULT, |
| 611 | crate::accent_palette::BASE_DEFAULT, |
| 612 | crate::accent_palette::BASE_DEFAULT, |
| 613 | ), |
| 614 | }; |
| 615 | |
| 616 | let accent_light_id = crate::accent::accent_id(stored_accent_light); |
| 617 | let accent_dark_id = crate::accent::accent_id(stored_accent_dark); |
| 618 | let base_light_id = crate::accent::base_id(stored_base_light); |
| 619 | let base_dark_id = crate::accent::base_id(stored_base_dark); |
| 620 | |
| 621 | let custom_css = crate::accent::custom_css_href( |
| 622 | accent_light_id, |
| 623 | accent_dark_id, |
| 624 | base_light_id, |
| 625 | base_dark_id, |
| 626 | ); |
| 627 | |
| 628 | let sidebar_side = match viewer { |
| 629 | Some((user, _)) if user.sidebar_side == "right" => "right", |
| 630 | _ => "left", |
| 631 | }; |
| 632 | |
| 633 | |
| 634 | let theme_pref = crate::theme::preference(cx, viewer.map(|(user, _)| user)); |
| 635 | let next_theme = crate::theme::next_preference(theme_pref); |
| 636 | let theme_state = match theme_pref { |
| 637 | "light" => mi::t(lang, MK::Light), |
| 638 | "dark" => mi::t(lang, MK::Dark), |
| 639 | _ => mi::t(lang, MK::MatchSystem), |
| 640 | }; |
| 641 | let theme_next = match next_theme { |
| 642 | "light" => MK::SwitchToLight, |
| 643 | "dark" => MK::SwitchToDark, |
| 644 | _ => MK::SwitchToMatchSystem, |
| 645 | }; |
| 646 | let switch_label = format!( |
| 647 | "{}: {}. {}", |
| 648 | mi::t(lang, MK::ThemeLabel), |
| 649 | theme_state, |
| 650 | mi::t(lang, theme_next), |
| 651 | ); |
| 652 | let palette_label = br::t(lang, br::K::PaletteOpen).to_owned(); |
| 653 | let explore_label = t(lang, Key::Explore); |
| 654 | let home_label = o::t(lang, OK::Home); |
| 655 | |
| 656 | let mut segments = path_segments(lang, uri(cx).path(), title); |
| 657 | |
| 658 | |
| 659 | if segments.is_empty() { |
| 660 | if let Some(section) = §ion { |
| 661 | let first = section.items.first().map(|item| item.href.clone()); |
| 662 | if section.title != title { |
| 663 | segments.push((section.title.clone(), first)); |
| 664 | } |
| 665 | let path = uri(cx).path(); |
| 666 | if let Some(item) = section.items.iter().find(|item| { |
| 667 | path.strip_prefix(item.href.as_str()) |
| 668 | .is_some_and(|below| below.starts_with('/')) |
| 669 | }) { |
| 670 | segments.push((item.label.to_owned(), Some(item.href.clone()))); |
| 671 | } |
| 672 | } |
| 673 | segments.push((title.to_owned(), None)); |
| 674 | } |
| 675 | |
| 676 | if !parents.is_empty() { |
| 677 | let at = segments.len().saturating_sub(1); |
| 678 | for (offset, (label, href)) in parents.into_iter().enumerate() { |
| 679 | segments.insert(at + offset, (label, Some(href))); |
| 680 | } |
| 681 | } |
| 682 | let path_attr = segments |
| 683 | .iter() |
| 684 | .map(|(label, _)| label.as_str()) |
| 685 | .collect::<Vec<_>>() |
| 686 | .join("/"); |
| 687 | let crumbs: Vec<PathCrumb> = segments |
| 688 | .into_iter() |
| 689 | .enumerate() |
| 690 | .map(|(i, (label, href))| PathCrumb { |
| 691 | class: if i == 0 && href.is_some() { |
| 692 | "pathbar-seg owner" |
| 693 | } else { |
| 694 | "pathbar-seg" |
| 695 | }, |
| 696 | label, |
| 697 | href, |
| 698 | }) |
| 699 | .collect(); |
| 700 | let strip = live_strip(lang, &runs); |
| 701 | |
| 702 | let running_tpl = count_template(&mi::running_count(lang, 2), 2); |
| 703 | let failed_tpl = count_template(&mi::failed_count(lang, 2), 2); |
| 704 | let passed_tpl = count_template(&mi::passed_count(lang, 2), 2); |
| 705 | let cancelled_tpl = count_template(&mi::cancelled_count(lang, 2), 2); |
| 706 | let runs_label = mi::t(lang, MK::YourCiRuns); |
| 707 | let search_for_label = mi::t(lang, MK::SearchPublicReposFor); |
| 708 | |
| 709 | |
| 710 | let corner = viewer.map(|(user, session)| ProfileCorner { |
| 711 | username: user.username.clone(), |
| 712 | name: user |
| 713 | .display_name |
| 714 | .as_deref() |
| 715 | .map(str::trim) |
| 716 | .filter(|n| !n.is_empty()) |
| 717 | .unwrap_or(&user.username) |
| 718 | .to_owned(), |
| 719 | avatar: avatar_url(&user.username, user.avatar_hash.as_deref()), |
| 720 | csrf: session.csrf_token.clone(), |
| 721 | is_admin: user.is_admin, |
| 722 | unread, |
| 723 | waiting: inbox.reviews + inbox.mentions + runs.failing > 0, |
| 724 | }); |
| 725 | Ok(view! { |
| 726 | <!DOCTYPE html> |
| 727 | <html lang=(lang.code()) data-theme=(theme_attr) data-sound=(sound_attr)data-accent-light=(accent_light_id) data-accent-dark=(accent_dark_id) data-base-light=(base_light_id) data-base-dark=(base_dark_id) data-sidebar=(sidebar_side) data-rel-words=(rel_words_attr.as_str()) data-rel-now=(rel_now_attr.as_str())> |
| 728 | <head> |
| 729 | <meta charset="utf-8"> |
| 730 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 731 | <meta name="referrer" content="same-origin"> |
| 732 | <meta name="theme-color" content="#b44d1a"> |
| 733 | <meta name="apple-mobile-web-app-capable" content="yes"> |
| 734 | <link rel="manifest" href="/manifest.webmanifest"> |
| 735 | <link rel="apple-touch-icon" href="/assets/icons/apple-touch-icon.png"> |
| 736 | <title>(full_title)</title> |
| 737 | <link rel="preload" as="font" type="font/woff2" crossorigin="anonymous" href=(FIGTREE_PRELOAD_HREF)> |
| 738 | <link rel="stylesheet" href=(STYLESHEET_HREF)> |
| 739 | if let Some(href) = &custom_css { |
| 740 | <link rel="stylesheet" href=(href)> |
| 741 | } |
| 742 | <link rel="stylesheet" href=(highlight_href())> |
| 743 | if let Some(href) = extra_stylesheet { |
| 744 | <link rel="stylesheet" href=(href)> |
| 745 | } |
| 746 | <script src=(NAV_SCRIPT_HREF) defer="defer"></script> |
| 747 | </head> |
| 748 | <body data-link-restarting=(lk::t(lang, LinkKey::Restarting)) data-link-back=(lk::t(lang, LinkKey::BackSubmit)) data-done-saved=(lk::t(lang, LinkKey::Saved)) data-done-ok=(lk::t(lang, LinkKey::Done)) data-draft-restored=(lk::t(lang, LinkKey::DraftRestored)) data-draft-discard=(lk::t(lang, LinkKey::DraftDiscard)) data-select-filter=(lk::t(lang, LinkKey::SelectFilter)) data-select-none=(lk::t(lang, LinkKey::SelectNone)) data-signed-in=(signed_in.then(|| "true".to_owned()))> |
| 749 | <header class="topbar"> |
| 750 | <div class="top-start"> |
| 751 | if let Some(corner) = corner { |
| 752 | <div class="corner-float"> |
| 753 | profile_corner(lang: lang, corner: corner) |
| 754 | </div> |
| 755 | } |
| 756 | <a class="wordmark" href="/" title=(home_label)>"forge"</a> |
| 757 | </div> |
| 758 | <nav class="pathbar" aria-label=(mi::t(lang, MK::BreadcrumbNav))> |
| 759 | <ol class="pathbar-segs"> |
| 760 | for crumb in crumbs.iter() { |
| 761 | if let Some(href) = &crumb.href { |
| 762 | <li><a class=(crumb.class) href=(href.as_str())>(crumb.label.as_str())</a></li> |
| 763 | } else { |
| 764 | <li><span class="pathbar-seg last" aria-current="page">(crumb.label.as_str())</span></li> |
| 765 | } |
| 766 | } |
| 767 | </ol> |
| 768 | if signed_in { |
| 769 | |
| 770 | <button type="button" class="pathbar-edit" data-palette-open="" data-path=(path_attr.as_str()) aria-label=(palette_label.as_str()) title=(palette_label.as_str()) |
| 771 | data-placeholder=(br::t(lang, br::K::PalettePlaceholder)) data-repos=(br::t(lang, br::K::PaletteRepos)) |
| 772 | data-orgs=(o::t(lang, OK::Organizations)) data-pages=(br::t(lang, br::K::PalettePages)) |
| 773 | data-empty=(br::t(lang, br::K::PaletteNoMatches)) data-loading=(br::t(lang, br::K::PaletteLoading)) |
| 774 | data-failed=(br::t(lang, br::K::PaletteFailed)) |
| 775 | data-key-move=(crate::i18n::s(lang, "move", "gezin")) |
| 776 | data-key-open=(crate::i18n::s(lang, "open", "aç")) |
| 777 | data-key-close=(crate::i18n::s(lang, "close", "kapat")) |
| 778 | data-search-label=(search_for_label) data-files=(br::t(lang, br::K::PaletteFiles)) |
| 779 | data-actions=(br::t(lang, br::K::PaletteActions)) data-done=(br::t(lang, br::K::PaletteDone)) |
| 780 | data-action-failed=(br::t(lang, br::K::PaletteActionFailed))> |
| 781 | <span class="pathbar-hint">(br::t(lang, br::K::PathbarHint))</span> |
| 782 | <kbd>"Ctrl K"</kbd> |
| 783 | </button> |
| 784 | } |
| 785 | </nav> |
| 786 | <a class="top-explore" href="/explore">(explore_label)</a> |
| 787 | if signed_in { |
| 788 | <div class="live-strip" data-activity="/-/activity" data-passed=(mi::t(lang, MK::Passed)) data-failed=(mi::t(lang, MK::Failed)) data-cancelled=(mi::t(lang, MK::Cancelled)) |
| 789 | data-count-running=(running_tpl.as_str()) data-count-failed=(failed_tpl.as_str()) data-count-passed=(passed_tpl.as_str()) data-count-cancelled=(cancelled_tpl.as_str()) |
| 790 | data-runs-label=(runs_label) aria-live="polite"> |
| 791 | if strip.runs.len() == 1 { |
| 792 | for run in strip.runs.iter() { |
| 793 | <a class=(run.pill_class.as_str()) href=(run.href.as_str())><span class="pill-dot"></span><b>(run.label.as_str())</b>(run.text.as_str())</a> |
| 794 | } |
| 795 | } |
| 796 | if strip.runs.len() > 1 { |
| 797 | <details class="strip-runs" id="strip-runs"> |
| 798 | <summary class=(strip.summary_class) aria-label=(runs_label)><span class="pill-dot"></span>(strip.summary.as_str())</summary> |
| 799 | <ul class="strip-list"> |
| 800 | for run in strip.runs.iter() { |
| 801 | <li><a class=(run.row_class.as_str()) href=(run.href.as_str())><span class="pill-dot"></span><b>(run.label.as_str())</b>(run.text.as_str())</a></li> |
| 802 | } |
| 803 | </ul> |
| 804 | </details> |
| 805 | } |
| 806 | </div> |
| 807 | } else { |
| 808 | <form class="theme-form" method="post" action="/-/theme"> |
| 809 | if let Some(csrf) = theme_csrf { |
| 810 | <input type="hidden" name="csrf" value=(csrf.as_str())> |
| 811 | } |
| 812 | if let Some(back) = back { |
| 813 | <input type="hidden" name="back" value=(back.as_str())> |
| 814 | } |
| 815 | <input type="hidden" name="theme" value=(next_theme)> |
| 816 | <button type="submit" class="icon-btn" aria-label=(switch_label.as_str()) title=(switch_label.as_str())> |
| 817 | if theme_pref == "light" { |
| 818 | <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg> |
| 819 | } else if theme_pref == "dark" { |
| 820 | <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z"/></svg> |
| 821 | } else { |
| 822 | <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8 20h8M12 16v4"/></svg> |
| 823 | } |
| 824 | </button> |
| 825 | </form> |
| 826 | <a class="button primary" href="/login">(t(lang, Key::LogIn))</a> |
| 827 | } |
| 828 | </header> |
| 829 | if let Some(banner) = banner { |
| 830 | <div class=(if banner.warning { "site-banner warning" } else { "site-banner" }) role="status" data-expires=(banner.expires.map(|t| t.to_string()))> |
| 831 | <p>(banner.message.as_str())</p> |
| 832 | <form method="post" action="/-/banner/dismiss"> |
| 833 | <input type="hidden" name="hash" value=(banner.hash.as_str())> |
| 834 | <input type="hidden" name="back" value=(banner_back.as_str())> |
| 835 | <button type="submit" class="icon-btn" aria-label=(dismiss_label) title=(dismiss_label)> |
| 836 | <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"/></svg> |
| 837 | </button> |
| 838 | </form> |
| 839 | </div> |
| 840 | } |
| 841 | <div class="shell"> |
| 842 | <div class="shell-body"> |
| 843 | <main tabindex="-1" data-width=(width)> |
| 844 | if let Some(section) = section { |
| 845 | section_tabs(key: section.key, label: section.title.as_str(), items: section.items, current: section.current, live: section.live) |
| 846 | } |
| 847 | (child) |
| 848 | </main> |
| 849 | </div> |
| 850 | </div> |
| 851 | </body> |
| 852 | </html> |
| 853 | } |
| 854 | |
| 855 | .boxed()) |
| 856 | } |
| 857 | |
| 858 | |
| 859 | |
| 860 | #[derive(Clone)] |
| 861 | pub struct NavItem { |
| 862 | pub key: &'static str, |
| 863 | pub href: String, |
| 864 | pub label: &'static str, |
| 865 | } |
| 866 | |
| 867 | |
| 868 | #[derive(Clone)] |
| 869 | pub struct Section { |
| 870 | |
| 871 | pub key: &'static str, |
| 872 | pub title: String, |
| 873 | pub items: Vec<NavItem>, |
| 874 | pub current: &'static str, |
| 875 | |
| 876 | pub live: &'static str, |
| 877 | } |
| 878 | |
| 879 | |
| 880 | |
| 881 | |
| 882 | pub fn page_width(path: &str) -> &'static str { |
| 883 | let parts: Vec<&str> = path.trim_matches('/').split('/').collect(); |
| 884 | match parts.as_slice() { |
| 885 | ["settings" | "admin", ..] | ["new", ..] | ["org", "new"] | ["org", _, "settings", ..] => { |
| 886 | "col" |
| 887 | } |
| 888 | [ |
| 889 | "login" | "register" | "forgot" | "reset" | "setup" | "invite", |
| 890 | .., |
| 891 | ] => "col", |
| 892 | [_, _, section, ..] => match *section { |
| 893 | "settings" | "new" | "edit" | "fork" | "transfer" | "rename" => "col", |
| 894 | "tree" | "blob" | "blame" | "commit" | "compare" | "ci" | "raw" | "edit-file" |
| 895 | | "scrub" => "wide", |
| 896 | "pulls" if parts.len() > 4 => "wide", |
| 897 | _ => "read", |
| 898 | }, |
| 899 | [_, _] => "wide", |
| 900 | _ => "read", |
| 901 | } |
| 902 | } |
| 903 | |
| 904 | pub fn admin_items(lang: Lang) -> Vec<NavItem> { |
| 905 | let item = |key, href: &'static str, label| NavItem { |
| 906 | key, |
| 907 | href: href.to_owned(), |
| 908 | label, |
| 909 | }; |
| 910 | vec![ |
| 911 | item("users", "/admin/users", ad::t(lang, AK::Users)), |
| 912 | item("runners", "/admin/runners", ad::t(lang, AK::Runners)), |
| 913 | item("server", "/admin/server", ad::t(lang, AK::ServerSettings)), |
| 914 | item("mail", "/admin/mail", ad::t(lang, AK::Mail)), |
| 915 | item("backups", "/admin/backups", ad::t(lang, AK::Backups)), |
| 916 | item( |
| 917 | "health", |
| 918 | "/admin/health", |
| 919 | crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Health), |
| 920 | ), |
| 921 | item("audit", "/admin/audit", ad::t(lang, AK::AuditLog)), |
| 922 | ] |
| 923 | } |
| 924 | |
| 925 | |
| 926 | |
| 927 | |
| 928 | |
| 929 | pub fn profile_items( |
| 930 | lang: Lang, |
| 931 | username: &str, |
| 932 | is_org: bool, |
| 933 | own_profile: bool, |
| 934 | org_member: bool, |
| 935 | ) -> Vec<NavItem> { |
| 936 | let profile = format!("/{}", enc(username)); |
| 937 | let tab = |key: &'static str, label: &'static str| NavItem { |
| 938 | key, |
| 939 | href: format!("{profile}?tab={key}"), |
| 940 | label, |
| 941 | }; |
| 942 | let mut items = vec![ |
| 943 | tab("overview", o::t(lang, OK::TabOverview)), |
| 944 | tab("repositories", o::t(lang, OK::Repositories)), |
| 945 | ]; |
| 946 | if !is_org { |
| 947 | items.push(tab("snippets", cm::t(lang, CK::Snippets))); |
| 948 | items.push(tab("stars", o::t(lang, OK::TabStars))); |
| 949 | } |
| 950 | items.push(tab("packages", pk::t(lang, PK::TabPackages))); |
| 951 | if own_profile { |
| 952 | items.push(tab("organizations", o::t(lang, OK::Organizations))); |
| 953 | } |
| 954 | if is_org && org_member { |
| 955 | let org = format!("/org/{}", enc(username)); |
| 956 | items.push(NavItem { |
| 957 | key: "members", |
| 958 | href: format!("{org}/members"), |
| 959 | label: o::t(lang, OK::Members), |
| 960 | }); |
| 961 | items.push(NavItem { |
| 962 | key: "teams", |
| 963 | href: format!("{org}/teams"), |
| 964 | label: o::t(lang, OK::Teams), |
| 965 | }); |
| 966 | } |
| 967 | items |
| 968 | } |
| 969 | |
| 970 | |
| 971 | |
| 972 | pub fn global_items(lang: Lang, can_create_org: bool) -> Vec<NavItem> { |
| 973 | let item = |key: &'static str, href: &'static str, label: &'static str| NavItem { |
| 974 | key, |
| 975 | href: href.to_owned(), |
| 976 | label, |
| 977 | }; |
| 978 | let mut items = vec![ |
| 979 | item("explore", "/explore", t(lang, Key::Explore)), |
| 980 | item( |
| 981 | "notifications", |
| 982 | "/notifications", |
| 983 | t(lang, Key::Notifications), |
| 984 | ), |
| 985 | item( |
| 986 | "reviews", |
| 987 | "/review-requests", |
| 988 | au::t(lang, AuK::ReviewRequests), |
| 989 | ), |
| 990 | item( |
| 991 | "needs-you", |
| 992 | "/needs-you", |
| 993 | crate::i18n::needs::t(lang, crate::i18n::needs::K::NeedsYou), |
| 994 | ), |
| 995 | item("new", "/new", t(lang, Key::NewRepository)), |
| 996 | item("import", "/new/import", mg::t(lang, MGK::ImportTitle)), |
| 997 | ]; |
| 998 | if can_create_org { |
| 999 | items.push(item("new-org", "/org/new", o::t(lang, OK::NewOrganization))); |
| 1000 | } |
| 1001 | items |
| 1002 | } |
| 1003 | |
| 1004 | pub fn settings_items(lang: Lang) -> Vec<NavItem> { |
| 1005 | let pk = crate::i18n::s; |
| 1006 | let item = |key, href: &'static str, label| NavItem { |
| 1007 | key, |
| 1008 | href: href.to_owned(), |
| 1009 | label, |
| 1010 | }; |
| 1011 | vec![ |
| 1012 | item("profile", "/settings/profile", t(lang, Key::Profile)), |
| 1013 | item( |
| 1014 | "appearance", |
| 1015 | "/settings/appearance", |
| 1016 | mi::t(lang, MK::Appearance), |
| 1017 | ), |
| 1018 | item( |
| 1019 | "notifications", |
| 1020 | "/settings/notifications", |
| 1021 | t(lang, Key::Notifications), |
| 1022 | ), |
| 1023 | item("security", "/settings/security", t(lang, Key::Security)), |
| 1024 | item("keys", "/settings/keys", pk(lang, "Keys", "Anahtarlar")), |
| 1025 | item("export", "/settings/export", pk(lang, "Data", "Veri")), |
| 1026 | ] |
| 1027 | } |
| 1028 | |
| 1029 | |
| 1030 | |
| 1031 | |
| 1032 | pub fn section_for(lang: Lang, path: &str) -> Option<Section> { |
| 1033 | let mut parts = path.trim_matches('/').split('/'); |
| 1034 | let first = parts.next()?; |
| 1035 | let second = parts.next().unwrap_or(""); |
| 1036 | let (key, title, items) = match first { |
| 1037 | "admin" => ( |
| 1038 | "admin", |
| 1039 | ad::t(lang, AK::AdminArea).to_owned(), |
| 1040 | admin_items(lang), |
| 1041 | ), |
| 1042 | "settings" => ( |
| 1043 | "settings", |
| 1044 | o::t(lang, OK::Settings).to_owned(), |
| 1045 | settings_items(lang), |
| 1046 | ), |
| 1047 | _ => return None, |
| 1048 | }; |
| 1049 | let second = match (first, second) { |
| 1050 | (_, "sessions") => "security", |
| 1051 | (_, "gpg" | "tokens") => "keys", |
| 1052 | |
| 1053 | ("admin", "invites") => "users", |
| 1054 | ("admin", "replication") => "backups", |
| 1055 | (_, other) => other, |
| 1056 | }; |
| 1057 | let current = items |
| 1058 | .iter() |
| 1059 | .find(|item| item.key == second) |
| 1060 | .map_or("", |item| item.key); |
| 1061 | |
| 1062 | let live = if first == "settings" { |
| 1063 | "/settings/events" |
| 1064 | } else { |
| 1065 | "" |
| 1066 | }; |
| 1067 | Some(Section { |
| 1068 | key, |
| 1069 | title, |
| 1070 | items, |
| 1071 | current, |
| 1072 | live, |
| 1073 | }) |
| 1074 | } |
| 1075 | |
| 1076 | |
| 1077 | #[component] |
| 1078 | async fn section_tabs( |
| 1079 | cx: &Cx, |
| 1080 | key: &'static str, |
| 1081 | label: &str, |
| 1082 | items: Vec<NavItem>, |
| 1083 | current: &str, |
| 1084 | live: &str, |
| 1085 | ) -> Result<impl View> { |
| 1086 | let live = (!live.is_empty()).then_some(live); |
| 1087 | let links: Vec<(NavItem, bool)> = items |
| 1088 | .into_iter() |
| 1089 | .map(|item| { |
| 1090 | let on = item.key == current; |
| 1091 | (item, on) |
| 1092 | }) |
| 1093 | .collect(); |
| 1094 | Ok(view! { |
| 1095 | <nav class="tabs" aria-label=(label) data-section=(key) data-live=(live)> |
| 1096 | for (item, on) in links.into_iter() { |
| 1097 | <a href=(item.href) aria-current=(on.then_some("page"))>(item.label)</a> |
| 1098 | } |
| 1099 | </nav> |
| 1100 | }) |
| 1101 | } |
| 1102 | |
| 1103 | |
| 1104 | |
| 1105 | |
| 1106 | pub fn display_name(lang: Lang, username: &str) -> String { |
| 1107 | if forge_core::names::normalize_name(username) == forge_core::store::user_delete::GHOST_USERNAME |
| 1108 | { |
| 1109 | i18n::deleted_user(lang).to_owned() |
| 1110 | } else { |
| 1111 | username.to_owned() |
| 1112 | } |
| 1113 | } |
| 1114 | |
| 1115 | |
| 1116 | |
| 1117 | |
| 1118 | pub fn avatar_url(username: &str, hash: Option<&str>) -> String { |
| 1119 | match hash { |
| 1120 | Some(hash) => format!("/avatars/{}?v={hash}", enc(username)), |
| 1121 | None => default_data_url(username), |
| 1122 | } |
| 1123 | } |
| 1124 | |
| 1125 | |
| 1126 | |
| 1127 | pub fn avatar_url_unknown(username: &str) -> String { |
| 1128 | format!("/avatars/{}?v=default", enc(username)) |
| 1129 | } |
| 1130 | |
| 1131 | |
| 1132 | pub fn user_href(username: &str) -> String { |
| 1133 | format!("/{}", enc(username)) |
| 1134 | } |
| 1135 | |
| 1136 | |
| 1137 | |
| 1138 | |
| 1139 | #[component] |
| 1140 | pub async fn user_link(cx: &Cx, shown: &str, login: &str) -> Result<impl View> { |
| 1141 | let href = user_href(login); |
| 1142 | Ok(view! { |
| 1143 | <a href=(href.as_str())>(shown)</a> |
| 1144 | }) |
| 1145 | } |
| 1146 | |
| 1147 | |
| 1148 | #[component] |
| 1149 | pub async fn csrf_field(cx: &Cx, token: &str) -> Result<impl View> { |
| 1150 | Ok(view! { |
| 1151 | <input type="hidden" name="csrf" value=(token)> |
| 1152 | }) |
| 1153 | } |
| 1154 | |
| 1155 | |
| 1156 | #[component] |
| 1157 | pub async fn alert(cx: &Cx, message: &str) -> Result<impl View> { |
| 1158 | Ok(view! { |
| 1159 | <p class="alert" role="alert">(message)</p> |
| 1160 | }) |
| 1161 | } |
| 1162 | |
| 1163 | |
| 1164 | |
| 1165 | |
| 1166 | #[component] |
| 1167 | pub async fn empty_state( |
| 1168 | cx: &Cx, |
| 1169 | title: &str, |
| 1170 | #[default] hint: Option<&str>, |
| 1171 | #[default] child: Child<'_>, |
| 1172 | ) -> Result<impl View> { |
| 1173 | Ok(view! { |
| 1174 | <div class="sec empty-state"> |
| 1175 | <p class="state">(title)</p> |
| 1176 | if let Some(hint) = hint { |
| 1177 | <p class="hint">(hint)</p> |
| 1178 | } |
| 1179 | <div class="acts">(child)</div> |
| 1180 | </div> |
| 1181 | }) |
| 1182 | } |
| 1183 | |
| 1184 | |
| 1185 | |
| 1186 | pub fn user_facing_message(err: &CoreError) -> Option<String> { |
| 1187 | match err { |
| 1188 | CoreError::InvalidName(m) | CoreError::Invalid(m) | CoreError::Conflict(m) => { |
| 1189 | Some(m.clone()) |
| 1190 | } |
| 1191 | _ => None, |
| 1192 | } |
| 1193 | } |
| 1194 | |
| 1195 | |
| 1196 | |
| 1197 | #[layer("/")] |
| 1198 | pub async fn security_headers(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> { |
| 1199 | let headers = response_headers(cx); |
| 1200 | headers.append(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); |
| 1201 | headers.append(REFERRER_POLICY, HeaderValue::from_static("same-origin")); |
| 1202 | headers.append(X_FRAME_OPTIONS, HeaderValue::from_static("DENY")); |
| 1203 | let csp = match try_context::<AppState>(cx) { |
| 1204 | Some(state) => APP_CSP |
| 1205 | .get_or_init(|| csp_header(&state.config.user_content_base_url)) |
| 1206 | .clone(), |
| 1207 | None => HeaderValue::from_static(CSP), |
| 1208 | }; |
| 1209 | headers.append(CONTENT_SECURITY_POLICY, csp); |
| 1210 | next.run(cx, body).await |
| 1211 | } |
| 1212 | |
| 1213 | |
| 1214 | |
| 1215 | |
| 1216 | pub fn enc(s: &str) -> String { |
| 1217 | let mut out = String::with_capacity(s.len()); |
| 1218 | for b in s.bytes() { |
| 1219 | if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b'/') { |
| 1220 | out.push(char::from(b)); |
| 1221 | } else { |
| 1222 | out.push_str(&format!("%{b:02X}")); |
| 1223 | } |
| 1224 | } |
| 1225 | out |
| 1226 | } |
| 1227 | |
| 1228 | |
| 1229 | |
| 1230 | pub fn repo_href(owner: &str, repo: &str, section: &str, rest: &str) -> String { |
| 1231 | let mut href = format!("/{}/{}", enc(owner), enc(repo)); |
| 1232 | if !section.is_empty() { |
| 1233 | href.push('/'); |
| 1234 | href.push_str(section); |
| 1235 | } |
| 1236 | let rest = rest.trim_matches('/'); |
| 1237 | if !rest.is_empty() { |
| 1238 | href.push('/'); |
| 1239 | href.push_str(&enc(rest)); |
| 1240 | } |
| 1241 | href |
| 1242 | } |
| 1243 | |
| 1244 | |
| 1245 | pub fn now_unix() -> i64 { |
| 1246 | std::time::SystemTime::now() |
| 1247 | .duration_since(std::time::UNIX_EPOCH) |
| 1248 | .map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) |
| 1249 | .unwrap_or(0) |
| 1250 | } |
| 1251 | |
| 1252 | |
| 1253 | pub fn iso_time(unix: i64) -> String { |
| 1254 | let days = unix.div_euclid(86_400); |
| 1255 | let secs = unix.rem_euclid(86_400); |
| 1256 | let (y, m, d) = civil_from_days(days); |
| 1257 | format!( |
| 1258 | "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", |
| 1259 | secs / 3600, |
| 1260 | secs % 3600 / 60, |
| 1261 | secs % 60 |
| 1262 | ) |
| 1263 | } |
| 1264 | |
| 1265 | |
| 1266 | fn civil_from_days(days: i64) -> (i64, i64, i64) { |
| 1267 | let z = days + 719_468; |
| 1268 | let era = z.div_euclid(146_097); |
| 1269 | let doe = z.rem_euclid(146_097); |
| 1270 | let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; |
| 1271 | let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); |
| 1272 | let mp = (5 * doy + 2) / 153; |
| 1273 | let d = doy - (153 * mp + 2) / 5 + 1; |
| 1274 | let m = if mp < 10 { mp + 3 } else { mp - 9 }; |
| 1275 | let y = yoe + era * 400 + i64::from(m <= 2); |
| 1276 | (y, m, d) |
| 1277 | } |
| 1278 | |
| 1279 | |
| 1280 | |
| 1281 | |
| 1282 | pub fn relative_time(lang: Lang, unix: i64, now: i64) -> String { |
| 1283 | use i18n::TimeUnit; |
| 1284 | let ahead = unix > now; |
| 1285 | let secs = if ahead { |
| 1286 | unix.saturating_sub(now) |
| 1287 | } else { |
| 1288 | now.saturating_sub(unix) |
| 1289 | }; |
| 1290 | let (n, unit) = match secs { |
| 1291 | 0..60 if ahead => (1, TimeUnit::Minute), |
| 1292 | 0..60 => return i18n::just_now(lang).to_owned(), |
| 1293 | 60..3_600 => (secs / 60, TimeUnit::Minute), |
| 1294 | 3_600..86_400 => (secs / 3_600, TimeUnit::Hour), |
| 1295 | 86_400..2_592_000 => (secs / 86_400, TimeUnit::Day), |
| 1296 | 2_592_000..31_536_000 => (secs / 2_592_000, TimeUnit::Month), |
| 1297 | _ => (secs / 31_536_000, TimeUnit::Year), |
| 1298 | }; |
| 1299 | if ahead { |
| 1300 | i18n::from_now(lang, n, unit) |
| 1301 | } else { |
| 1302 | i18n::ago(lang, n, unit) |
| 1303 | } |
| 1304 | } |
| 1305 | |
| 1306 | |
| 1307 | |
| 1308 | |
| 1309 | |
| 1310 | pub fn rel_words(lang: Lang) -> String { |
| 1311 | use i18n::TimeUnit; |
| 1312 | let units = [ |
| 1313 | TimeUnit::Minute, |
| 1314 | TimeUnit::Hour, |
| 1315 | TimeUnit::Day, |
| 1316 | TimeUnit::Month, |
| 1317 | TimeUnit::Year, |
| 1318 | ]; |
| 1319 | let mut words = vec![i18n::just_now(lang).to_owned()]; |
| 1320 | for unit in units { |
| 1321 | for n in [1, 2] { |
| 1322 | words.push(i18n::ago(lang, n, unit).replacen(&n.to_string(), "{n}", 1)); |
| 1323 | } |
| 1324 | } |
| 1325 | for unit in units { |
| 1326 | for n in [1, 2] { |
| 1327 | words.push(i18n::from_now(lang, n, unit).replacen(&n.to_string(), "{n}", 1)); |
| 1328 | } |
| 1329 | } |
| 1330 | words.join("|") |
| 1331 | } |
| 1332 | |
| 1333 | |
| 1334 | |
| 1335 | #[component] |
| 1336 | pub async fn rel_time(cx: &Cx, lang: Lang, stamp: &str) -> Result<impl View> { |
| 1337 | let label = forge_core::time::stamp_to_unix(stamp) |
| 1338 | .map_or_else(String::new, |unix| relative_time(lang, unix, now_unix())); |
| 1339 | Ok(view! { |
| 1340 | <time data-rel="true" datetime=(stamp)>(label)</time> |
| 1341 | }) |
| 1342 | } |
| 1343 | |
| 1344 | |
| 1345 | #[component] |
| 1346 | pub async fn rel_time_or_never(cx: &Cx, lang: Lang, stamp: Option<&str>) -> Result<impl View> { |
| 1347 | Ok(view! { |
| 1348 | if let Some(stamp) = stamp { |
| 1349 | rel_time(lang: lang, stamp: stamp) |
| 1350 | } else { |
| 1351 | (t(lang, Key::Never)) |
| 1352 | } |
| 1353 | }) |
| 1354 | } |
| 1355 | |
| 1356 | |
| 1357 | |
| 1358 | #[component] |
| 1359 | pub async fn added_status( |
| 1360 | cx: &Cx, |
| 1361 | lang: Lang, |
| 1362 | added: Option<&str>, |
| 1363 | used: Option<&str>, |
| 1364 | ) -> Result<impl View> { |
| 1365 | let sep = if added.is_some() && used.is_some() { |
| 1366 | " · " |
| 1367 | } else { |
| 1368 | "" |
| 1369 | }; |
| 1370 | Ok(view! { |
| 1371 | if let Some(stamp) = added { |
| 1372 | (i18n::dated_label(lang, Key::Added)) " " rel_time(lang: lang, stamp: stamp) |
| 1373 | } |
| 1374 | (sep) |
| 1375 | if let Some(stamp) = used { |
| 1376 | (i18n::dated_label(lang, Key::LastUsed)) " " rel_time(lang: lang, stamp: stamp) |
| 1377 | } |
| 1378 | }) |
| 1379 | } |
| 1380 | |
| 1381 | |
| 1382 | pub fn short_oid(oid: &str) -> &str { |
| 1383 | oid.get(..7).unwrap_or(oid) |
| 1384 | } |
| 1385 | |
| 1386 | |
| 1387 | pub fn human_size(lang: Lang, bytes: u64) -> String { |
| 1388 | let decimal = |value: f64| { |
| 1389 | let text = format!("{value:.1}"); |
| 1390 | match lang { |
| 1391 | Lang::En => text, |
| 1392 | Lang::Tr => text.replace('.', ","), |
| 1393 | } |
| 1394 | }; |
| 1395 | if bytes < 1024 { |
| 1396 | match lang { |
| 1397 | Lang::En if bytes == 1 => "1 byte".to_owned(), |
| 1398 | Lang::En => format!("{bytes} bytes"), |
| 1399 | Lang::Tr => format!("{bytes} bayt"), |
| 1400 | } |
| 1401 | } else if bytes < 1024 * 1024 { |
| 1402 | format!("{} KiB", decimal(bytes as f64 / 1024.0)) |
| 1403 | } else if bytes < 1024 * 1024 * 1024 { |
| 1404 | format!("{} MiB", decimal(bytes as f64 / (1024.0 * 1024.0))) |
| 1405 | } else if bytes < 1024 * 1024 * 1024 * 1024 { |
| 1406 | format!("{} GiB", decimal(bytes as f64 / (1024.0 * 1024.0 * 1024.0))) |
| 1407 | } else { |
| 1408 | format!( |
| 1409 | "{} TiB", |
| 1410 | decimal(bytes as f64 / (1024.0 * 1024.0 * 1024.0 * 1024.0)) |
| 1411 | ) |
| 1412 | } |
| 1413 | } |
| 1414 | |
| 1415 | fn tab_class(on: bool) -> &'static str { |
| 1416 | if on { "tab active" } else { "tab" } |
| 1417 | } |
| 1418 | |
| 1419 | fn tab_more_class(on: bool) -> &'static str { |
| 1420 | if on { |
| 1421 | "tab-more-link is-current" |
| 1422 | } else { |
| 1423 | "tab-more-link" |
| 1424 | } |
| 1425 | } |
| 1426 | |
| 1427 | |
| 1428 | |
| 1429 | |
| 1430 | |
| 1431 | #[component] |
| 1432 | pub async fn repo_tabs( |
| 1433 | cx: &Cx, |
| 1434 | owner: String, |
| 1435 | repo: String, |
| 1436 | default_branch: String, |
| 1437 | active: String, |
| 1438 | can_admin: bool, |
| 1439 | lang: Lang, |
| 1440 | #[default] open_issues: Option<u64>, |
| 1441 | #[default] open_pulls: Option<u64>, |
| 1442 | #[default] discussions: bool, |
| 1443 | #[default] wiki: bool, |
| 1444 | #[default] security: bool, |
| 1445 | ) -> Result<impl View> { |
| 1446 | let home = repo_href(&owner, &repo, "", ""); |
| 1447 | let issues = repo_href(&owner, &repo, "issues", ""); |
| 1448 | let issues_count = open_issues.filter(|n| *n > 0).map(|n| n.to_string()); |
| 1449 | let pulls = repo_href(&owner, &repo, "pulls", ""); |
| 1450 | let pulls_count = open_pulls.filter(|n| *n > 0).map(|n| n.to_string()); |
| 1451 | let pulls_on = active == "pulls"; |
| 1452 | let commits = repo_href(&owner, &repo, "commits", &default_branch); |
| 1453 | let branches = repo_href(&owner, &repo, "branches", ""); |
| 1454 | let tags = repo_href(&owner, &repo, "tags", ""); |
| 1455 | let releases = repo_href(&owner, &repo, "releases", ""); |
| 1456 | let ci = repo_href(&owner, &repo, "ci", ""); |
| 1457 | let ci_on = active == "ci"; |
| 1458 | |
| 1459 | let more_on = matches!( |
| 1460 | active.as_str(), |
| 1461 | "commits" | "branches" | "tags" | "releases" |
| 1462 | ); |
| 1463 | let code_on = active == "code" || more_on; |
| 1464 | let issues_on = active == "issues"; |
| 1465 | let commits_on = active == "commits"; |
| 1466 | let branches_on = active == "branches"; |
| 1467 | let tags_on = active == "tags"; |
| 1468 | let releases_on = active == "releases"; |
| 1469 | |
| 1470 | let settings = repo_href(&owner, &repo, "settings", ""); |
| 1471 | let settings_on = active == "settings"; |
| 1472 | let discussions_tab = repo_href(&owner, &repo, "discussions", ""); |
| 1473 | let discussions_on = active == "discussions"; |
| 1474 | let wiki_tab = repo_href(&owner, &repo, "wiki", ""); |
| 1475 | let wiki_on = active == "wiki"; |
| 1476 | let security_tab = repo_href(&owner, &repo, "security", ""); |
| 1477 | let security_on = active == "security"; |
| 1478 | Ok(view! { |
| 1479 | <nav class="repo-tabs" aria-label=(g::t(lang, K::RepositoryNav))> |
| 1480 | <a class=(tab_class(code_on)) href=(home)> |
| 1481 | (t(lang, Key::Code)) |
| 1482 | </a> |
| 1483 | <details class="menu tab-more"> |
| 1484 | <summary class="tab tab-more-toggle" aria-label=(s(lang, "More code pages", "Diğer kod sayfaları"))> |
| 1485 | <svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg> |
| 1486 | </summary> |
| 1487 | <div class="tab-more-list"> |
| 1488 | <a class=(tab_more_class(commits_on)) href=(commits)>(g::t(lang, K::TabCommits))</a> |
| 1489 | <a class=(tab_more_class(branches_on)) href=(branches)>(g::t(lang, K::BranchesTitle))</a> |
| 1490 | <a class=(tab_more_class(tags_on)) href=(tags)>(g::t(lang, K::TagsTitle))</a> |
| 1491 | <a class=(tab_more_class(releases_on)) href=(releases)>(g::t(lang, K::TabReleases))</a> |
| 1492 | </div> |
| 1493 | </details> |
| 1494 | <a class=(tab_class(issues_on)) href=(issues)> |
| 1495 | (g::t(lang, K::TabIssues)) |
| 1496 | if let Some(count) = issues_count { |
| 1497 | " " <span class="tab-count" data-arrive=(count.as_str())>(count.as_str())</span> |
| 1498 | } |
| 1499 | </a> |
| 1500 | <a class=(tab_class(pulls_on)) href=(pulls)> |
| 1501 | (g::t(lang, K::TabPulls)) |
| 1502 | if let Some(count) = pulls_count { |
| 1503 | " " <span class="tab-count" data-arrive=(count.as_str())>(count.as_str())</span> |
| 1504 | } |
| 1505 | </a> |
| 1506 | <a class=(tab_class(ci_on)) href=(ci)> |
| 1507 | (g::t(lang, K::TabCi)) |
| 1508 | </a> |
| 1509 | if discussions { |
| 1510 | <a class=(tab_class(discussions_on)) href=(discussions_tab)> |
| 1511 | (g::t(lang, K::TabDiscussions)) |
| 1512 | </a> |
| 1513 | } |
| 1514 | if wiki { |
| 1515 | <a class=(tab_class(wiki_on)) href=(wiki_tab)> |
| 1516 | (g::t(lang, K::TabWiki)) |
| 1517 | </a> |
| 1518 | } |
| 1519 | if security { |
| 1520 | <a class=(tab_class(security_on)) href=(security_tab)> |
| 1521 | (t(lang, Key::Security)) |
| 1522 | </a> |
| 1523 | } |
| 1524 | if can_admin { |
| 1525 | <a class=(tab_class(settings_on)) href=(settings)> |
| 1526 | (g::t(lang, K::TabSettings)) |
| 1527 | </a> |
| 1528 | } |
| 1529 | </nav> |
| 1530 | } |
| 1531 | .boxed()) |
| 1532 | } |
| 1533 | |
| 1534 | |
| 1535 | |
| 1536 | #[derive(Clone)] |
| 1537 | pub struct RefLink { |
| 1538 | pub name: String, |
| 1539 | pub href: String, |
| 1540 | pub current: bool, |
| 1541 | pub default: bool, |
| 1542 | pub updated: i64, |
| 1543 | } |
| 1544 | |
| 1545 | |
| 1546 | |
| 1547 | pub const REF_SHOWN: usize = 8; |
| 1548 | |
| 1549 | const BRANCH_ICON: &str = r#"<svg viewBox="0 0 24 24"><circle cx="6" cy="5" r="2"/><circle cx="6" cy="19" r="2"/><circle cx="18" cy="6" r="2"/><path d="M6 7v10M18 8c0 4-6 4-12 9"/></svg>"#; |
| 1550 | const TAG_ICON: &str = r#"<svg viewBox="0 0 24 24"><path d="M20.6 13.4 13.4 20.6a2 2 0 0 1-2.8 0L3 13V3h10l7.6 7.6a2 2 0 0 1 0 2.8z"/><circle cx="7.5" cy="7.5" r="1.5"/></svg>"#; |
| 1551 | |
| 1552 | |
| 1553 | |
| 1554 | #[component] |
| 1555 | async fn ref_group( |
| 1556 | cx: &Cx, |
| 1557 | lang: Lang, |
| 1558 | kind: &'static str, |
| 1559 | heading: &'static str, |
| 1560 | links: Vec<RefLink>, |
| 1561 | now: i64, |
| 1562 | ) -> Result<impl View> { |
| 1563 | let count = links.len(); |
| 1564 | let icon = if kind == "tags" { |
| 1565 | TAG_ICON |
| 1566 | } else { |
| 1567 | BRANCH_ICON |
| 1568 | }; |
| 1569 | let head_id = format!("ref-head-{kind}"); |
| 1570 | Ok(view! { |
| 1571 | if count > 0 { |
| 1572 | <div class="ref-group" data-ref-group=""> |
| 1573 | <div class="ref-head" id=(head_id.as_str())> |
| 1574 | <span>(heading)</span> |
| 1575 | <span class="ref-count">(count)</span> |
| 1576 | </div> |
| 1577 | <ul class="ref-list" role="group" aria-labelledby=(head_id.as_str())> |
| 1578 | for (n, link) in links.into_iter().enumerate() { |
| 1579 | <li role="option" id=(format!("ref-{kind}-{n}")) data-ref-item="" |
| 1580 | data-ref-name=(link.name.as_str()) aria-current=(link.current.then_some("true")) |
| 1581 | hidden=((n >= REF_SHOWN).then_some(""))> |
| 1582 | <a href=(link.href)> |
| 1583 | <span class="ref-kind" aria-hidden="true">(Unescaped::new_unchecked(icon))</span> |
| 1584 | <span class="ref-text">(link.name.as_str())</span> |
| 1585 | if link.default { |
| 1586 | <span class="ref-chip">(g::t(lang, K::DefaultBadge))</span> |
| 1587 | } |
| 1588 | <span class="ref-age">(relative_time(lang, link.updated, now))</span> |
| 1589 | </a> |
| 1590 | </li> |
| 1591 | } |
| 1592 | </ul> |
| 1593 | </div> |
| 1594 | } |
| 1595 | }) |
| 1596 | } |
| 1597 | |
| 1598 | |
| 1599 | |
| 1600 | |
| 1601 | |
| 1602 | |
| 1603 | #[component] |
| 1604 | pub async fn ref_selector( |
| 1605 | cx: &Cx, |
| 1606 | lang: Lang, |
| 1607 | label: &'static str, |
| 1608 | current: String, |
| 1609 | branches: Vec<RefLink>, |
| 1610 | tags: Vec<RefLink>, |
| 1611 | branches_href: String, |
| 1612 | tags_href: String, |
| 1613 | ) -> Result<impl View> { |
| 1614 | |
| 1615 | let is_tag = !branches.iter().any(|b| b.current) && tags.iter().any(|t| t.current); |
| 1616 | let none = branches.is_empty() && tags.is_empty(); |
| 1617 | let now = now_unix(); |
| 1618 | Ok(view! { |
| 1619 | <details class="ref-select" data-ref-switch=""> |
| 1620 | <summary title=(label) aria-label=(format!("{label}: {current}"))> |
| 1621 | <span class="ref-icon" aria-hidden="true">(Unescaped::new_unchecked(if is_tag { TAG_ICON } else { BRANCH_ICON }))</span> |
| 1622 | <code class="ref-name">(current.as_str())</code> |
| 1623 | <span class="ref-caret" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></svg></span> |
| 1624 | </summary> |
| 1625 | <div class="ref-menu"> |
| 1626 | <label class="ref-search"> |
| 1627 | <svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg> |
| 1628 | <input type="text" class="ref-filter" data-ref-filter="" autocomplete="off" spellcheck="false" |
| 1629 | placeholder=(g::t(lang, K::FilterRefs)) aria-label=(g::t(lang, K::FilterRefs)) |
| 1630 | role="combobox" aria-expanded="true" aria-autocomplete="list" aria-controls="ref-results"> |
| 1631 | </label> |
| 1632 | <div class="ref-results" id="ref-results" role="listbox"> |
| 1633 | ref_group(lang: lang, kind: "branches", heading: g::t(lang, K::BranchesTitle), links: branches, now: now) |
| 1634 | ref_group(lang: lang, kind: "tags", heading: g::t(lang, K::TagsTitle), links: tags, now: now) |
| 1635 | <p class="muted small ref-note" data-ref-empty="" hidden=(!none)> |
| 1636 | (g::t(lang, if none { K::NothingHere } else { K::NoMatches })) |
| 1637 | </p> |
| 1638 | </div> |
| 1639 | <div class="ref-foot"> |
| 1640 | <a href=(branches_href) title=(g::t(lang, K::ViewAllBranches))>(g::t(lang, K::ViewAllBranches))</a> |
| 1641 | <a href=(tags_href) title=(g::t(lang, K::ViewAllTags))>(g::t(lang, K::ViewAllTags))</a> |
| 1642 | </div> |
| 1643 | </div> |
| 1644 | </details> |
| 1645 | }) |
| 1646 | } |
| 1647 | |
| 1648 | |
| 1649 | #[derive(Clone)] |
| 1650 | pub struct When { |
| 1651 | pub iso: String, |
| 1652 | pub absolute: String, |
| 1653 | pub relative: String, |
| 1654 | } |
| 1655 | |
| 1656 | impl When { |
| 1657 | pub fn new(lang: Lang, stamp: &str, tz: &str, now: i64) -> Self { |
| 1658 | let unix = stamp_unix(stamp); |
| 1659 | Self { |
| 1660 | iso: iso_time(unix), |
| 1661 | absolute: forge_core::tz::format_in_tz(unix, tz), |
| 1662 | relative: relative_time(lang, unix, now), |
| 1663 | } |
| 1664 | } |
| 1665 | } |
| 1666 | |
| 1667 | |
| 1668 | pub fn stamp_unix(stamp: &str) -> i64 { |
| 1669 | let field = |range: std::ops::Range<usize>| { |
| 1670 | stamp |
| 1671 | .get(range) |
| 1672 | .and_then(|digits| digits.parse::<i64>().ok()) |
| 1673 | }; |
| 1674 | let (Some(y), Some(mo), Some(d), Some(h), Some(mi), Some(s)) = ( |
| 1675 | field(0..4), |
| 1676 | field(5..7), |
| 1677 | field(8..10), |
| 1678 | field(11..13), |
| 1679 | field(14..16), |
| 1680 | field(17..19), |
| 1681 | ) else { |
| 1682 | return 0; |
| 1683 | }; |
| 1684 | days_from_civil(y, mo, d) * 86_400 + h * 3_600 + mi * 60 + s |
| 1685 | } |
| 1686 | |
| 1687 | |
| 1688 | fn days_from_civil(year: i64, month: i64, day: i64) -> i64 { |
| 1689 | let y = if month <= 2 { year - 1 } else { year }; |
| 1690 | let era = y.div_euclid(400); |
| 1691 | let yoe = y - era * 400; |
| 1692 | let mp = (month + 9) % 12; |
| 1693 | let doy = (153 * mp + 2) / 5 + day - 1; |
| 1694 | let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; |
| 1695 | era * 146_097 + doe - 719_468 |
| 1696 | } |
| 1697 | |
| 1698 | |
| 1699 | pub fn url_path(path: &str) -> String { |
| 1700 | let mut out = String::with_capacity(path.len()); |
| 1701 | for b in path.bytes() { |
| 1702 | match b { |
| 1703 | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => { |
| 1704 | out.push(char::from(b)); |
| 1705 | } |
| 1706 | _ => out.push_str(&format!("%{b:02X}")), |
| 1707 | } |
| 1708 | } |
| 1709 | out |
| 1710 | } |
| 1711 | |
| 1712 | |
| 1713 | static HIGHLIGHT_CSS: OnceLock<String> = OnceLock::new(); |
| 1714 | |
| 1715 | |
| 1716 | pub fn highlight_css_text() -> &'static str { |
| 1717 | HIGHLIGHT_CSS.get_or_init(highlight_css).as_str() |
| 1718 | } |
| 1719 | |
| 1720 | |
| 1721 | |
| 1722 | |
| 1723 | pub const PALETTE: [&str; 8] = [ |
| 1724 | "#5E7D63", "#4A6750", "#3F5F46", "#4E6E68", "#3E6B63", "#5B6B4E", "#56705F", "#4F6A55", |
| 1725 | ]; |
| 1726 | |
| 1727 | |
| 1728 | |
| 1729 | pub fn default_svg(username: &str) -> String { |
| 1730 | let digest = Sha256::digest(username.as_bytes()); |
| 1731 | let color = PALETTE[usize::from(digest[0]) % PALETTE.len()]; |
| 1732 | let letter = username |
| 1733 | .chars() |
| 1734 | .next() |
| 1735 | .map_or_else(|| "?".to_owned(), |c| c.to_uppercase().collect()); |
| 1736 | let letter = xml_escape(&letter); |
| 1737 | format!( |
| 1738 | r##"<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256"><rect width="256" height="256" fill="{color}"/><text x="128" y="128" dy="0.35em" text-anchor="middle" font-family="sans-serif" font-size="128" fill="#ffffff">{letter}</text></svg>"## |
| 1739 | ) |
| 1740 | } |
| 1741 | |
| 1742 | |
| 1743 | |
| 1744 | pub fn default_data_url(username: &str) -> String { |
| 1745 | let svg = default_svg(username); |
| 1746 | let mut out = String::with_capacity(svg.len() + 40); |
| 1747 | out.push_str("data:image/svg+xml,"); |
| 1748 | for byte in svg.bytes() { |
| 1749 | if byte.is_ascii_alphanumeric() || b" -_.~/=:;,'()".contains(&byte) { |
| 1750 | out.push(char::from(byte)); |
| 1751 | } else { |
| 1752 | out.push_str(&format!("%{byte:02X}")); |
| 1753 | } |
| 1754 | } |
| 1755 | out |
| 1756 | } |
| 1757 | |
| 1758 | fn xml_escape(text: &str) -> String { |
| 1759 | let mut out = String::with_capacity(text.len()); |
| 1760 | for c in text.chars() { |
| 1761 | match c { |
| 1762 | '&' => out.push_str("&"), |
| 1763 | '<' => out.push_str("<"), |
| 1764 | '>' => out.push_str(">"), |
| 1765 | '"' => out.push_str("""), |
| 1766 | '\'' => out.push_str("'"), |
| 1767 | other => out.push(other), |
| 1768 | } |
| 1769 | } |
| 1770 | out |
| 1771 | } |
| 1772 | |
| 1773 | |
| 1774 | pub const BANNER_COOKIE: &str = "forge_banner"; |
| 1775 | |
| 1776 | |
| 1777 | pub const BANNER_PREF: &str = "banner_dismissed"; |
| 1778 | |
| 1779 | |
| 1780 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1781 | pub struct BannerView { |
| 1782 | pub message: String, |
| 1783 | pub warning: bool, |
| 1784 | pub hash: String, |
| 1785 | |
| 1786 | pub expires: Option<i64>, |
| 1787 | } |
| 1788 | |
| 1789 | |
| 1790 | pub fn banner_hash(message: &str, level: &str) -> String { |
| 1791 | hash_token(&format!("{level}\n{message}"))[..16].to_owned() |
| 1792 | } |
| 1793 | |
| 1794 | |
| 1795 | |
| 1796 | pub fn view_for(config: &BannerConfig, now: i64, dismissed: Option<&str>) -> Option<BannerView> { |
| 1797 | if !config.active_at(now) { |
| 1798 | return None; |
| 1799 | } |
| 1800 | let message = config.message.trim().to_owned(); |
| 1801 | let hash = banner_hash(&message, &config.level); |
| 1802 | if dismissed == Some(hash.as_str()) { |
| 1803 | return None; |
| 1804 | } |
| 1805 | Some(BannerView { |
| 1806 | message, |
| 1807 | warning: config.level == "warning", |
| 1808 | hash, |
| 1809 | expires: config.expires_unix(), |
| 1810 | }) |
| 1811 | } |
| 1812 | |
| 1813 | |
| 1814 | |
| 1815 | pub fn current_banner(cx: &Cx, prefs: Option<&HashMap<String, String>>) -> Option<BannerView> { |
| 1816 | let state = try_context::<AppState>(cx)?; |
| 1817 | let live = state.live(); |
| 1818 | if live.banner.message.trim().is_empty() { |
| 1819 | return None; |
| 1820 | } |
| 1821 | let dismissed = match prefs { |
| 1822 | Some(prefs) => prefs.get(BANNER_PREF).cloned(), |
| 1823 | None => cookies(cx).get(BANNER_COOKIE).map(|c| c.value().to_owned()), |
| 1824 | }; |
| 1825 | view_for(&live.banner, now_unix(), dismissed.as_deref()) |
| 1826 | } |
| 1827 | |
| 1828 | |
| 1829 | pub fn tab_title(lang: Lang, active: &str, repo: &str) -> String { |
| 1830 | match active { |
| 1831 | "issues" => g::t(lang, K::TabIssues).to_owned(), |
| 1832 | "pulls" => g::t(lang, K::TabPulls).to_owned(), |
| 1833 | "ci" => g::t(lang, K::TabCi).to_owned(), |
| 1834 | "commits" => g::t(lang, K::TabCommits).to_owned(), |
| 1835 | "branches" => g::t(lang, K::BranchesTitle).to_owned(), |
| 1836 | "tags" => g::t(lang, K::TagsTitle).to_owned(), |
| 1837 | "releases" => g::t(lang, K::TabReleases).to_owned(), |
| 1838 | "discussions" => g::t(lang, K::TabDiscussions).to_owned(), |
| 1839 | "wiki" => g::t(lang, K::TabWiki).to_owned(), |
| 1840 | "security" => i18n::t(lang, i18n::Key::Security).to_owned(), |
| 1841 | "settings" => g::t(lang, K::TabSettings).to_owned(), |
| 1842 | _ => repo.to_owned(), |
| 1843 | } |
| 1844 | } |
| 1845 | |
| 1846 | |
| 1847 | pub fn sound_attr(prefs: Option<&HashMap<String, String>>) -> Option<&'static str> { |
| 1848 | let stored = prefs.and_then(|p| p.get(SOUND))?; |
| 1849 | (stored == "on").then_some("on") |
| 1850 | } |
| 1851 | |
| 1852 | |
| 1853 | pub fn bytes_text(bytes: u64) -> String { |
| 1854 | let gib = bytes as f64 / (1u64 << 30) as f64; |
| 1855 | format!("{gib:.1} GiB") |
| 1856 | } |
| 1857 | |
| 1858 | |
| 1859 | pub fn https_clone_url(config: &Config, owner: &str, name: &str) -> String { |
| 1860 | format!( |
| 1861 | "{}/{owner}/{name}.git", |
| 1862 | config.base_url.trim_end_matches('/') |
| 1863 | ) |
| 1864 | } |
| 1865 | |
| 1866 | |
| 1867 | pub fn ssh_clone_url(config: &Config, owner: &str, name: &str) -> String { |
| 1868 | let host = &config.ssh_public_host; |
| 1869 | if config.ssh_public_port == 22 { |
| 1870 | format!("git@{host}:{owner}/{name}.git") |
| 1871 | } else { |
| 1872 | format!( |
| 1873 | "ssh://git@{host}:{}/{owner}/{name}.git", |
| 1874 | config.ssh_public_port |
| 1875 | ) |
| 1876 | } |
| 1877 | } |
| 1878 | |
| 1879 | #[cfg(test)] |
| 1880 | mod tests { |
| 1881 | use super::*; |
| 1882 | |
| 1883 | #[test] |
| 1884 | fn enc_keeps_slashes_and_escapes_the_rest() { |
| 1885 | assert_eq!(enc("feature/x y#1"), "feature/x%20y%231"); |
| 1886 | assert_eq!(enc("a~b.c_d-e"), "a~b.c_d-e"); |
| 1887 | } |
| 1888 | |
| 1889 | #[test] |
| 1890 | fn live_strip_is_one_pill_for_one_run_and_a_summary_for_more() { |
| 1891 | let run = |state, number| ActorRun { |
| 1892 | owner: "tahinli".into(), |
| 1893 | repo: "proj".into(), |
| 1894 | number, |
| 1895 | git_ref: "main".into(), |
| 1896 | state, |
| 1897 | created_at: String::new(), |
| 1898 | finished_at: None, |
| 1899 | jobs_total: 0, |
| 1900 | jobs_done: 0, |
| 1901 | current_job: None, |
| 1902 | }; |
| 1903 | let many = ActorRuns { |
| 1904 | running: vec![run(RunState::Running, 3)], |
| 1905 | finished: vec![run(RunState::Failure, 2), run(RunState::Cancelled, 1)], |
| 1906 | failing: 0, |
| 1907 | newest_failing: None, |
| 1908 | }; |
| 1909 | let strip = live_strip(Lang::En, &many); |
| 1910 | assert_eq!(strip.runs.len(), 3); |
| 1911 | assert_eq!(strip.summary, "1 running · 1 failed · 1 cancelled"); |
| 1912 | assert_eq!(strip.summary_class, "pill hot"); |
| 1913 | let alone = ActorRuns { |
| 1914 | running: Vec::new(), |
| 1915 | finished: vec![run(RunState::Cancelled, 1)], |
| 1916 | failing: 0, |
| 1917 | newest_failing: None, |
| 1918 | }; |
| 1919 | let one = live_strip(Lang::En, &alone); |
| 1920 | assert_eq!(one.runs.len(), 1); |
| 1921 | assert_eq!(one.runs[0].pill_class, "pill off"); |
| 1922 | assert_eq!(one.runs[0].text, " cancelled"); |
| 1923 | } |
| 1924 | |
| 1925 | #[test] |
| 1926 | fn repo_href_builds_each_form() { |
| 1927 | assert_eq!(repo_href("tahinli", "demo", "", ""), "/tahinli/demo"); |
| 1928 | assert_eq!( |
| 1929 | repo_href("tahinli", "demo", "tree", "feature/x/src"), |
| 1930 | "/tahinli/demo/tree/feature/x/src" |
| 1931 | ); |
| 1932 | assert_eq!( |
| 1933 | repo_href("tahinli", "demo", "tree", "main/"), |
| 1934 | "/tahinli/demo/tree/main" |
| 1935 | ); |
| 1936 | } |
| 1937 | |
| 1938 | #[test] |
| 1939 | fn path_segments_follow_the_request_path() { |
| 1940 | assert_eq!( |
| 1941 | path_segments(Lang::En, "/tahinli/forge/blob/main/src/main.rs", "main.rs"), |
| 1942 | vec![ |
| 1943 | ("tahinli".to_owned(), Some("/tahinli".to_owned())), |
| 1944 | ("forge".to_owned(), Some("/tahinli/forge".to_owned())), |
| 1945 | ( |
| 1946 | "src".to_owned(), |
| 1947 | Some("/tahinli/forge/tree/main/src".to_owned()) |
| 1948 | ), |
| 1949 | ("main.rs".to_owned(), None), |
| 1950 | ] |
| 1951 | ); |
| 1952 | assert_eq!( |
| 1953 | path_segments(Lang::En, "/tahinli/forge", "tahinli/forge"), |
| 1954 | vec![ |
| 1955 | ("tahinli".to_owned(), Some("/tahinli".to_owned())), |
| 1956 | ("forge".to_owned(), None), |
| 1957 | ] |
| 1958 | ); |
| 1959 | let (last, _) = |
| 1960 | path_segments(Lang::En, "/tahinli/forge/issues", "tahinli/forge · Issues").remove(2); |
| 1961 | assert_eq!(last, "Issues"); |
| 1962 | let crumbs = path_segments(Lang::En, "/tahinli/forge/commits/main", "tahinli/forge"); |
| 1963 | assert_eq!( |
| 1964 | crumbs[2], |
| 1965 | ( |
| 1966 | "Commits".to_owned(), |
| 1967 | Some("/tahinli/forge/commits".to_owned()) |
| 1968 | ) |
| 1969 | ); |
| 1970 | assert_eq!(crumbs[3], ("main".to_owned(), None)); |
| 1971 | let crumbs = path_segments(Lang::En, "/tahinli/forge/issues/4/edit", "tahinli/forge"); |
| 1972 | let labels: Vec<&str> = crumbs.iter().map(|(label, _)| label.as_str()).collect(); |
| 1973 | assert_eq!(labels, ["tahinli", "forge", "Issues", "#4", "Edit"]); |
| 1974 | assert_eq!(crumbs[3].1.as_deref(), Some("/tahinli/forge/issues/4")); |
| 1975 | assert!(path_segments(Lang::En, "/explore", "Explore").is_empty()); |
| 1976 | assert!(path_segments(Lang::En, "/", "Home").is_empty()); |
| 1977 | let (last, _) = path_segments( |
| 1978 | Lang::En, |
| 1979 | "/tahinli/forge/commit/0123456789abcdef0123456789abcdef01234567", |
| 1980 | "tahinli/forge", |
| 1981 | ) |
| 1982 | .remove(3); |
| 1983 | assert_eq!(last, "0123456"); |
| 1984 | } |
| 1985 | |
| 1986 | #[test] |
| 1987 | fn csp_allows_the_raw_origin_for_images_and_falls_back_otherwise() { |
| 1988 | let origin = origin_of("https://raw.forge.test:8443/some/path/"); |
| 1989 | assert_eq!(origin.as_deref(), Some("https://raw.forge.test:8443")); |
| 1990 | let csp = csp_for(origin.as_deref()); |
| 1991 | assert!(csp.contains("img-src 'self' data: https://raw.forge.test:8443;")); |
| 1992 | assert!(csp.contains("form-action 'self'; frame-ancestors 'none'")); |
| 1993 | |
| 1994 | assert_eq!(origin_of("not a url"), None); |
| 1995 | assert_eq!(origin_of("ftp://files.test"), None); |
| 1996 | assert_eq!(origin_of("https://user:pw@files.test"), None); |
| 1997 | assert_eq!(csp_for(None), CSP); |
| 1998 | } |
| 1999 | |
| 2000 | #[test] |
| 2001 | fn iso_time_matches_known_instants() { |
| 2002 | assert_eq!(iso_time(0), "1970-01-01T00:00:00Z"); |
| 2003 | assert_eq!(iso_time(1_700_000_000), "2023-11-14T22:13:20Z"); |
| 2004 | assert_eq!(iso_time(951_782_400), "2000-02-29T00:00:00Z"); |
| 2005 | } |
| 2006 | |
| 2007 | #[test] |
| 2008 | fn relative_time_picks_the_unit() { |
| 2009 | assert_eq!(relative_time(Lang::En, 100, 110), "just now"); |
| 2010 | assert_eq!(relative_time(Lang::En, 0, 120), "2 minutes ago"); |
| 2011 | assert_eq!(relative_time(Lang::En, 0, 3_600), "1 hour ago"); |
| 2012 | assert_eq!(relative_time(Lang::En, 0, 2 * 86_400), "2 days ago"); |
| 2013 | assert_eq!(relative_time(Lang::En, 0, 10), "just now"); |
| 2014 | assert_eq!(relative_time(Lang::En, 0, 30 * 86_400), "1 month ago"); |
| 2015 | assert_eq!(relative_time(Lang::En, 0, 365 * 86_400), "1 year ago"); |
| 2016 | assert_eq!(relative_time(Lang::En, 0, 2 * 365 * 86_400), "2 years ago"); |
| 2017 | assert_eq!(relative_time(Lang::Tr, 100, 110), "az önce"); |
| 2018 | assert_eq!(relative_time(Lang::Tr, 0, 60), "1 dakika önce"); |
| 2019 | assert_eq!(relative_time(Lang::Tr, 0, 5 * 60), "5 dakika önce"); |
| 2020 | assert_eq!(relative_time(Lang::Tr, 0, 3 * 3_600), "3 saat önce"); |
| 2021 | assert_eq!(relative_time(Lang::Tr, 0, 3 * 86_400), "3 gün önce"); |
| 2022 | assert_eq!(relative_time(Lang::Tr, 0, 2 * 2_592_000), "2 ay önce"); |
| 2023 | assert_eq!(relative_time(Lang::Tr, 0, 365 * 86_400), "1 yıl önce"); |
| 2024 | |
| 2025 | assert_eq!( |
| 2026 | rel_words(Lang::En), |
| 2027 | "just now|{n} minute ago|{n} minutes ago|{n} hour ago|{n} hours ago|{n} day ago|\ |
| 2028 | {n} days ago|{n} month ago|{n} months ago|{n} year ago|{n} years ago|\ |
| 2029 | in {n} minute|in {n} minutes|in {n} hour|in {n} hours|in {n} day|in {n} days|\ |
| 2030 | in {n} month|in {n} months|in {n} year|in {n} years" |
| 2031 | ); |
| 2032 | assert_eq!(rel_words(Lang::Tr).split('|').nth(4), Some("{n} saat önce")); |
| 2033 | } |
| 2034 | |
| 2035 | #[test] |
| 2036 | fn short_oid_and_sizes() { |
| 2037 | assert_eq!(short_oid("0123456789abcdef"), "0123456"); |
| 2038 | assert_eq!(human_size(Lang::En, 12), "12 bytes"); |
| 2039 | assert_eq!(human_size(Lang::En, 2048), "2.0 KiB"); |
| 2040 | assert_eq!(human_size(Lang::En, 1_572_864), "1.5 MiB"); |
| 2041 | assert_eq!(human_size(Lang::Tr, 512), "512 bayt"); |
| 2042 | assert_eq!(human_size(Lang::Tr, 2048), "2,0 KiB"); |
| 2043 | assert_eq!(human_size(Lang::Tr, 1_572_864), "1,5 MiB"); |
| 2044 | } |
| 2045 | |
| 2046 | #[test] |
| 2047 | fn ghost_and_visibility_labels_follow_the_language() { |
| 2048 | assert_eq!(i18n::deleted_user(Lang::En), "Deleted user"); |
| 2049 | assert_eq!(i18n::deleted_user(Lang::Tr), "Silinmiş kullanıcı"); |
| 2050 | assert_eq!( |
| 2051 | i18n::visibility_label(Lang::Tr, forge_core::Visibility::Public), |
| 2052 | "Herkese açık" |
| 2053 | ); |
| 2054 | assert_eq!( |
| 2055 | i18n::visibility_label(Lang::En, forge_core::Visibility::Private), |
| 2056 | "Private" |
| 2057 | ); |
| 2058 | } |
| 2059 | } |