Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.
Rust downloadmanagerguihacktoberfesthomebrewlightweightlinuxlinux-distributionlocal-firstmacosmacos-packagemedia-toolboxopen-sourcerustsveltetauritrendingtrending-repositorieswindowswindows-desktopytdlp
feat(league): statistical match model, live economy and configurable role goals
tonhowtf5da47980be82
diff --git a/src-tauri/src/commands/league.rs b/src-tauri/src/commands/league/mod.rssimilarity index 71%rename from src-tauri/src/commands/league.rsrename to src-tauri/src/commands/league/mod.rsindex 19874d89..3eb4bb47 100644--- a/src-tauri/src/commands/league.rs+++ b/src-tauri/src/commands/league/mod.rs@@ -1,3 +1,5 @@+pub mod stats;+use once_cell::sync::Lazy;use serde::Serialize;use serde_json::{json, Value};@@ -777,6 +779,359 @@ pub async fn league_player_report(puuid: String) -> Result<Value, String> {}))}+/// Extracts rank plus, when trustworthy, the season win/loss record.+///+/// For anyone other than the local player the client reports `losses = 0` and a+/// career-long `wins` total, so a non-zero win count with zero losses is treated+/// as "hidden" instead of a perfect record.+fn ranked_entry_parts(entry: &Value) -> (Option<f64>, u32, u32) {+ let tier = entry.get("tier").and_then(Value::as_str).unwrap_or("");+ let division = entry.get("division").and_then(Value::as_str).unwrap_or("");+ let lp = entry+ .get("leaguePoints")+ .and_then(Value::as_i64)+ .unwrap_or(0)+ .max(0) as u32;+ let wins = entry.get("wins").and_then(Value::as_i64).unwrap_or(0).max(0) as u32;+ let losses = entry+ .get("losses")+ .and_then(Value::as_i64)+ .unwrap_or(0)+ .max(0) as u32;+ let rank = stats::rank_rating(tier, division, lp);+ if losses == 0 && wins > 0 {+ return (rank, 0, 0);+ }+ (rank, wins, losses)+}++/// Full pre-game analysis: per-player strength, team win probability and the+/// premade groups inferred from overlapping match histories.+#[tauri::command]+pub async fn league_match_analysis() -> Result<Value, String> {+ ensure_enabled()?;+ let client = get_client().await?;+ let roster = league_game_players().await?;+ let players: Vec<Value> = roster+ .get("players")+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ if players.is_empty() {+ return Err("no players in the current game".to_string());+ }++ let mut tasks = Vec::new();+ for (index, player) in players.iter().enumerate() {+ let puuid = player+ .get("puuid")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string();+ let task_client = client.clone();+ tasks.push(tauri::async_runtime::spawn(async move {+ if puuid.is_empty() {+ return (index, Value::Null, Vec::new());+ }+ let ranked = lcu_get_raw(+ &task_client,+ &format!("/lol-ranked/v1/ranked-stats/{}", puuid),+ )+ .await+ .unwrap_or(Value::Null);+ let history = lcu_get_raw(+ &task_client,+ &format!(+ "/lol-match-history/v1/products/lol/{}/matches?begIndex=0&endIndex=19",+ puuid+ ),+ )+ .await+ .unwrap_or(Value::Null);+ let game_ids: Vec<i64> = history+ .get("games")+ .and_then(|g| g.get("games"))+ .and_then(Value::as_array)+ .map(|arr| {+ arr.iter()+ .filter_map(|g| g.get("gameId").and_then(Value::as_i64))+ .collect()+ })+ .unwrap_or_default();+ (index, json!({ "ranked": ranked, "history": history }), game_ids)+ }));+ }++ let mut fetched: Vec<Value> = vec![Value::Null; players.len()];+ let mut histories: Vec<Vec<i64>> = vec![Vec::new(); players.len()];+ for task in tasks {+ if let Ok((index, data, ids)) = task.await {+ fetched[index] = data;+ histories[index] = ids;+ }+ }++ let mut ally_strengths = Vec::new();+ let mut enemy_strengths = Vec::new();+ let mut detail: Vec<Value> = Vec::new();++ for (index, player) in players.iter().enumerate() {+ let is_ally = player.get("isAlly").and_then(Value::as_bool).unwrap_or(false);+ let data = &fetched[index];+ let solo = data+ .get("ranked")+ .and_then(|r| r.get("queueMap"))+ .and_then(|q| q.get("RANKED_SOLO_5x5"))+ .cloned()+ .unwrap_or(Value::Null);+ let (rank, season_wins, season_losses) = if solo.is_null() {+ (None, 0, 0)+ } else {+ ranked_entry_parts(&solo)+ };++ let games: Vec<Value> = data+ .get("history")+ .and_then(|h| h.get("games"))+ .and_then(|g| g.get("games"))+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ let mut recent_wins = 0u32;+ let mut recent_losses = 0u32;+ for game in &games {+ let win = game+ .get("participants")+ .and_then(Value::as_array)+ .and_then(|p| p.first())+ .and_then(|p| p.get("stats"))+ .and_then(|s| s.get("win"))+ .and_then(Value::as_bool)+ .unwrap_or(false);+ if win {+ recent_wins += 1;+ } else {+ recent_losses += 1;+ }+ }++ let strength =+ stats::player_strength(rank, season_wins, season_losses, recent_wins, recent_losses);+ if is_ally {+ ally_strengths.push(strength);+ } else {+ enemy_strengths.push(strength);+ }++ let season_shrunk =+ stats::shrunk_winrate(season_wins, season_losses, stats::PRIOR_GAMES);+ let (wilson_low, wilson_high) =+ stats::wilson_interval(season_wins, season_losses, stats::Z_90);++ detail.push(json!({+ "puuid": player.get("puuid"),+ "isAlly": is_ally,+ "rating": strength.rating.round(),+ "sigma": strength.sigma.round(),+ "known": strength.known,+ "rankRating": rank.map(|r| r.round()),+ "seasonWins": season_wins,+ "seasonLosses": season_losses,+ "seasonWinrate": if season_wins + season_losses > 0 {+ json!(((season_wins as f64 / (season_wins + season_losses) as f64) * 100.0).round())+ } else { Value::Null },+ "seasonAvailable": season_wins + season_losses > 0,+ "recentWinrate": if recent_wins + recent_losses > 0 {+ json!(((recent_wins as f64 / (recent_wins + recent_losses) as f64) * 100.0).round())+ } else { Value::Null },+ "shrunkWinrate": (season_shrunk * 1000.0).round() / 10.0,+ "wilsonLow": (wilson_low * 1000.0).round() / 10.0,+ "wilsonHigh": (wilson_high * 1000.0).round() / 10.0,+ "recentWins": recent_wins,+ "recentGames": recent_wins + recent_losses,+ }));+ }++ let win = stats::team_win_probability(&ally_strengths, &enemy_strengths);++ // Two players who keep appearing in the same games are queueing together.+ let mut pairs: Vec<(usize, usize, u32)> = Vec::new();+ for i in 0..players.len() {+ for j in (i + 1)..players.len() {+ let a: HashSet<i64> = histories[i].iter().copied().collect();+ let shared = histories[j].iter().filter(|id| a.contains(id)).count() as u32;+ if shared > 0 {+ pairs.push((i, j, shared));+ }+ }+ }+ let groups = stats::premade_groups(players.len(), &pairs, 3);+ let premades: Vec<Value> = groups+ .iter()+ .enumerate()+ .map(|(gi, group)| {+ json!({+ "label": char::from(b'A' + (gi.min(25) as u8)).to_string(),+ "puuids": group+ .iter()+ .filter_map(|i| players[*i].get("puuid").cloned())+ .collect::<Vec<_>>(),+ })+ })+ .collect();++ Ok(json!({+ "winProbability": (win.probability * 1000.0).round() / 10.0,+ "winLow": (win.low * 1000.0).round() / 10.0,+ "winHigh": (win.high * 1000.0).round() / 10.0,+ "ratingGap": win.rating_gap.round(),+ "knownPlayers": win.known_players,+ "totalPlayers": win.total_players,+ "players": detail,+ "premades": premades,+ }))+}++/// Live economy snapshot: gold carried in items, CS and level for every player,+/// plus the difference against the opponent in the same position.+#[tauri::command]+pub async fn league_live_metrics() -> Result<Value, String> {+ ensure_enabled()?;+ let http = http_client()?;+ let base = "https://127.0.0.1:2999/liveclientdata";+ let stats_value = http+ .get(format!("{}/gamestats", base))+ .send()+ .await+ .map_err(|e| format!("live client not reachable: {}", e))?+ .json::<Value>()+ .await+ .map_err(|e| format!("invalid live client response: {}", e))?;+ let players = http+ .get(format!("{}/playerlist", base))+ .send()+ .await+ .map_err(|e| format!("live client not reachable: {}", e))?+ .json::<Value>()+ .await+ .map_err(|e| format!("invalid live client response: {}", e))?;+ let active = http+ .get(format!("{}/activeplayername", base))+ .send()+ .await+ .ok();+ let active_name = match active {+ Some(r) => r+ .json::<Value>()+ .await+ .ok()+ .and_then(|v| v.as_str().map(String::from))+ .unwrap_or_default(),+ None => String::new(),+ };++ let seconds = stats_value+ .get("gameTime")+ .and_then(Value::as_f64)+ .unwrap_or(0.0);+ let list = players.as_array().cloned().unwrap_or_default();++ let mut rows: Vec<Value> = Vec::new();+ for p in &list {+ let scores = p.get("scores").cloned().unwrap_or(Value::Null);+ let cs = scores+ .get("creepScore")+ .and_then(Value::as_f64)+ .unwrap_or(0.0);+ let prices: Vec<(u32, u32)> = p+ .get("items")+ .and_then(Value::as_array)+ .map(|items| {+ items+ .iter()+ .map(|i| {+ (+ i.get("price").and_then(Value::as_i64).unwrap_or(0).max(0) as u32,+ i.get("count").and_then(Value::as_i64).unwrap_or(1).max(0) as u32,+ )+ })+ .collect()+ })+ .unwrap_or_default();+ let item_gold = stats::items_gold(&prices);+ let riot_id = p+ .get("riotId")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string();+ rows.push(json!({+ "riotId": riot_id,+ "championName": p.get("championName"),+ "rawChampionName": p.get("rawChampionName"),+ "team": p.get("team"),+ "position": p.get("position"),+ "level": p.get("level"),+ "isDead": p.get("isDead"),+ "respawnTimer": p.get("respawnTimer"),+ "kills": scores.get("kills"),+ "deaths": scores.get("deaths"),+ "assists": scores.get("assists"),+ "cs": cs,+ "csPerMin": (stats::per_minute(cs, seconds) * 10.0).round() / 10.0,+ "visionScore": scores.get("wardScore"),+ "itemGold": item_gold,+ "goldPerMin": (stats::per_minute(item_gold as f64, seconds)).round(),+ "kda": (stats::kda(+ scores.get("kills").and_then(Value::as_i64).unwrap_or(0).max(0) as u32,+ scores.get("deaths").and_then(Value::as_i64).unwrap_or(0).max(0) as u32,+ scores.get("assists").and_then(Value::as_i64).unwrap_or(0).max(0) as u32,+ ) * 100.0).round() / 100.0,+ "isSelf": !active_name.is_empty() && riot_id == active_name,+ }));+ }++ // Match each player against the opponent holding the same position.+ let mut enriched: Vec<Value> = Vec::new();+ for row in &rows {+ let position = row.get("position").and_then(Value::as_str).unwrap_or("");+ let team = row.get("team").and_then(Value::as_str).unwrap_or("");+ let opponent = rows.iter().find(|other| {+ other.get("position").and_then(Value::as_str) == Some(position)+ && other.get("team").and_then(Value::as_str) != Some(team)+ && !position.is_empty()+ });+ let mut row = row.clone();+ if let Some(o) = opponent {+ let gold = row.get("itemGold").and_then(Value::as_i64).unwrap_or(0);+ let ogold = o.get("itemGold").and_then(Value::as_i64).unwrap_or(0);+ let cs = row.get("cs").and_then(Value::as_f64).unwrap_or(0.0);+ let ocs = o.get("cs").and_then(Value::as_f64).unwrap_or(0.0);+ let level = row.get("level").and_then(Value::as_i64).unwrap_or(0);+ let olevel = o.get("level").and_then(Value::as_i64).unwrap_or(0);+ row["goldDiff"] = json!(gold - ogold);+ row["csDiff"] = json!(cs - ocs);+ row["levelDiff"] = json!(level - olevel);+ row["opponent"] = o.get("championName").cloned().unwrap_or(Value::Null);+ }+ enriched.push(row);+ }++ let team_gold = |team: &str| -> i64 {+ enriched+ .iter()+ .filter(|r| r.get("team").and_then(Value::as_str) == Some(team))+ .filter_map(|r| r.get("itemGold").and_then(Value::as_i64))+ .sum()+ };++ Ok(json!({+ "gameTime": seconds.round(),+ "players": enriched,+ "teamGold": { "ORDER": team_gold("ORDER"), "CHAOS": team_gold("CHAOS") },+ "teamGoldDiff": team_gold("ORDER") - team_gold("CHAOS"),+ }))+}+#[tauri::command]pub async fn league_auto_accept_set(enabled: bool) -> Result<(), String> {ensure_enabled()?;diff --git a/src-tauri/src/commands/league/stats.rs b/src-tauri/src/commands/league/stats.rsnew file mode 100644index 00000000..9f023cad--- /dev/null+++ b/src-tauri/src/commands/league/stats.rs@@ -0,0 +1,846 @@+//! Statistical model for pre-game win probability and per-role performance.+//!+//! The estimator is deliberately conservative: matchmaking targets balanced+//! games, so honest outputs cluster near 50% and always carry an interval.++/// Prior strength for the Beta-Binomial shrinkage, expressed in games.+/// A player with `PRIOR_GAMES` games is pulled halfway to the 50% baseline.+pub const PRIOR_GAMES: f64 = 40.0;++/// Elo scale: a rating gap of `ELO_SCALE` means 10:1 odds in the logistic model.+pub const ELO_SCALE: f64 = 400.0;++/// Converts log-odds into Elo-equivalent rating points (400 / ln(10)).+pub const LOGIT_TO_ELO: f64 = 173.717_792_76;++/// Rating points per full tier (Iron -> Bronze -> ...).+pub const TIER_POINTS: f64 = 400.0;++/// Rating points per division inside a tier.+pub const DIVISION_POINTS: f64 = 100.0;++/// Rating floor: Iron IV. Community MMR estimates put Iron around 600 and the+/// median player (high Silver / low Gold) around 1400-1500.+pub const RATING_FLOOR: f64 = 600.0;++/// Default rating for players whose rank is unknown or hidden (ladder median).+pub const UNRANKED_RATING: f64 = 1500.0;++/// Rating uncertainty (in points) assumed for a player with no usable data.+pub const UNKNOWN_SIGMA: f64 = 260.0;++/// How much the win-rate signal is allowed to move a player's rating.+///+/// Kept below 1 on purpose: matchmaking drives win rate back to 50%, so it+/// measures displacement from one's own bracket, not absolute skill.+pub const FORM_WEIGHT: f64 = 0.5;++/// Rating uncertainty from the gap between hidden MMR and the visible rank,+/// about one division.+pub const RANK_SIGMA: f64 = 100.0;++/// z value for a 90% two-sided interval.+pub const Z_90: f64 = 1.644_853_63;++/// Beta-Binomial posterior mean with a prior centred on 50%.+///+/// `(w + k/2) / (n + k)` — the estimate of a 10-game sample is dominated by the+/// prior, while a 1000-game sample is essentially its own raw rate. This is what+/// makes 50% over 1000 games and 50% over 10 games behave differently: the point+/// estimate matches, but the confidence (see [`beta_posterior_sd`]) does not.+pub fn shrunk_winrate(wins: u32, losses: u32, prior_games: f64) -> f64 {+ let n = (wins + losses) as f64;+ let half = prior_games / 2.0;+ (wins as f64 + half) / (n + prior_games)+}++/// Standard deviation of the Beta posterior, i.e. how unsure we are about the+/// shrunk win rate. Shrinks as 1/sqrt(n), so large samples are trusted more.+pub fn beta_posterior_sd(wins: u32, losses: u32, prior_games: f64) -> f64 {+ let half = prior_games / 2.0;+ let a = wins as f64 + half;+ let b = losses as f64 + half;+ let total = a + b;+ ((a * b) / (total * total * (total + 1.0))).sqrt()+}++/// Wilson score interval for a binomial proportion.+///+/// Preferred over the normal approximation because it stays inside `[0, 1]` and+/// keeps sensible coverage for small `n` (where `p̂ ± z·sqrt(p̂q̂/n)` breaks down).+pub fn wilson_interval(wins: u32, losses: u32, z: f64) -> (f64, f64) {+ let n = (wins + losses) as f64;+ if n <= 0.0 {+ return (0.0, 1.0);+ }+ let p = wins as f64 / n;+ let z2 = z * z;+ let denom = 1.0 + z2 / n;+ let center = (p + z2 / (2.0 * n)) / denom;+ let margin = (z / denom) * ((p * (1.0 - p) / n) + z2 / (4.0 * n * n)).sqrt();+ ((center - margin).max(0.0), (center + margin).min(1.0))+}++/// Maps a ranked tier/division/LP triple onto a continuous rating scale.+///+/// Divisions are numbered from IV (lowest) to I (highest); apex tiers have a+/// single division and let LP run past 100.+pub fn rank_rating(tier: &str, division: &str, league_points: u32) -> Option<f64> {+ let tier_index = match tier.to_ascii_uppercase().as_str() {+ "IRON" => 0.0,+ "BRONZE" => 1.0,+ "SILVER" => 2.0,+ "GOLD" => 3.0,+ "PLATINUM" => 4.0,+ "EMERALD" => 5.0,+ "DIAMOND" => 6.0,+ "MASTER" => 7.0,+ "GRANDMASTER" => 8.0,+ "CHALLENGER" => 9.0,+ _ => return None,+ };+ let division_index = match division.to_ascii_uppercase().as_str() {+ "IV" | "4" => 0.0,+ "III" | "3" => 1.0,+ "II" | "2" => 2.0,+ "I" | "1" | "NA" | "" => 3.0,+ _ => 0.0,+ };+ let apex = tier_index >= 7.0;+ let base = RATING_FLOOR + tier_index * TIER_POINTS;+ if apex {+ // Apex tiers have no divisions; LP keeps climbing, so compress it.+ Some(base + (league_points as f64).min(2000.0) * 0.4)+ } else {+ Some(base + division_index * DIVISION_POINTS + (league_points as f64).min(100.0))+ }+}++/// Rating adjustment derived from a win rate, in Elo-equivalent points.+///+/// A shrunk 50% rate contributes nothing; deviations are converted through the+/// logit so the scale matches the logistic win model.+pub fn winrate_rating_delta(shrunk: f64) -> f64 {+ let p = shrunk.clamp(0.001, 0.999);+ (p / (1.0 - p)).ln() * LOGIT_TO_ELO+}++/// Logistic expectancy: probability that a rating of `a` beats a rating of `b`.+pub fn elo_expectancy(a: f64, b: f64) -> f64 {+ 1.0 / (1.0 + 10f64.powf((b - a) / ELO_SCALE))+}++/// Log5 (Bradley-Terry) combination of two independent win rates.+///+/// `P = (pa − pa·pb) / (pa + pb − 2·pa·pb)` — used as a cross-check of the Elo+/// path; both reduce to the same answer for symmetric inputs.+pub fn log5(pa: f64, pb: f64) -> f64 {+ let num = pa - pa * pb;+ let den = pa + pb - 2.0 * pa * pb;+ if den.abs() < f64::EPSILON {+ 0.5+ } else {+ num / den+ }+}++/// One player's contribution to the team strength estimate.+#[derive(Debug, Clone, Copy)]+pub struct PlayerStrength {+ /// Point estimate of the player's rating.+ pub rating: f64,+ /// Standard deviation of that estimate, in rating points.+ pub sigma: f64,+ /// False when the player had no usable rank or history.+ pub known: bool,+}++impl PlayerStrength {+ pub fn unknown() -> Self {+ Self {+ rating: UNRANKED_RATING,+ sigma: UNKNOWN_SIGMA,+ known: false,+ }+ }+}++/// Builds a player's strength from rank plus win-rate evidence.+///+/// Rank carries the skill signal (matchmaking pushes win rate back to ~50% at+/// equilibrium, so a win rate mostly measures whether someone is currently+/// climbing or sliding). Season and recent samples enter as shrunk deviations.+pub fn player_strength(+ rank: Option<f64>,+ season_wins: u32,+ season_losses: u32,+ recent_wins: u32,+ recent_losses: u32,+) -> PlayerStrength {+ let season_games = season_wins + season_losses;+ let recent_games = recent_wins + recent_losses;+ if rank.is_none() && season_games == 0 && recent_games == 0 {+ return PlayerStrength::unknown();+ }++ let base = rank.unwrap_or(UNRANKED_RATING);+ // Rank is the strong signal; without it we fall back to a wide prior.+ let base_sigma = if rank.is_some() { RANK_SIGMA } else { UNKNOWN_SIGMA };++ let season_p = shrunk_winrate(season_wins, season_losses, PRIOR_GAMES);+ let season_delta = winrate_rating_delta(season_p);+ let season_sd = beta_posterior_sd(season_wins, season_losses, PRIOR_GAMES);++ let recent_p = shrunk_winrate(recent_wins, recent_losses, PRIOR_GAMES);+ let recent_delta = winrate_rating_delta(recent_p);+ let recent_sd = beta_posterior_sd(recent_wins, recent_losses, PRIOR_GAMES);++ // Season sample is larger and steadier; recent games carry the form signal.+ let delta = FORM_WEIGHT * (0.65 * season_delta + 0.35 * recent_delta);++ // Delta method: d(rating)/d(p) = LOGIT_TO_ELO / (p(1-p)).+ let season_slope = LOGIT_TO_ELO / (season_p * (1.0 - season_p)).max(1e-6);+ let recent_slope = LOGIT_TO_ELO / (recent_p * (1.0 - recent_p)).max(1e-6);+ let delta_sigma = FORM_WEIGHT+ * ((0.65 * season_slope * season_sd).powi(2) + (0.35 * recent_slope * recent_sd).powi(2))+ .sqrt();++ PlayerStrength {+ rating: base + delta,+ sigma: (base_sigma.powi(2) + delta_sigma.powi(2)).sqrt(),+ known: true,+ }+}++/// Result of the team-vs-team comparison.+#[derive(Debug, Clone, Copy)]+pub struct WinProbability {+ /// Point estimate for the ally team.+ pub probability: f64,+ /// Lower bound of the 90% interval.+ pub low: f64,+ /// High bound of the 90% interval.+ pub high: f64,+ /// Mean rating gap in Elo points (positive favours the allies).+ pub rating_gap: f64,+ /// How many of the ten players contributed real data.+ pub known_players: usize,+ pub total_players: usize,+}++/// Aggregates both teams and returns the ally win probability with an interval.+///+/// Teams are equal size, so the mean rating is the right aggregate under a+/// Bradley-Terry model with additive strengths. The interval comes from+/// propagating each player's variance through the mean and then through the+/// logistic — it is wide on purpose when players are unknown.+pub fn team_win_probability(allies: &[PlayerStrength], enemies: &[PlayerStrength]) -> WinProbability {+ let total_players = allies.len() + enemies.len();+ let known_players = allies.iter().filter(|p| p.known).count()+ + enemies.iter().filter(|p| p.known).count();++ if allies.is_empty() || enemies.is_empty() {+ return WinProbability {+ probability: 0.5,+ low: 0.0,+ high: 1.0,+ rating_gap: 0.0,+ known_players,+ total_players,+ };+ }++ let mean = |team: &[PlayerStrength]| -> f64 {+ team.iter().map(|p| p.rating).sum::<f64>() / team.len() as f64+ };+ // Variance of a mean of independent estimates: sum(sigma^2) / n^2.+ let mean_var = |team: &[PlayerStrength]| -> f64 {+ team.iter().map(|p| p.sigma * p.sigma).sum::<f64>() / (team.len() as f64).powi(2)+ };++ let gap = mean(allies) - mean(enemies);+ let gap_sigma = (mean_var(allies) + mean_var(enemies)).sqrt();++ let probability = elo_expectancy(mean(allies), mean(enemies));+ let low = elo_expectancy(gap - Z_90 * gap_sigma, 0.0);+ let high = elo_expectancy(gap + Z_90 * gap_sigma, 0.0);++ WinProbability {+ probability,+ low: low.min(probability),+ high: high.max(probability),+ rating_gap: gap,+ known_players,+ total_players,+ }+}++/// Per-minute normalisation guarding against zero-length games.+pub fn per_minute(value: f64, seconds: f64) -> f64 {+ if seconds <= 0.0 {+ 0.0+ } else {+ value / (seconds / 60.0)+ }+}++/// KDA ratio with the usual "perfect KDA" convention when deaths are zero.+pub fn kda(kills: u32, deaths: u32, assists: u32) -> f64 {+ let k = (kills + assists) as f64;+ if deaths == 0 {+ k+ } else {+ k / deaths as f64+ }+}++/// Kill participation: share of the team's kills the player was involved in.+pub fn kill_participation(kills: u32, assists: u32, team_kills: u32) -> f64 {+ if team_kills == 0 {+ 0.0+ } else {+ ((kills + assists) as f64 / team_kills as f64).min(1.0)+ }+}++/// Gold value carried in a player's item slots (exact, from live item prices).+pub fn items_gold(prices: &[(u32, u32)]) -> u32 {+ prices.iter().map(|(price, count)| price * count).sum()+}++/// Default performance targets per role, used until the user overrides them.+#[derive(Debug, Clone, Copy)]+pub struct RoleTargets {+ pub cs_per_min: f64,+ pub gold_per_min: f64,+ pub kda: f64,+ pub vision_per_min: f64,+ pub damage_share: f64,+}++/// Baselines are per-role because a support's CS target is not a mid's.+pub fn default_targets(position: &str) -> RoleTargets {+ match position.to_ascii_uppercase().as_str() {+ "TOP" => RoleTargets {+ cs_per_min: 7.0,+ gold_per_min: 380.0,+ kda: 2.5,+ vision_per_min: 0.6,+ damage_share: 0.22,+ },+ "JUNGLE" => RoleTargets {+ cs_per_min: 5.5,+ gold_per_min: 360.0,+ kda: 3.0,+ vision_per_min: 1.0,+ damage_share: 0.18,+ },+ "MIDDLE" | "MID" => RoleTargets {+ cs_per_min: 7.5,+ gold_per_min: 400.0,+ kda: 3.0,+ vision_per_min: 0.7,+ damage_share: 0.27,+ },+ "BOTTOM" | "ADC" => RoleTargets {+ cs_per_min: 8.0,+ gold_per_min: 420.0,+ kda: 3.0,+ vision_per_min: 0.6,+ damage_share: 0.28,+ },+ "UTILITY" | "SUPPORT" => RoleTargets {+ cs_per_min: 1.5,+ gold_per_min: 260.0,+ kda: 3.0,+ vision_per_min: 2.0,+ damage_share: 0.10,+ },+ _ => RoleTargets {+ cs_per_min: 6.0,+ gold_per_min: 360.0,+ kda: 2.5,+ vision_per_min: 0.8,+ damage_share: 0.20,+ },+ }+}++/// Share of a team total, expressed against an even split.+///+/// `1.0` means the player carried exactly their fair share (1/team_size);+/// `2.0` means double it. Returns 0 when the team total is unusable.+pub fn contribution_ratio(value: f64, team_total: f64, team_size: usize) -> f64 {+ if team_total <= 0.0 || team_size == 0 {+ return 0.0;+ }+ (value / team_total) * team_size as f64+}++/// Kill-damage efficiency: kill share divided by damage share.+///+/// Above 1 the player converts less damage into more kills (finishing or+/// stealing); below 1 they deal damage others convert. Neutral when unknown.+pub fn kill_damage_efficiency(+ kills: u32,+ team_kills: u32,+ damage: f64,+ team_damage: f64,+) -> f64 {+ if team_kills == 0 || team_damage <= 0.0 || damage <= 0.0 {+ return 1.0;+ }+ let kill_share = kills as f64 / team_kills as f64;+ let damage_share = damage / team_damage;+ if damage_share <= 0.0 {+ 1.0+ } else {+ kill_share / damage_share+ }+}++/// Linear ramp used by the impact components: `min` scores 0, `max` scores full.+fn ramp(value: f64, min: f64, max: f64, weight: f64) -> f64 {+ if max <= min {+ return 0.0;+ }+ ((value - min) / (max - min)).clamp(0.0, 1.0) * weight+}++/// Inputs for the composite impact score, all taken from one finished game.+#[derive(Debug, Clone, Copy, Default)]+pub struct ImpactInput {+ pub kills: u32,+ pub deaths: u32,+ pub assists: u32,+ pub team_kills: u32,+ pub damage_to_champions: f64,+ pub team_damage: f64,+ pub damage_taken: f64,+ pub team_damage_taken: f64,+ pub gold: f64,+ pub team_gold: f64,+ pub cs: f64,+ pub vision_score: f64,+ pub team_vision: f64,+ pub duration_seconds: f64,+ pub team_size: usize,+}++/// Composite 0-10 impact score for a single game.+///+/// Every component is a bounded ramp, so no single stat can dominate and the+/// result stays comparable across roles and game lengths.+pub fn impact_score(input: &ImpactInput) -> f64 {+ let team_size = if input.team_size == 0 { 5 } else { input.team_size };++ // KDA on a square-root curve: the gap from 2 to 5 matters more than 8 to 11.+ let kda_value = kda(input.kills, input.deaths, input.assists);+ let kda_component = ramp((kda_value - 2.0).max(0.0).sqrt(), 0.0, 2.2, 1.5);++ let kp = kill_participation(input.kills, input.assists, input.team_kills);+ let kp_component = ramp(kp, 0.3, 1.0, 1.5);++ let damage_component = ramp(+ contribution_ratio(input.damage_to_champions, input.team_damage, team_size),+ 1.0,+ 2.0,+ 2.0,+ );+ let tank_component = ramp(+ contribution_ratio(input.damage_taken, input.team_damage_taken, team_size),+ 1.0,+ 2.0,+ 1.0,+ );+ let gold_component = ramp(+ contribution_ratio(input.gold, input.team_gold, team_size),+ 1.0,+ 1.5,+ 1.5,+ );+ let vision_component = ramp(+ contribution_ratio(input.vision_score, input.team_vision, team_size),+ 1.0,+ 2.0,+ 1.5,+ );+ let cs_component = ramp(per_minute(input.cs, input.duration_seconds), 4.0, 9.0, 1.0);++ (kda_component+ + kp_component+ + damage_component+ + tank_component+ + gold_component+ + vision_component+ + cs_component)+ .clamp(0.0, 10.0)+}++/// Disjoint-set forest used to merge overlapping premade pairs.+struct DisjointSet {+ parent: Vec<usize>,+}++impl DisjointSet {+ fn new(n: usize) -> Self {+ Self {+ parent: (0..n).collect(),+ }+ }++ fn find(&mut self, x: usize) -> usize {+ if self.parent[x] != x {+ let root = self.find(self.parent[x]);+ self.parent[x] = root;+ }+ self.parent[x]+ }++ fn union(&mut self, a: usize, b: usize) {+ let (ra, rb) = (self.find(a), self.find(b));+ if ra != rb {+ self.parent[rb] = ra;+ }+ }+}++/// Groups players that keep showing up in each other's recent games.+///+/// `pairs` holds `(i, j, shared_games)`. Pairs at or above `threshold` are+/// merged transitively, so a duo that both queue with a third player surfaces as+/// one trio. Groups of a single player are dropped.+pub fn premade_groups(+ player_count: usize,+ pairs: &[(usize, usize, u32)],+ threshold: u32,+) -> Vec<Vec<usize>> {+ if player_count == 0 {+ return Vec::new();+ }+ let mut sets = DisjointSet::new(player_count);+ for (a, b, shared) in pairs {+ if *shared >= threshold && *a < player_count && *b < player_count {+ sets.union(*a, *b);+ }+ }+ let mut buckets: std::collections::HashMap<usize, Vec<usize>> =+ std::collections::HashMap::new();+ for i in 0..player_count {+ let root = sets.find(i);+ buckets.entry(root).or_default().push(i);+ }+ let mut groups: Vec<Vec<usize>> = buckets+ .into_values()+ .filter(|g| g.len() > 1)+ .map(|mut g| {+ g.sort_unstable();+ g+ })+ .collect();+ groups.sort_by(|a, b| a[0].cmp(&b[0]));+ groups+}++#[cfg(test)]+mod tests {+ use super::*;++ fn close(a: f64, b: f64, tol: f64) -> bool {+ (a - b).abs() < tol+ }++ #[test]+ fn shrinkage_pulls_small_samples_toward_the_baseline() {+ // 60% over 10 games is mostly prior; 60% over 1000 games is trusted.+ let small = shrunk_winrate(6, 4, PRIOR_GAMES);+ let large = shrunk_winrate(600, 400, PRIOR_GAMES);+ assert!(small < large, "small sample must shrink harder");+ assert!(close(small, 0.52, 0.01), "got {}", small);+ assert!(close(large, 0.596, 0.005), "got {}", large);+ }++ #[test]+ fn equal_rates_differ_only_in_confidence() {+ // The user's question: 50% over 1000 vs 50% over 10.+ let few = shrunk_winrate(5, 5, PRIOR_GAMES);+ let many = shrunk_winrate(500, 500, PRIOR_GAMES);+ assert!(close(few, 0.5, 1e-9));+ assert!(close(many, 0.5, 1e-9));++ let sd_few = beta_posterior_sd(5, 5, PRIOR_GAMES);+ let sd_many = beta_posterior_sd(500, 500, PRIOR_GAMES);+ assert!(sd_few > sd_many * 4.0, "large sample must be far tighter");+ }++ #[test]+ fn wilson_interval_matches_known_values() {+ // Textbook check: 10 successes in 20 trials at 95% -> about (0.299, 0.701).+ let (lo, hi) = wilson_interval(10, 10, 1.959_964);+ assert!(close(lo, 0.299, 0.002), "lo={}", lo);+ assert!(close(hi, 0.701, 0.002), "hi={}", hi);++ // Zero successes must stay inside [0, 1] (where the normal approx fails).+ let (lo0, hi0) = wilson_interval(0, 10, 1.959_964);+ assert!(lo0 >= 0.0 && hi0 < 0.32, "({}, {})", lo0, hi0);+ }++ #[test]+ fn wilson_tightens_with_sample_size() {+ let (lo_small, hi_small) = wilson_interval(5, 5, Z_90);+ let (lo_big, hi_big) = wilson_interval(500, 500, Z_90);+ assert!((hi_small - lo_small) > (hi_big - lo_big) * 8.0);+ }++ #[test]+ fn rank_rating_is_monotonic() {+ let iron4 = rank_rating("IRON", "IV", 0).unwrap();+ assert!(close(iron4, RATING_FLOOR, 1e-9));+ // Silver IV should land near the ladder median used for unranked.+ let silver4 = rank_rating("SILVER", "IV", 0).unwrap();+ assert!((silver4 - UNRANKED_RATING).abs() < 150.0, "silver4={}", silver4);+ let gold4 = rank_rating("GOLD", "IV", 0).unwrap();+ let gold1 = rank_rating("GOLD", "I", 75).unwrap();+ let emerald4 = rank_rating("EMERALD", "IV", 0).unwrap();+ let challenger = rank_rating("CHALLENGER", "I", 900).unwrap();+ assert!(iron4 < gold4 && gold4 < gold1 && gold1 < emerald4 && emerald4 < challenger);+ assert!(close(gold4 - iron4, 3.0 * TIER_POINTS, 1e-9));+ assert!(rank_rating("UNRANKED", "", 0).is_none());+ }++ #[test]+ fn elo_expectancy_is_symmetric_and_calibrated() {+ assert!(close(elo_expectancy(1500.0, 1500.0), 0.5, 1e-12));+ // A 400-point gap is 10:1 odds by construction.+ assert!(close(elo_expectancy(1900.0, 1500.0), 10.0 / 11.0, 1e-9));+ let p = elo_expectancy(1600.0, 1500.0);+ assert!(close(p + elo_expectancy(1500.0, 1600.0), 1.0, 1e-12));+ }++ #[test]+ fn log5_agrees_with_the_logit_path() {+ // Log5 of two rates equals the logistic on their rating deltas.+ let pa = 0.6;+ let pb = 0.45;+ let via_log5 = log5(pa, pb);+ let ra = winrate_rating_delta(pa);+ let rb = winrate_rating_delta(pb);+ let via_elo = elo_expectancy(ra, rb);+ assert!(close(via_log5, via_elo, 1e-9), "{} vs {}", via_log5, via_elo);+ assert!(close(log5(0.5, 0.5), 0.5, 1e-12));+ }++ #[test]+ fn winrate_delta_is_zero_at_the_baseline() {+ assert!(close(winrate_rating_delta(0.5), 0.0, 1e-12));+ assert!(winrate_rating_delta(0.6) > 0.0);+ assert!(winrate_rating_delta(0.4) < 0.0);+ assert!(close(+ winrate_rating_delta(0.6),+ -winrate_rating_delta(0.4),+ 1e-9+ ));+ }++ #[test]+ fn sample_size_changes_strength_not_just_confidence() {+ let rank = rank_rating("GOLD", "II", 50);+ // Same 60% rate, very different sample sizes.+ let veteran = player_strength(rank, 600, 400, 12, 8);+ let rookie = player_strength(rank, 6, 4, 6, 4);+ assert!(+ veteran.rating > rookie.rating,+ "1000 games at 60% must outrank 10 games at 60% ({} vs {})",+ veteran.rating,+ rookie.rating+ );+ assert!(+ veteran.sigma < rookie.sigma,+ "the big sample must also be more certain"+ );+ }++ #[test]+ fn balanced_teams_land_near_even() {+ let rank = rank_rating("PLATINUM", "II", 40);+ let team: Vec<PlayerStrength> = (0..5)+ .map(|_| player_strength(rank, 100, 100, 10, 10))+ .collect();+ let p = team_win_probability(&team, &team);+ assert!(close(p.probability, 0.5, 1e-9));+ assert!(close(p.rating_gap, 0.0, 1e-9));+ assert_eq!(p.known_players, 10);+ }++ #[test]+ fn stronger_team_is_favoured_but_not_absurdly() {+ let high = rank_rating("DIAMOND", "IV", 0);+ let low = rank_rating("GOLD", "IV", 0);+ let allies: Vec<PlayerStrength> = (0..5)+ .map(|_| player_strength(high, 120, 80, 12, 8))+ .collect();+ let enemies: Vec<PlayerStrength> = (0..5)+ .map(|_| player_strength(low, 80, 120, 8, 12))+ .collect();+ let p = team_win_probability(&allies, &enemies);+ assert!(p.probability > 0.8, "got {}", p.probability);+ assert!(p.rating_gap > 0.0);+ assert!(p.low < p.probability && p.high > p.probability);+ }++ #[test]+ fn unknown_players_widen_the_interval() {+ let rank = rank_rating("SILVER", "I", 20);+ let known: Vec<PlayerStrength> = (0..5)+ .map(|_| player_strength(rank, 50, 50, 10, 10))+ .collect();+ let mut hidden = known.clone();+ hidden[0] = PlayerStrength::unknown();+ hidden[1] = PlayerStrength::unknown();++ let tight = team_win_probability(&known, &known);+ let loose = team_win_probability(&hidden, &known);+ assert!(+ (loose.high - loose.low) > (tight.high - tight.low),+ "hidden profiles must not fake precision"+ );+ assert_eq!(loose.known_players, 8);+ assert_eq!(loose.total_players, 10);+ }++ #[test]+ fn probability_stays_inside_the_interval() {+ let a = rank_rating("EMERALD", "III", 60);+ let b = rank_rating("PLATINUM", "I", 90);+ let allies: Vec<PlayerStrength> =+ (0..5).map(|_| player_strength(a, 33, 27, 11, 9)).collect();+ let enemies: Vec<PlayerStrength> =+ (0..5).map(|_| player_strength(b, 40, 40, 10, 10)).collect();+ let p = team_win_probability(&allies, &enemies);+ assert!(p.low <= p.probability && p.probability <= p.high);+ assert!(p.low >= 0.0 && p.high <= 1.0);+ }++ #[test]+ fn kda_and_participation_behave() {+ assert!(close(kda(6, 3, 6), 4.0, 1e-12));+ // Zero deaths reports the raw kill+assist count instead of dividing by 0.+ assert!(close(kda(5, 0, 5), 10.0, 1e-12));+ assert!(close(kill_participation(3, 5, 16), 0.5, 1e-12));+ assert!(close(kill_participation(3, 5, 0), 0.0, 1e-12));+ // Participation cannot exceed 100% even with odd inputs.+ assert!(close(kill_participation(10, 10, 5), 1.0, 1e-12));+ }++ #[test]+ fn per_minute_and_items_gold_are_exact() {+ // 128 CS in a 28:06 game (1686s) — matches the live-client sample.+ assert!(close(per_minute(128.0, 1686.0), 4.556, 0.001));+ assert!(close(per_minute(9002.0, 1686.0), 320.4, 0.1));+ assert!(close(per_minute(1.0, 0.0), 0.0, 1e-12));+ // Doran's Ring (400) + trinket (0) as reported by the live client.+ assert_eq!(items_gold(&[(400, 1), (0, 1)]), 400);+ assert_eq!(items_gold(&[(1300, 1), (900, 2)]), 3100);+ }++ #[test]+ fn contribution_ratio_measures_fair_share() {+ // 20% of the team total in a 5-man team is exactly a fair share.+ assert!(close(contribution_ratio(200.0, 1000.0, 5), 1.0, 1e-12));+ assert!(close(contribution_ratio(400.0, 1000.0, 5), 2.0, 1e-12));+ assert!(close(contribution_ratio(1.0, 0.0, 5), 0.0, 1e-12));+ }++ #[test]+ fn kill_damage_efficiency_flags_finishers_and_feeders() {+ // 40% of kills on 20% of the damage: a finisher.+ let ks = kill_damage_efficiency(4, 10, 200.0, 1000.0);+ assert!(close(ks, 2.0, 1e-9), "got {}", ks);+ // Half the damage but only a fifth of the kills: enabling others.+ let dealer = kill_damage_efficiency(2, 10, 500.0, 1000.0);+ assert!(close(dealer, 0.4, 1e-9), "got {}", dealer);+ // Missing data stays neutral instead of exploding.+ assert!(close(kill_damage_efficiency(0, 0, 0.0, 0.0), 1.0, 1e-12));+ }++ #[test]+ fn impact_score_separates_a_carry_from_a_passenger() {+ let base = ImpactInput {+ team_kills: 40,+ team_damage: 100_000.0,+ team_damage_taken: 100_000.0,+ team_gold: 60_000.0,+ team_vision: 100.0,+ duration_seconds: 1800.0,+ team_size: 5,+ ..Default::default()+ };+ let carry = ImpactInput {+ kills: 15,+ deaths: 3,+ assists: 10,+ damage_to_champions: 40_000.0,+ damage_taken: 20_000.0,+ gold: 18_000.0,+ cs: 250.0,+ vision_score: 30.0,+ ..base+ };+ let passenger = ImpactInput {+ kills: 1,+ deaths: 9,+ assists: 4,+ damage_to_champions: 8_000.0,+ damage_taken: 12_000.0,+ gold: 8_000.0,+ cs: 90.0,+ vision_score: 10.0,+ ..base+ };+ let cs_score = impact_score(&carry);+ let ps_score = impact_score(&passenger);+ assert!(cs_score > ps_score + 3.0, "{} vs {}", cs_score, ps_score);+ assert!((0.0..=10.0).contains(&cs_score));+ assert!((0.0..=10.0).contains(&ps_score));+ // An empty game must not panic or produce a negative score.+ assert!(close(impact_score(&ImpactInput::default()), 0.0, 1e-12));+ }++ #[test]+ fn premade_detection_merges_transitively() {+ // 0-1 and 1-2 both cleared the bar, so all three queued together.+ let pairs = [(0usize, 1usize, 6u32), (1, 2, 5), (3, 4, 1)];+ let groups = premade_groups(5, &pairs, 3);+ assert_eq!(groups, vec![vec![0, 1, 2]]);+ }++ #[test]+ fn premade_detection_respects_the_threshold() {+ // Two shared games is noise, not a duo.+ let pairs = [(0usize, 1usize, 2u32)];+ assert!(premade_groups(5, &pairs, 3).is_empty());+ let solo = premade_groups(5, &[], 3);+ assert!(solo.is_empty(), "no pairs means no premades");+ // Out-of-range indices are ignored rather than panicking.+ assert!(premade_groups(2, &[(0, 9, 10)], 3).is_empty());+ }++ #[test]+ fn premade_detection_finds_two_separate_duos() {+ let pairs = [(0usize, 1usize, 8u32), (2, 3, 9)];+ let groups = premade_groups(5, &pairs, 5);+ assert_eq!(groups, vec![vec![0, 1], vec![2, 3]]);+ }++ #[test]+ fn role_targets_reflect_role_reality() {+ let sup = default_targets("UTILITY");+ let adc = default_targets("BOTTOM");+ assert!(sup.cs_per_min < adc.cs_per_min);+ assert!(sup.vision_per_min > adc.vision_per_min);+ assert!(adc.damage_share > sup.damage_share);+ // Unknown roles fall back to a neutral profile rather than panicking.+ let unknown = default_targets("");+ assert!(unknown.cs_per_min > 0.0);+ }+}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex daf11150..75974ada 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -724,6 +724,8 @@ pub fn run() {commands::league::league_live_game,commands::league::league_game_players,commands::league::league_player_report,+ commands::league::league_match_analysis,+ commands::league::league_live_metrics,commands::bilibili_auth::bilibili_qr_generate,commands::bilibili_auth::bilibili_qr_poll,commands::bilibili_auth::bilibili_captcha_challenge,diff --git a/src/lib/i18n/el.json b/src/lib/i18n/el.jsonindex 53142d6b..3cc20b75 100644--- a/src/lib/i18n/el.json+++ b/src/lib/i18n/el.json@@ -37,6 +37,42 @@"nav_downloads": "Μετάβαση στις Λήψεις"},"league": {+ "tab_overview": "Επισκόπηση",+ "tab_analysis": "Ανάλυση",+ "tab_live": "Ζωντανά",+ "tab_goals": "Στόχοι",+ "tab_automation": "Αυτοματισμός",+ "tab_history": "Ιστορικό",+ "win_title": "Πιθανότητα νίκης",+ "win_allies": "Η ομάδα σου",+ "win_interval": "εύρος 90%",+ "win_gap": "Διαφορά rating",+ "win_known": "παίκτες με δεδομένα",+ "win_disclaimer": "Το matchmaking φτιάχνει αγώνες με προσδοκία 50%, οπότε οι τίμιες εκτιμήσεις μένουν κοντά στο ισόπαλο. Δες το ως τάση, όχι ετυμηγορία.",+ "win_unavailable": "Διαθέσιμο στην επιλογή ηρώων και εντός αγώνα.",+ "premades": "Ομάδες (premade)",+ "players": "παίκτες",+ "gold_title": "Ζωντανή οικονομία",+ "gold_unavailable": "Μπες σε αγώνα για να δεις χρυσό και διαφορές lane.",+ "your_team": "Η ομάδα σου",+ "enemy_team": "Αντίπαλη ομάδα",+ "col_player": "Παίκτης",+ "col_gold": "Χρυσός",+ "col_diff": "vs αντίπαλο lane",+ "goals_live": "Οι στόχοι σου σε αυτόν τον αγώνα",+ "goals_title": "Στόχοι απόδοσης",+ "goals_role": "Ρόλος",+ "goals_desc": "Στόχοι ανά ρόλο για την αξιολόγηση του τρέχοντος αγώνα. Προσάρμοσέ τους στο επίπεδό σου.",+ "goals_reset": "Επαναφορά",+ "goal_cs": "CS ανά λεπτό",+ "goal_gold": "Χρυσός ανά λεπτό",+ "goal_kda": "KDA",+ "goal_vision": "Vision ανά λεπτό",+ "role_top": "Top",+ "role_jungle": "Jungle",+ "role_middle": "Mid",+ "role_bottom": "Bot",+ "role_utility": "Support","scout_title": "Ανάλυση αγώνα","scout_allies": "Σύμμαχοι","scout_enemies": "Αντίπαλοι",diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.jsonindex 9038c063..116725f5 100644--- a/src/lib/i18n/en.json+++ b/src/lib/i18n/en.json@@ -37,6 +37,42 @@"nav_downloads": "Go to Downloads"},"league": {+ "tab_overview": "Overview",+ "tab_analysis": "Analysis",+ "tab_live": "Live",+ "tab_goals": "Goals",+ "tab_automation": "Automation",+ "tab_history": "History",+ "win_title": "Win probability",+ "win_allies": "Your team",+ "win_interval": "90% range",+ "win_gap": "Rating gap",+ "win_known": "players with data",+ "win_disclaimer": "Matchmaking builds games around a 50% expectation, so honest estimates stay close to even. Treat this as a lean, not a verdict.",+ "win_unavailable": "Available during champion select and in game.",+ "premades": "Premade groups",+ "players": "players",+ "gold_title": "Live economy",+ "gold_unavailable": "Open a game to see live gold and lane differences.",+ "your_team": "Your team",+ "enemy_team": "Enemy team",+ "col_player": "Player",+ "col_gold": "Gold",+ "col_diff": "vs lane opponent",+ "goals_live": "Your goals this game",+ "goals_title": "Performance goals",+ "goals_role": "Role",+ "goals_desc": "Targets per role, used to grade your live game. Adjust them to your own level.",+ "goals_reset": "Reset to defaults",+ "goal_cs": "CS per minute",+ "goal_gold": "Gold per minute",+ "goal_kda": "KDA",+ "goal_vision": "Vision per minute",+ "role_top": "Top",+ "role_jungle": "Jungle",+ "role_middle": "Mid",+ "role_bottom": "Bot",+ "role_utility": "Support","scout_title": "Match scouting","scout_allies": "Allies","scout_enemies": "Enemies",diff --git a/src/lib/i18n/es.json b/src/lib/i18n/es.jsonindex cb95c5b3..b390f68b 100644--- a/src/lib/i18n/es.json+++ b/src/lib/i18n/es.json@@ -37,6 +37,42 @@"nav_downloads": "Ir a Descargas"},"league": {+ "tab_overview": "Resumen",+ "tab_analysis": "Análisis",+ "tab_live": "En vivo",+ "tab_goals": "Metas",+ "tab_automation": "Automatización",+ "tab_history": "Historial",+ "win_title": "Probabilidad de victoria",+ "win_allies": "Tu equipo",+ "win_interval": "rango del 90%",+ "win_gap": "Diferencia de rating",+ "win_known": "jugadores con datos",+ "win_disclaimer": "El emparejamiento crea partidas con una expectativa del 50%, así que las estimaciones honestas quedan cerca del empate. Tómalo como una tendencia, no un veredicto.",+ "win_unavailable": "Disponible en la selección de campeones y en partida.",+ "premades": "Grupos (premades)",+ "players": "jugadores",+ "gold_title": "Economía en vivo",+ "gold_unavailable": "Entra en una partida para ver el oro y las diferencias de línea.",+ "your_team": "Tu equipo",+ "enemy_team": "Equipo enemigo",+ "col_player": "Jugador",+ "col_gold": "Oro",+ "col_diff": "vs rival de línea",+ "goals_live": "Tus metas en esta partida",+ "goals_title": "Metas de rendimiento",+ "goals_role": "Rol",+ "goals_desc": "Metas por rol, usadas para evaluar tu partida en vivo. Ajústalas a tu nivel.",+ "goals_reset": "Restaurar valores",+ "goal_cs": "CS por minuto",+ "goal_gold": "Oro por minuto",+ "goal_kda": "KDA",+ "goal_vision": "Visión por minuto",+ "role_top": "Superior",+ "role_jungle": "Jungla",+ "role_middle": "Central",+ "role_bottom": "Tirador",+ "role_utility": "Soporte","scout_title": "Análisis de la partida","scout_allies": "Aliados","scout_enemies": "Enemigos",diff --git a/src/lib/i18n/fr.json b/src/lib/i18n/fr.jsonindex 853325c8..42b9706d 100644--- a/src/lib/i18n/fr.json+++ b/src/lib/i18n/fr.json@@ -37,6 +37,42 @@"nav_downloads": "Aller aux Téléchargements"},"league": {+ "tab_overview": "Aperçu",+ "tab_analysis": "Analyse",+ "tab_live": "En direct",+ "tab_goals": "Objectifs",+ "tab_automation": "Automatisation",+ "tab_history": "Historique",+ "win_title": "Probabilité de victoire",+ "win_allies": "Votre équipe",+ "win_interval": "plage 90%",+ "win_gap": "Écart de rating",+ "win_known": "joueurs avec données",+ "win_disclaimer": "Le matchmaking crée des parties avec une attente de 50%, donc les estimations honnêtes restent proches de l'égalité. À prendre comme une tendance, pas un verdict.",+ "win_unavailable": "Disponible pendant la sélection et en partie.",+ "premades": "Groupes (premades)",+ "players": "joueurs",+ "gold_title": "Économie en direct",+ "gold_unavailable": "Lancez une partie pour voir l'or et les écarts de voie.",+ "your_team": "Votre équipe",+ "enemy_team": "Équipe ennemie",+ "col_player": "Joueur",+ "col_gold": "Or",+ "col_diff": "vs adversaire de voie",+ "goals_live": "Vos objectifs cette partie",+ "goals_title": "Objectifs de performance",+ "goals_role": "Rôle",+ "goals_desc": "Objectifs par rôle, utilisés pour évaluer votre partie en direct. Ajustez-les à votre niveau.",+ "goals_reset": "Réinitialiser",+ "goal_cs": "CS par minute",+ "goal_gold": "Or par minute",+ "goal_kda": "KDA",+ "goal_vision": "Vision par minute",+ "role_top": "Top",+ "role_jungle": "Jungle",+ "role_middle": "Milieu",+ "role_bottom": "Tireur",+ "role_utility": "Support","scout_title": "Analyse de la partie","scout_allies": "Alliés","scout_enemies": "Ennemis",diff --git a/src/lib/i18n/it.json b/src/lib/i18n/it.jsonindex 57a60a2d..f03fbbab 100644--- a/src/lib/i18n/it.json+++ b/src/lib/i18n/it.json@@ -37,6 +37,42 @@"nav_downloads": "Vai ai Download"},"league": {+ "tab_overview": "Panoramica",+ "tab_analysis": "Analisi",+ "tab_live": "In diretta",+ "tab_goals": "Obiettivi",+ "tab_automation": "Automazione",+ "tab_history": "Cronologia",+ "win_title": "Probabilità di vittoria",+ "win_allies": "La tua squadra",+ "win_interval": "intervallo 90%",+ "win_gap": "Differenza di rating",+ "win_known": "giocatori con dati",+ "win_disclaimer": "Il matchmaking crea partite con un'aspettativa del 50%, quindi le stime oneste restano vicine alla parità. Consideralo un'inclinazione, non un verdetto.",+ "win_unavailable": "Disponibile durante la selezione e in partita.",+ "premades": "Gruppi (premade)",+ "players": "giocatori",+ "gold_title": "Economia in diretta",+ "gold_unavailable": "Entra in partita per vedere oro e differenze di corsia.",+ "your_team": "La tua squadra",+ "enemy_team": "Squadra nemica",+ "col_player": "Giocatore",+ "col_gold": "Oro",+ "col_diff": "vs avversario di corsia",+ "goals_live": "I tuoi obiettivi in questa partita",+ "goals_title": "Obiettivi di rendimento",+ "goals_role": "Ruolo",+ "goals_desc": "Obiettivi per ruolo, usati per valutare la partita in diretta. Adattali al tuo livello.",+ "goals_reset": "Ripristina",+ "goal_cs": "CS al minuto",+ "goal_gold": "Oro al minuto",+ "goal_kda": "KDA",+ "goal_vision": "Visione al minuto",+ "role_top": "Top",+ "role_jungle": "Giungla",+ "role_middle": "Mid",+ "role_bottom": "Tiratore",+ "role_utility": "Supporto","scout_title": "Analisi della partita","scout_allies": "Alleati","scout_enemies": "Nemici",diff --git a/src/lib/i18n/ja.json b/src/lib/i18n/ja.jsonindex 2f88d4a7..ab84ef90 100644--- a/src/lib/i18n/ja.json+++ b/src/lib/i18n/ja.json@@ -37,6 +37,42 @@"nav_downloads": "ダウンロードへ移動"},"league": {+ "tab_overview": "概要",+ "tab_analysis": "分析",+ "tab_live": "ライブ",+ "tab_goals": "目標",+ "tab_automation": "自動化",+ "tab_history": "履歴",+ "win_title": "勝率予測",+ "win_allies": "自チーム",+ "win_interval": "90%範囲",+ "win_gap": "レーティング差",+ "win_known": "人のデータあり",+ "win_disclaimer": "マッチメイキングは勝率50%を目標に組まれるため、誠実な推定は互角付近に留まります。傾向として見てください。",+ "win_unavailable": "チャンピオン選択中と試合中に利用できます。",+ "premades": "パーティー",+ "players": "人",+ "gold_title": "ライブ経済",+ "gold_unavailable": "試合に入るとゴールドとレーン差が表示されます。",+ "your_team": "自チーム",+ "enemy_team": "敵チーム",+ "col_player": "プレイヤー",+ "col_gold": "ゴールド",+ "col_diff": "対面との差",+ "goals_live": "この試合の目標",+ "goals_title": "パフォーマンス目標",+ "goals_role": "ロール",+ "goals_desc": "ロール別の目標値。試合中の評価に使われます。自分のレベルに合わせて調整してください。",+ "goals_reset": "初期値に戻す",+ "goal_cs": "CS/分",+ "goal_gold": "ゴールド/分",+ "goal_kda": "KDA",+ "goal_vision": "視界スコア/分",+ "role_top": "トップ",+ "role_jungle": "ジャングル",+ "role_middle": "ミッド",+ "role_bottom": "ボット",+ "role_utility": "サポート","scout_title": "マッチ分析","scout_allies": "味方","scout_enemies": "敵",diff --git a/src/lib/i18n/keys.ts b/src/lib/i18n/keys.tsindex 349bb50b..034ba5fc 100644--- a/src/lib/i18n/keys.ts+++ b/src/lib/i18n/keys.ts@@ -377,12 +377,27 @@ export type TranslationKeys =| 'league.ban_list'| 'league.bench_title'| 'league.champ_select_title'+ | 'league.col_diff'+ | 'league.col_gold'+ | 'league.col_player'| 'league.connected'| 'league.defeat'| 'league.disabled_body'| 'league.disabled_title'| 'league.disconnected_body'| 'league.disconnected_title'+ | 'league.enemy_team'+ | 'league.goal_cs'+ | 'league.goal_gold'+ | 'league.goal_kda'+ | 'league.goal_vision'+ | 'league.goals_desc'+ | 'league.goals_live'+ | 'league.goals_reset'+ | 'league.goals_role'+ | 'league.goals_title'+ | 'league.gold_title'+ | 'league.gold_unavailable'| 'league.history_empty'| 'league.history_title'| 'league.leave_lobby'@@ -402,12 +417,19 @@ export type TranslationKeys =| 'league.phase_ready_check'| 'league.pick_list'| 'league.play_again'+ | 'league.players'+ | 'league.premades'| 'league.ranked_flex'| 'league.ranked_solo'| 'league.refresh'| 'league.remove'| 'league.reroll'| 'league.respawn_in'+ | 'league.role_bottom'+ | 'league.role_jungle'+ | 'league.role_middle'+ | 'league.role_top'+ | 'league.role_utility'| 'league.scout_allies'| 'league.scout_enemies'| 'league.scout_enemies_hidden'@@ -425,6 +447,12 @@ export type TranslationKeys =| 'league.start_queue'| 'league.stop_queue'| 'league.swap'+ | 'league.tab_analysis'+ | 'league.tab_automation'+ | 'league.tab_goals'+ | 'league.tab_history'+ | 'league.tab_live'+ | 'league.tab_overview'| 'league.tag_cold_streak'| 'league.tag_high_kda'| 'league.tag_high_winrate'@@ -434,6 +462,14 @@ export type TranslationKeys =| 'league.tag_one_trick'| 'league.unranked'| 'league.victory'+ | 'league.win_allies'+ | 'league.win_disclaimer'+ | 'league.win_gap'+ | 'league.win_interval'+ | 'league.win_known'+ | 'league.win_title'+ | 'league.win_unavailable'+ | 'league.your_team'| 'legal.acknowledge'| 'legal.body_paragraph_1'diff --git a/src/lib/i18n/pt.json b/src/lib/i18n/pt.jsonindex 019a8f3f..7688f836 100644--- a/src/lib/i18n/pt.json+++ b/src/lib/i18n/pt.json@@ -37,6 +37,42 @@"nav_downloads": "Ir para Downloads"},"league": {+ "tab_overview": "Visão geral",+ "tab_analysis": "Análise",+ "tab_live": "Ao vivo",+ "tab_goals": "Metas",+ "tab_automation": "Automação",+ "tab_history": "Histórico",+ "win_title": "Chance de vitória",+ "win_allies": "Seu time",+ "win_interval": "faixa de 90%",+ "win_gap": "Diferença de rating",+ "win_known": "jogadores com dados",+ "win_disclaimer": "O emparelhamento monta partidas com expectativa de 50%, então estimativas honestas ficam perto do empate. Trate como uma tendência, não como veredito.",+ "win_unavailable": "Disponível na seleção de campeões e em partida.",+ "premades": "Grupos (premades)",+ "players": "jogadores",+ "gold_title": "Economia ao vivo",+ "gold_unavailable": "Entre em uma partida para ver ouro e diferenças de lane.",+ "your_team": "Seu time",+ "enemy_team": "Time inimigo",+ "col_player": "Jogador",+ "col_gold": "Ouro",+ "col_diff": "vs oponente de lane",+ "goals_live": "Suas metas nesta partida",+ "goals_title": "Metas de desempenho",+ "goals_role": "Função",+ "goals_desc": "Metas por função, usadas para avaliar sua partida ao vivo. Ajuste ao seu nível.",+ "goals_reset": "Restaurar padrões",+ "goal_cs": "CS por minuto",+ "goal_gold": "Ouro por minuto",+ "goal_kda": "KDA",+ "goal_vision": "Visão por minuto",+ "role_top": "Topo",+ "role_jungle": "Selva",+ "role_middle": "Meio",+ "role_bottom": "Atirador",+ "role_utility": "Suporte","scout_title": "Análise da partida","scout_allies": "Aliados","scout_enemies": "Inimigos",diff --git a/src/lib/i18n/ru.json b/src/lib/i18n/ru.jsonindex 9804a47a..28290f7c 100644--- a/src/lib/i18n/ru.json+++ b/src/lib/i18n/ru.json@@ -37,6 +37,42 @@"nav_downloads": "Перейти к загрузкам"},"league": {+ "tab_overview": "Обзор",+ "tab_analysis": "Анализ",+ "tab_live": "В игре",+ "tab_goals": "Цели",+ "tab_automation": "Автоматизация",+ "tab_history": "История",+ "win_title": "Вероятность победы",+ "win_allies": "Ваша команда",+ "win_interval": "диапазон 90%",+ "win_gap": "Разрыв рейтинга",+ "win_known": "игроков с данными",+ "win_disclaimer": "Подбор строит матчи с ожиданием 50%, поэтому честные оценки держатся около равенства. Считайте это склонностью, а не приговором.",+ "win_unavailable": "Доступно при выборе чемпионов и в игре.",+ "premades": "Группы (пати)",+ "players": "игроков",+ "gold_title": "Экономика в игре",+ "gold_unavailable": "Зайдите в игру, чтобы увидеть золото и разницу на линии.",+ "your_team": "Ваша команда",+ "enemy_team": "Команда противника",+ "col_player": "Игрок",+ "col_gold": "Золото",+ "col_diff": "против оппонента",+ "goals_live": "Ваши цели в этой игре",+ "goals_title": "Цели по показателям",+ "goals_role": "Роль",+ "goals_desc": "Цели по ролям для оценки текущей игры. Настройте под свой уровень.",+ "goals_reset": "Сбросить",+ "goal_cs": "CS в минуту",+ "goal_gold": "Золото в минуту",+ "goal_kda": "KDA",+ "goal_vision": "Обзор в минуту",+ "role_top": "Топ",+ "role_jungle": "Лес",+ "role_middle": "Мид",+ "role_bottom": "Бот",+ "role_utility": "Саппорт","scout_title": "Разведка матча","scout_allies": "Союзники","scout_enemies": "Противники",diff --git a/src/lib/i18n/zh-TW.json b/src/lib/i18n/zh-TW.jsonindex b927e578..4a4891af 100644--- a/src/lib/i18n/zh-TW.json+++ b/src/lib/i18n/zh-TW.json@@ -37,6 +37,42 @@"nav_downloads": "前往下載"},"league": {+ "tab_overview": "總覽",+ "tab_analysis": "分析",+ "tab_live": "即時",+ "tab_goals": "目標",+ "tab_automation": "自動化",+ "tab_history": "歷史",+ "win_title": "勝率預測",+ "win_allies": "我方",+ "win_interval": "90% 區間",+ "win_gap": "評分差",+ "win_known": "名玩家有資料",+ "win_disclaimer": "配對系統以 50% 勝率組建對戰,因此誠實的估計都接近五五開。請當作傾向參考,而非定論。",+ "win_unavailable": "在英雄選擇與對戰中可用。",+ "premades": "開黑小隊",+ "players": "名玩家",+ "gold_title": "即時經濟",+ "gold_unavailable": "進入對戰後可查看經濟與對線差距。",+ "your_team": "我方",+ "enemy_team": "敵方",+ "col_player": "玩家",+ "col_gold": "金幣",+ "col_diff": "對線差",+ "goals_live": "本場目標",+ "goals_title": "表現目標",+ "goals_role": "位置",+ "goals_desc": "依位置設定的目標,用於評估當前對戰。可依自己的水準調整。",+ "goals_reset": "恢復預設",+ "goal_cs": "每分鐘補兵",+ "goal_gold": "每分鐘金幣",+ "goal_kda": "KDA",+ "goal_vision": "每分鐘視野",+ "role_top": "上路",+ "role_jungle": "打野",+ "role_middle": "中路",+ "role_bottom": "射手",+ "role_utility": "輔助","scout_title": "對戰分析","scout_allies": "隊友","scout_enemies": "敵方",diff --git a/src/lib/i18n/zh.json b/src/lib/i18n/zh.jsonindex ababb27c..b2f9bab5 100644--- a/src/lib/i18n/zh.json+++ b/src/lib/i18n/zh.json@@ -37,6 +37,42 @@"nav_downloads": "前往下载"},"league": {+ "tab_overview": "总览",+ "tab_analysis": "分析",+ "tab_live": "实时",+ "tab_goals": "目标",+ "tab_automation": "自动化",+ "tab_history": "历史",+ "win_title": "胜率预测",+ "win_allies": "我方",+ "win_interval": "90% 区间",+ "win_gap": "评分差",+ "win_known": "名玩家有数据",+ "win_disclaimer": "匹配系统按 50% 胜率组建对局,因此诚实的估计都接近五五开。请当作倾向参考,而非定论。",+ "win_unavailable": "在英雄选择和对局中可用。",+ "premades": "开黑小队",+ "players": "名玩家",+ "gold_title": "实时经济",+ "gold_unavailable": "进入对局后可查看经济与对线差距。",+ "your_team": "我方",+ "enemy_team": "敌方",+ "col_player": "玩家",+ "col_gold": "金币",+ "col_diff": "对线差",+ "goals_live": "本局目标",+ "goals_title": "表现目标",+ "goals_role": "位置",+ "goals_desc": "按位置设定的目标,用于评估当前对局。可根据自己的水平调整。",+ "goals_reset": "恢复默认",+ "goal_cs": "每分钟补刀",+ "goal_gold": "每分钟金币",+ "goal_kda": "KDA",+ "goal_vision": "每分钟视野",+ "role_top": "上单",+ "role_jungle": "打野",+ "role_middle": "中单",+ "role_bottom": "射手",+ "role_utility": "辅助","scout_title": "对局分析","scout_allies": "队友","scout_enemies": "敌方",diff --git a/src/routes/league/+page.svelte b/src/routes/league/+page.svelteindex f2cc482a..a7fd669e 100644--- a/src/routes/league/+page.svelte+++ b/src/routes/league/+page.svelte@@ -99,6 +99,128 @@];}+ const TAB_IDS = ["overview", "analysis", "live", "goals", "automation", "history"] as const;+ type Tab = (typeof TAB_IDS)[number];+ let tab = $state<Tab>("overview");++ let analysis = $state<any>(null);+ let analysisLoading = $state(false);+ let liveMetrics = $state<any>(null);++ const ROLES = ["TOP", "JUNGLE", "MIDDLE", "BOTTOM", "UTILITY"] as const;+ type Role = (typeof ROLES)[number];+ const GOALS_KEY = "league-role-goals";+ const GOAL_FIELDS = [+ { key: "csPerMin", labelKey: "league.goal_cs", step: 0.1 },+ { key: "goldPerMin", labelKey: "league.goal_gold", step: 10 },+ { key: "kda", labelKey: "league.goal_kda", step: 0.1 },+ { key: "visionPerMin", labelKey: "league.goal_vision", step: 0.1 },+ ] as const;+ type GoalKey = (typeof GOAL_FIELDS)[number]["key"];++ // Baselines mirror the Rust defaults; a support is not judged on CS.+ const DEFAULT_GOALS: Record<Role, Record<GoalKey, number>> = {+ TOP: { csPerMin: 7.0, goldPerMin: 380, kda: 2.5, visionPerMin: 0.6 },+ JUNGLE: { csPerMin: 5.5, goldPerMin: 360, kda: 3.0, visionPerMin: 1.0 },+ MIDDLE: { csPerMin: 7.5, goldPerMin: 400, kda: 3.0, visionPerMin: 0.7 },+ BOTTOM: { csPerMin: 8.0, goldPerMin: 420, kda: 3.0, visionPerMin: 0.6 },+ UTILITY: { csPerMin: 1.5, goldPerMin: 260, kda: 3.0, visionPerMin: 2.0 },+ };++ let goalRole = $state<Role>("MIDDLE");+ let goals = $state<Record<string, Record<string, number>>>({});++ function loadGoals() {+ try {+ goals = JSON.parse(localStorage.getItem(GOALS_KEY) ?? "{}");+ } catch {+ goals = {};+ }+ }++ function goalValue(role: Role, key: GoalKey): number {+ return goals[role]?.[key] ?? DEFAULT_GOALS[role][key];+ }++ function setGoal(role: Role, key: GoalKey, value: number) {+ if (!Number.isFinite(value) || value < 0) return;+ goals = { ...goals, [role]: { ...(goals[role] ?? {}), [key]: value } };+ localStorage.setItem(GOALS_KEY, JSON.stringify(goals));+ }++ function resetGoals(role: Role) {+ const next = { ...goals };+ delete next[role];+ goals = next;+ localStorage.setItem(GOALS_KEY, JSON.stringify(goals));+ }++ async function loadAnalysis() {+ if (analysisLoading) return;+ analysisLoading = true;+ try {+ analysis = await invoke<any>("league_match_analysis");+ } catch {+ analysis = null;+ } finally {+ analysisLoading = false;+ }+ }++ async function loadLiveMetrics() {+ try {+ liveMetrics = await invoke<any>("league_live_metrics");+ } catch {+ liveMetrics = null;+ }+ }++ let selfRow = $derived(liveMetrics?.players?.find((r: any) => r.isSelf) ?? null);+ let myTeam = $derived(selfRow?.team ?? "ORDER");+ let enemyTeam = $derived(myTeam === "ORDER" ? "CHAOS" : "ORDER");+ let teamGoldLead = $derived(+ (liveMetrics?.teamGold?.[myTeam] ?? 0) - (liveMetrics?.teamGold?.[enemyTeam] ?? 0)+ );++ let liveGoals = $derived.by(() => {+ if (!selfRow) return [];+ const role: Role = (ROLES as readonly string[]).includes(selfRow.position)+ ? (selfRow.position as Role)+ : "MIDDLE";+ const minutes = Math.max((liveMetrics?.gameTime ?? 0) / 60, 0.1);+ const visionPerMin = (selfRow.visionScore ?? 0) / minutes;+ return [+ {+ key: "csPerMin",+ labelKey: "league.goal_cs",+ current: (selfRow.csPerMin ?? 0).toFixed(1),+ target: goalValue(role, "csPerMin").toFixed(1),+ ratio: (selfRow.csPerMin ?? 0) / goalValue(role, "csPerMin"),+ },+ {+ key: "goldPerMin",+ labelKey: "league.goal_gold",+ current: String(selfRow.goldPerMin ?? 0),+ target: String(goalValue(role, "goldPerMin")),+ ratio: (selfRow.goldPerMin ?? 0) / goalValue(role, "goldPerMin"),+ },+ {+ key: "kda",+ labelKey: "league.goal_kda",+ current: (selfRow.kda ?? 0).toFixed(2),+ target: goalValue(role, "kda").toFixed(1),+ ratio: (selfRow.kda ?? 0) / goalValue(role, "kda"),+ },+ {+ key: "visionPerMin",+ labelKey: "league.goal_vision",+ current: visionPerMin.toFixed(1),+ target: goalValue(role, "visionPerMin").toFixed(1),+ ratio: visionPerMin / goalValue(role, "visionPerMin"),+ },+ ];+ });+const PHASE_KEYS: Record<string, string> = {Lobby: "league.phase_lobby",Matchmaking: "league.phase_matchmaking",@@ -189,8 +311,15 @@}if (phase === "ChampSelect" || phase === "InProgress") {if (scoutPlayers.length === 0) loadScouting();+ if (!analysis && !analysisLoading) loadAnalysis();} else if (scoutPlayers.length > 0) {scoutPlayers = [];+ analysis = null;+ }+ if (phase === "InProgress") {+ loadLiveMetrics();+ } else if (liveMetrics) {+ liveMetrics = null;}if (phase === "Lobby" || phase === "Matchmaking") {try {@@ -346,6 +475,7 @@onMount(() => {if (!enabled) return;loadNotes();+ loadGoals();invoke<boolean>("league_auto_accept_get").then((v) => { autoAccept = v; }).catch(() => {});@@ -382,6 +512,15 @@<p>{$t("league.disconnected_body")}</p></div>{:else}+ <nav class="league-tabs" aria-label={$t("league.nav") as string}>+ {#each TAB_IDS as id (id)}+ <button class="league-tab" class:on={tab === id} onclick={() => (tab = id)} aria-current={tab === id}>+ {$t(`league.tab_${id}`)}+ </button>+ {/each}+ </nav>++ {#if tab === "overview"}{#if summoner}<section class="profile-card"><img@@ -408,11 +547,9 @@</div></section>{/if}-{#if actionError}<div class="action-error" role="alert">{actionError}</div>{/if}-{#if phase === "ChampSelect" && champSelect}<section class="card"><div class="card-head">@@ -515,6 +652,44 @@{/if}</section>{/if}+ {/if}++ {#if tab === "analysis"}+ {#if analysis}+ <section class="card">+ <div class="card-head">+ <h3>{$t("league.win_title")}</h3>+ <button class="button" onclick={loadAnalysis} disabled={analysisLoading}>{$t("league.refresh")}</button>+ </div>+ <div class="winbar-wrap">+ <div class="winbar" role="img" aria-label={`${$t("league.win_allies")} ${analysis.winProbability}%`}>+ <div class="winbar-fill" style={`width:${analysis.winProbability}%`}></div>+ <div class="winbar-range" style={`left:${analysis.winLow}%;width:${Math.max(analysis.winHigh - analysis.winLow, 0)}%`}></div>+ </div>+ <div class="winbar-legend">+ <span class="win-value">{analysis.winProbability}%</span>+ <span class="win-range">{$t("league.win_interval")} {analysis.winLow}%–{analysis.winHigh}%</span>+ </div>+ </div>+ <p class="win-note">+ {$t("league.win_gap")} {analysis.ratingGap > 0 ? "+" : ""}{analysis.ratingGap} · {analysis.knownPlayers}/{analysis.totalPlayers} {$t("league.win_known")}+ </p>+ <p class="win-disclaimer">{$t("league.win_disclaimer")}</p>+ {#if analysis.premades?.length}+ <div class="premade-row">+ <span class="bench-label">{$t("league.premades")}</span>+ {#each analysis.premades as group (group.label)}+ <span class="scout-tag">{group.label}: {group.puuids.length} {$t("league.players")}</span>+ {/each}+ </div>+ {/if}+ </section>+ {:else}+ <div class="guard-card">+ <p>{$t("league.win_unavailable")}</p>+ <button class="button" onclick={loadAnalysis} disabled={analysisLoading}>{$t("league.refresh")}</button>+ </div>+ {/if}{#if (phase === "ChampSelect" || phase === "InProgress") && scoutPlayers.length > 0}<section class="card">@@ -580,7 +755,105 @@</div></section>{/if}+ {/if}++ {#if tab === "live"}+ {#if liveMetrics?.players?.length}+ <section class="card">+ <div class="card-head">+ <h3>{$t("league.gold_title")}</h3>+ <span class="phase-tag">{formatGameTime(liveMetrics.gameTime ?? 0)}</span>+ </div>+ <div class="gold-summary">+ <span class="gold-team">{$t("league.your_team")}: <strong>{liveMetrics.teamGold?.[myTeam] ?? 0}</strong></span>+ <span class="gold-diff" class:good={teamGoldLead > 0} class:bad={teamGoldLead < 0}>+ {teamGoldLead > 0 ? "+" : ""}{teamGoldLead}+ </span>+ <span class="gold-team">{$t("league.enemy_team")}: <strong>{liveMetrics.teamGold?.[enemyTeam] ?? 0}</strong></span>+ </div>+ <div class="metric-table" role="table">+ <div class="metric-head" role="row">+ <span role="columnheader">{$t("league.col_player")}</span>+ <span role="columnheader">KDA</span>+ <span role="columnheader">CS</span>+ <span role="columnheader">{$t("league.col_gold")}</span>+ <span role="columnheader">{$t("league.col_diff")}</span>+ </div>+ {#each liveMetrics.players as row (row.riotId)}+ <div class="metric-row" role="row" class:self={row.isSelf}>+ <span class="metric-name" role="cell">+ <span class="pos-chip">{(row.position ?? "?").slice(0, 3)}</span>+ {row.championName}+ </span>+ <span role="cell">{row.kills}/{row.deaths}/{row.assists}</span>+ <span role="cell">{row.cs} <span class="dim">({row.csPerMin}/m)</span></span>+ <span role="cell">{row.itemGold}</span>+ <span role="cell" class="diff" class:good={(row.goldDiff ?? 0) > 0} class:bad={(row.goldDiff ?? 0) < 0}>+ {#if row.goldDiff !== undefined && row.goldDiff !== null}+ {row.goldDiff > 0 ? "+" : ""}{row.goldDiff}g+ <span class="dim">{(row.csDiff ?? 0) > 0 ? "+" : ""}{Math.round(row.csDiff ?? 0)}cs</span>+ {:else}—{/if}+ </span>+ </div>+ {/each}+ </div>+ </section>++ {#if selfRow}+ <section class="card">+ <div class="card-head">+ <h3>{$t("league.goals_live")}</h3>+ <span class="phase-tag">{selfRow.position ?? "?"}</span>+ </div>+ <div class="goal-list">+ {#each liveGoals as goal (goal.key)}+ <div class="goal-row">+ <span class="goal-name">{$t(goal.labelKey)}</span>+ <div class="goal-bar"><div class="goal-fill" class:met={goal.ratio >= 1} style={`width:${Math.min(goal.ratio * 100, 100)}%`}></div></div>+ <span class="goal-value" class:met={goal.ratio >= 1}>{goal.current} <span class="dim">/ {goal.target}</span></span>+ </div>+ {/each}+ </div>+ </section>+ {/if}+ {:else}+ <div class="guard-card">+ <p>{$t("league.gold_unavailable")}</p>+ </div>+ {/if}+ {/if}++ {#if tab === "goals"}+ <section class="card">+ <div class="card-head">+ <h3>{$t("league.goals_title")}</h3>+ <select class="select-role" bind:value={goalRole} aria-label={$t("league.goals_role") as string}>+ {#each ROLES as r (r)}+ <option value={r}>{$t(`league.role_${r.toLowerCase()}`)}</option>+ {/each}+ </select>+ </div>+ <p class="win-disclaimer">{$t("league.goals_desc")}</p>+ <div class="goal-config">+ {#each GOAL_FIELDS as field (field.key)}+ <label class="goal-field">+ <span class="goal-field-label">{$t(field.labelKey)}</span>+ <input+ type="number"+ class="input-text"+ min="0"+ step={field.step}+ value={goalValue(goalRole, field.key)}+ onchange={(e) => setGoal(goalRole, field.key, Number(e.currentTarget.value))}+ />+ </label>+ {/each}+ </div>+ <button class="button" onclick={() => resetGoals(goalRole)}>{$t("league.goals_reset")}</button>+ </section>+ {/if}+ {#if tab === "automation"}<section class="card"><div class="card-head"><h3>{$t("league.automation_title")}</h3>@@ -682,6 +955,9 @@{/if}</section>+ {/if}++ {#if tab === "history"}<section class="history-section"><div class="history-head"><h3>{$t("league.history_title")}</h3>@@ -706,6 +982,7 @@</div>{/if}</section>+ {/if}{/if}{/if}</div>@@ -1145,6 +1422,261 @@outline: none;}+ .league-tabs {+ display: flex;+ gap: 4px;+ flex-wrap: wrap;+ padding-bottom: 2px;+ border-bottom: 1px solid var(--border);+ }++ .league-tab {+ padding: 6px 12px;+ font-size: 12.5px;+ background: none;+ border: none;+ border-bottom: 2px solid transparent;+ color: var(--gray);+ cursor: pointer;+ }++ .league-tab:hover {+ color: var(--text);+ }++ .league-tab.on {+ color: var(--text);+ border-bottom-color: var(--accent);+ }++ .league-tab:focus-visible {+ outline: 1px solid var(--accent);+ outline-offset: -1px;+ }++ .winbar-wrap {+ display: flex;+ flex-direction: column;+ gap: 6px;+ }++ .winbar {+ position: relative;+ height: 12px;+ border-radius: 999px;+ background: var(--button);+ border: 1px solid var(--input-border);+ overflow: hidden;+ }++ .winbar-fill {+ height: 100%;+ background: var(--accent);+ }++ .winbar-range {+ position: absolute;+ top: 0;+ height: 100%;+ background: var(--accent);+ opacity: 0.25;+ }++ .winbar-legend {+ display: flex;+ align-items: baseline;+ gap: 10px;+ }++ .win-value {+ font-size: 22px;+ font-weight: 600;+ font-variant-numeric: tabular-nums;+ }++ .win-range,+ .win-note {+ font-size: 12px;+ color: var(--gray);+ }++ .win-note {+ margin: 8px 0 0;+ }++ .win-disclaimer {+ margin: 4px 0 0;+ font-size: 11.5px;+ color: var(--gray);+ line-height: 1.45;+ }++ .premade-row {+ display: flex;+ align-items: center;+ gap: 6px;+ flex-wrap: wrap;+ margin-top: 10px;+ }++ .gold-summary {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 14px;+ margin-bottom: 10px;+ font-size: 13px;+ flex-wrap: wrap;+ }++ .gold-team {+ color: var(--gray);+ }++ .gold-diff {+ font-size: 17px;+ font-weight: 600;+ font-variant-numeric: tabular-nums;+ }++ .gold-diff.good,+ .diff.good {+ color: var(--success);+ }++ .gold-diff.bad,+ .diff.bad {+ color: var(--danger);+ }++ .metric-table {+ display: flex;+ flex-direction: column;+ gap: 2px;+ overflow-x: auto;+ }++ .metric-head,+ .metric-row {+ display: grid;+ grid-template-columns: minmax(120px, 1.6fr) 68px 92px 64px minmax(110px, 1fr);+ gap: 8px;+ align-items: center;+ padding: 5px 7px;+ font-size: 12px;+ font-variant-numeric: tabular-nums;+ min-width: 460px;+ }++ .metric-head {+ color: var(--gray);+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ }++ .metric-row {+ border-radius: calc(var(--border-radius) - 4px);+ background: var(--button);+ }++ .metric-row.self {+ background: var(--accent-soft, var(--surface));+ }++ .metric-name {+ display: flex;+ align-items: center;+ gap: 6px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .pos-chip {+ font-size: 9.5px;+ padding: 1px 5px;+ border-radius: 4px;+ background: var(--surface);+ color: var(--gray);+ letter-spacing: 0.03em;+ }++ .dim {+ color: var(--gray);+ }++ .goal-list {+ display: flex;+ flex-direction: column;+ gap: 8px;+ }++ .goal-row {+ display: grid;+ grid-template-columns: minmax(80px, 1fr) minmax(90px, 2fr) minmax(90px, 1fr);+ gap: 10px;+ align-items: center;+ font-size: 12.5px;+ }++ .goal-name {+ color: var(--gray);+ }++ .goal-bar {+ height: 8px;+ border-radius: 999px;+ background: var(--button);+ border: 1px solid var(--input-border);+ overflow: hidden;+ }++ .goal-fill {+ height: 100%;+ background: var(--gray);+ }++ .goal-fill.met {+ background: var(--success);+ }++ .goal-value {+ text-align: right;+ font-variant-numeric: tabular-nums;+ }++ .goal-value.met {+ color: var(--success);+ }++ .goal-config {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));+ gap: 10px;+ margin: 10px 0;+ }++ .goal-field {+ display: flex;+ flex-direction: column;+ gap: 4px;+ }++ .goal-field-label {+ font-size: 12px;+ color: var(--gray);+ }++ .select-role {+ padding: 5px 10px;+ font-size: 12.5px;+ background: var(--button);+ border: 1px solid var(--input-border);+ border-radius: calc(var(--border-radius) - 2px);+ color: var(--text);+ }+.scout-teams {display: grid;grid-template-columns: 1fr 1fr;