Skip to content

Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.

feat(league): estimar o retorno dos objetivos e listar os eventos da partida (#254)

antonio7274c62445cb
diff --git a/src-tauri/src/commands/league/live.rs b/src-tauri/src/commands/league/live.rs
new file mode 100644
index 00000000..fc7f208c
--- /dev/null
+++ b/src-tauri/src/commands/league/live.rs
@@ -0,0 +1,239 @@
+use serde::Serialize;
+use serde_json::Value;
+
+/// Respawn windows are balance constants and move between patches, so every
+/// number derived from them is presented as an estimate.
+const BARON_RESPAWN: f64 = 360.0;
+const DRAGON_RESPAWN: f64 = 300.0;
+const INHIBITOR_RESPAWN: f64 = 300.0;
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct ObjectiveTimer {
+ pub kind: &'static str,
+ pub killed_at: f64,
+ pub respawns_at: f64,
+ pub remaining: f64,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct GameEvent {
+ pub id: i64,
+ pub name: String,
+ pub at: f64,
+ pub actor: Option<String>,
+ pub target: Option<String>,
+ pub detail: Option<String>,
+}
+
+fn event_time(event: &Value) -> Option<f64> {
+ event.get("EventTime").and_then(Value::as_f64)
+}
+
+fn text(event: &Value, key: &str) -> Option<String> {
+ event
+ .get(key)
+ .and_then(Value::as_str)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string)
+}
+
+fn last_kill_time(events: &[Value], name: &str) -> Option<f64> {
+ events
+ .iter()
+ .filter(|e| event_name(e) == name)
+ .filter_map(event_time)
+ .fold(None, |acc: Option<f64>, t| {
+ Some(acc.map_or(t, |a| a.max(t)))
+ })
+}
+
+fn event_name(event: &Value) -> &str {
+ event.get("EventName").and_then(Value::as_str).unwrap_or("")
+}
+
+/// Turns the kill events into "when does it come back" timers. Objectives whose
+/// window already elapsed are dropped: an expired timer says nothing the map
+/// doesn't already show.
+pub fn objective_timers(events: &[Value], game_time: f64) -> Vec<ObjectiveTimer> {
+ let mut timers = Vec::new();
+ for (kind, event, window) in [
+ ("baron", "BaronKill", BARON_RESPAWN),
+ ("dragon", "DragonKill", DRAGON_RESPAWN),
+ ("inhibitor", "InhibKilled", INHIBITOR_RESPAWN),
+ ] {
+ if let Some(killed_at) = last_kill_time(events, event) {
+ let respawns_at = killed_at + window;
+ let remaining = respawns_at - game_time;
+ if remaining > 0.0 {
+ timers.push(ObjectiveTimer {
+ kind,
+ killed_at,
+ respawns_at,
+ remaining,
+ });
+ }
+ }
+ }
+ timers.sort_by(|a, b| a.remaining.total_cmp(&b.remaining));
+ timers
+}
+
+/// Normalises the raw event list into a feed the UI can render without knowing
+/// the shape of every event type.
+pub fn game_events(events: &[Value], limit: usize) -> Vec<GameEvent> {
+ let mut feed: Vec<GameEvent> = events
+ .iter()
+ .filter_map(|event| {
+ let name = event_name(event);
+ if name.is_empty() {
+ return None;
+ }
+ let (actor, target, detail) = match name {
+ "ChampionKill" => (
+ text(event, "KillerName"),
+ text(event, "VictimName"),
+ assist_count(event),
+ ),
+ "TurretKilled" => (text(event, "KillerName"), text(event, "TurretKilled"), None),
+ "InhibKilled" | "InhibRespawned" | "InhibRespawningSoon" => {
+ (text(event, "KillerName"), text(event, "InhibKilled"), None)
+ }
+ "DragonKill" => (
+ text(event, "KillerName"),
+ None,
+ text(event, "DragonType").or_else(|| stolen(event)),
+ ),
+ "BaronKill" | "HeraldKill" => (text(event, "KillerName"), None, stolen(event)),
+ "Multikill" => (
+ text(event, "KillerName"),
+ None,
+ event
+ .get("KillStreak")
+ .and_then(Value::as_i64)
+ .map(|n| n.to_string()),
+ ),
+ "Ace" => (text(event, "Acer"), None, text(event, "AcingTeam")),
+ "FirstBrick" | "FirstBlood" => (
+ text(event, "KillerName").or_else(|| text(event, "Recipient")),
+ None,
+ None,
+ ),
+ _ => (text(event, "KillerName"), None, None),
+ };
+ Some(GameEvent {
+ id: event.get("EventID").and_then(Value::as_i64).unwrap_or(-1),
+ name: name.to_string(),
+ at: event_time(event).unwrap_or(0.0),
+ actor,
+ target,
+ detail,
+ })
+ })
+ .collect();
+ // Newest first, and the client is not guaranteed to keep them ordered.
+ feed.sort_by(|a, b| b.at.total_cmp(&a.at).then(b.id.cmp(&a.id)));
+ feed.truncate(limit);
+ feed
+}
+
+fn stolen(event: &Value) -> Option<String> {
+ match event.get("Stolen") {
+ Some(Value::String(s)) if s.eq_ignore_ascii_case("true") => Some("stolen".to_string()),
+ Some(Value::Bool(true)) => Some("stolen".to_string()),
+ _ => None,
+ }
+}
+
+fn assist_count(event: &Value) -> Option<String> {
+ let count = event
+ .get("Assisters")
+ .and_then(Value::as_array)
+ .map(|a| a.len())
+ .unwrap_or(0);
+ if count > 0 {
+ Some(count.to_string())
+ } else {
+ None
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn events() -> Vec<Value> {
+ vec![
+ json!({ "EventID": 0, "EventName": "GameStart", "EventTime": 0.05 }),
+ json!({ "EventID": 1, "EventName": "DragonKill", "EventTime": 320.0, "KillerName": "Ally1", "DragonType": "Infernal", "Stolen": "False" }),
+ json!({ "EventID": 2, "EventName": "BaronKill", "EventTime": 1300.0, "KillerName": "Enemy3", "Stolen": "True" }),
+ json!({ "EventID": 3, "EventName": "DragonKill", "EventTime": 1400.0, "KillerName": "Enemy2", "DragonType": "Ocean", "Stolen": "False" }),
+ json!({ "EventID": 4, "EventName": "ChampionKill", "EventTime": 1450.0, "KillerName": "Ally2", "VictimName": "Enemy1", "Assisters": ["Ally3", "Ally4"] }),
+ ]
+ }
+
+ #[test]
+ fn the_latest_kill_drives_each_objective_timer() {
+ let timers = objective_timers(&events(), 1500.0);
+ // Dragon at 1400 (not the one at 320) + 300 = 1700, so 200s left.
+ let dragon = timers.iter().find(|t| t.kind == "dragon").expect("dragon");
+ assert_eq!(dragon.killed_at, 1400.0);
+ assert_eq!(dragon.respawns_at, 1700.0);
+ assert_eq!(dragon.remaining, 200.0);
+ // Baron at 1300 + 360 = 1660, so 160s left, and it sorts first.
+ assert_eq!(timers[0].kind, "baron");
+ assert_eq!(timers[0].remaining, 160.0);
+ }
+
+ #[test]
+ fn elapsed_windows_are_dropped_rather_than_shown_as_negative() {
+ // Long past both windows: nothing pending.
+ assert!(objective_timers(&events(), 5000.0).is_empty());
+ // No kills at all.
+ assert!(objective_timers(&[], 100.0).is_empty());
+ }
+
+ #[test]
+ fn an_objective_that_never_died_has_no_timer() {
+ let timers = objective_timers(&events(), 1500.0);
+ assert!(timers.iter().all(|t| t.kind != "inhibitor"));
+ }
+
+ #[test]
+ fn the_feed_is_newest_first_and_capped() {
+ let feed = game_events(&events(), 3);
+ assert_eq!(feed.len(), 3);
+ assert_eq!(feed[0].name, "ChampionKill");
+ assert_eq!(feed[0].actor.as_deref(), Some("Ally2"));
+ assert_eq!(feed[0].target.as_deref(), Some("Enemy1"));
+ assert_eq!(feed[0].detail.as_deref(), Some("2"));
+ assert_eq!(feed[1].name, "DragonKill");
+ }
+
+ #[test]
+ fn a_stolen_objective_is_flagged_and_a_clean_one_is_not() {
+ let feed = game_events(&events(), 10);
+ let baron = feed.iter().find(|e| e.name == "BaronKill").expect("baron");
+ assert_eq!(baron.detail.as_deref(), Some("stolen"));
+ let dragon = feed
+ .iter()
+ .find(|e| e.name == "DragonKill" && e.at == 320.0)
+ .expect("dragon");
+ assert_eq!(dragon.detail.as_deref(), Some("Infernal"));
+ }
+
+ #[test]
+ fn malformed_events_are_skipped_instead_of_panicking() {
+ let messy = vec![
+ json!({}),
+ json!({ "EventName": "" }),
+ json!({ "EventName": "ChampionKill" }),
+ Value::Null,
+ ];
+ let feed = game_events(&messy, 10);
+ assert_eq!(feed.len(), 1);
+ assert_eq!(feed[0].at, 0.0);
+ assert_eq!(feed[0].id, -1);
+ assert!(objective_timers(&messy, 10.0).is_empty());
+ }
+}
diff --git a/src-tauri/src/commands/league/mod.rs b/src-tauri/src/commands/league/mod.rs
index 483720dc..4541c853 100644
--- a/src-tauri/src/commands/league/mod.rs
+++ b/src-tauri/src/commands/league/mod.rs
@@ -1,4 +1,5 @@
pub mod analysis;
+pub mod live;
pub mod locator;
pub mod stats;
pub mod ws;
@@ -1210,6 +1211,49 @@ pub async fn league_match_analysis() -> Result<Value, String> {
}))
}
+/// Objective respawn estimates and a readable feed of what just happened,
+/// derived from the in-game event log.
+#[tauri::command]
+pub async fn league_live_events() -> Result<Value, String> {
+ ensure_enabled()?;
+ let http = http_client()?;
+ let base = "https://127.0.0.1:2999/liveclientdata";
+ let raw = http
+ .get(format!("{}/eventdata", 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 game_time = http
+ .get(format!("{}/gamestats", base))
+ .send()
+ .await
+ .ok()
+ .and_then(|r| r.error_for_status().ok());
+ let game_time = match game_time {
+ Some(response) => response
+ .json::<Value>()
+ .await
+ .ok()
+ .and_then(|v| v.get("gameTime").and_then(Value::as_f64))
+ .unwrap_or(0.0),
+ None => 0.0,
+ };
+ let events: Vec<Value> = raw
+ .get("Events")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+
+ Ok(json!({
+ "gameTime": game_time,
+ "objectives": live::objective_timers(&events, game_time),
+ "events": live::game_events(&events, 12),
+ }))
+}
+
/// 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]
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 0b250f04..5389cbd5 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -829,6 +829,7 @@ pub fn run() {
commands::league::league_game_players,
commands::league::league_player_report,
commands::league::league_match_analysis,
+ commands::league::league_live_events,
commands::league::league_live_metrics,
commands::league::league_search_player,
commands::league::league_duos,
diff --git a/src/components/league/HistoryTab.svelte b/src/components/league/HistoryTab.svelte
index 5f639c16..05246c15 100644
--- a/src/components/league/HistoryTab.svelte
+++ b/src/components/league/HistoryTab.svelte
@@ -3,6 +3,7 @@
import { t, locale } from "$lib/i18n";
import timeAgo from "$lib/time-ago";
import { CDRAGON, type Champion } from "./shared";
+ import { filterByQueue, queuesInGames, summarise } from "$lib/league-history";
let {
games,
@@ -31,6 +32,19 @@
return QUEUE_NAMES[id] ?? mode ?? "";
}
+ let queueFilter = $state<number | null>(null);
+ let availableQueues = $derived(queuesInGames(games));
+ let visibleGames = $derived(filterByQueue(games, queueFilter));
+ let summary = $derived(summarise(visibleGames));
+
+ $effect(() => {
+ // A filter kept after a refresh that no longer has the queue would show an
+ // empty list with no explanation.
+ if (queueFilter !== null && !availableQueues.includes(queueFilter)) {
+ queueFilter = null;
+ }
+ });
+
function playerStats(game: any): { championId: number; kills: number; deaths: number; assists: number; win: boolean } {
const p = game?.participants?.[0];
return {
@@ -100,8 +114,33 @@
{#if games.length === 0}
<p class="empty-hint">{$t("league.history_empty")}</p>
{:else}
+ {#if availableQueues.length > 1}
+ <div class="queue-filter" role="group" aria-label={$t("league.filter_queue") as string}>
+ <button class="queue-chip" class:on={queueFilter === null} onclick={() => (queueFilter = null)} aria-pressed={queueFilter === null}>
+ {$t("league.filter_all")}
+ </button>
+ {#each availableQueues as id (id)}
+ <button class="queue-chip" class:on={queueFilter === id} onclick={() => (queueFilter = id)} aria-pressed={queueFilter === id}>
+ {queueName(id, "")}
+ </button>
+ {/each}
+ </div>
+ {/if}
+ <p class="history-summary">
+ {summary.counted}
+ {$t("league.summary_games")}
+ {#if summary.winrate !== null}
+ · <strong>{summary.wins}{$t("league.summary_win_short")} {summary.losses}{$t("league.summary_loss_short")}</strong> · {summary.winrate}%
+ {/if}
+ {#if summary.kda !== null}
+ · KDA {summary.kda.toFixed(2)}
+ {/if}
+ {#if summary.remakes > 0}
+ · <span class="dim">{summary.remakes} {$t("league.summary_remakes")}</span>
+ {/if}
+ </p>
<div class="game-list">
- {#each games as game (game.gameId)}
+ {#each visibleGames as game (game.gameId)}
{@const p = playerStats(game)}
<button
class="game-row"
diff --git a/src/components/league/LiveTab.svelte b/src/components/league/LiveTab.svelte
index 547f3e2d..b77efa53 100644
--- a/src/components/league/LiveTab.svelte
+++ b/src/components/league/LiveTab.svelte
@@ -5,10 +5,12 @@
let {
liveMetrics,
cooldowns,
+ liveEvents,
goalValue,
}: {
liveMetrics: any;
cooldowns: any;
+ liveEvents: any;
goalValue: (role: Role, key: GoalKey) => number;
} = $props();
@@ -96,6 +98,49 @@
if (!end) return null;
return Math.max(0, Math.ceil((end - timerNow) / 1000));
}
+
+ // The objective payload only refreshes every few seconds, so the countdown is
+ // continued locally instead of jumping in steps.
+ let eventsFetchedAt = $state(Date.now());
+ let objectiveNow = $state(Date.now());
+
+ $effect(() => {
+ void liveEvents;
+ eventsFetchedAt = Date.now();
+ objectiveNow = Date.now();
+ });
+
+ $effect(() => {
+ if (!liveEvents?.objectives?.length) return;
+ const tick = setInterval(() => {
+ objectiveNow = Date.now();
+ }, 1000);
+ return () => clearInterval(tick);
+ });
+
+ let objectives = $derived.by(() => {
+ const elapsed = (objectiveNow - eventsFetchedAt) / 1000;
+ return (liveEvents?.objectives ?? [])
+ .map((o: any) => ({ ...o, left: Math.max(0, Math.round(o.remaining - elapsed)) }))
+ .filter((o: any) => o.left > 0);
+ });
+
+ const EVENT_LABELS: Record<string, string> = {
+ ChampionKill: "league.event_kill",
+ TurretKilled: "league.event_turret",
+ InhibKilled: "league.event_inhib",
+ DragonKill: "league.event_dragon",
+ BaronKill: "league.event_baron",
+ HeraldKill: "league.event_herald",
+ Multikill: "league.event_multikill",
+ Ace: "league.event_ace",
+ FirstBrick: "league.event_first_turret",
+ FirstBlood: "league.event_first_blood",
+ };
+
+ let feed = $derived(
+ (liveEvents?.events ?? []).filter((e: any) => EVENT_LABELS[e.name])
+ );
</script>
{#if liveMetrics?.players?.length}
@@ -191,6 +236,40 @@
</section>
{/if}
+ {#if objectives.length > 0 || feed.length > 0}
+ <section class="card">
+ <div class="card-head">
+ <h3>{$t("league.objectives_title")}</h3>
+ </div>
+ {#if objectives.length > 0}
+ <div class="objective-row">
+ {#each objectives as objective (objective.kind)}
+ <span class="objective-chip">
+ <strong>{$t(`league.objective_${objective.kind}`)}</strong>
+ {formatGameTime(objective.left)}
+ </span>
+ {/each}
+ </div>
+ <p class="win-disclaimer">{$t("league.objectives_estimate")}</p>
+ {/if}
+ {#if feed.length > 0}
+ <ul class="event-feed">
+ {#each feed as event (`${event.id}:${event.at}`)}
+ <li class="event-item">
+ <span class="event-time">{formatGameTime(event.at)}</span>
+ <span class="event-text">
+ {$t(EVENT_LABELS[event.name])}
+ {#if event.actor}<strong>{event.actor}</strong>{/if}
+ {#if event.target}<span class="dim">→ {event.target}</span>{/if}
+ {#if event.detail}<span class="dim">({event.detail})</span>{/if}
+ </span>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ </section>
+ {/if}
+
{#if selfRow}
<section class="card">
<div class="card-head">
diff --git a/src/lib/i18n/el.json b/src/lib/i18n/el.json
index 61fb9275..54eb357b 100644
--- a/src/lib/i18n/el.json
+++ b/src/lib/i18n/el.json
@@ -115,6 +115,21 @@
"premade_source_party": "Από τα δεδομένα του παιχνιδιού",
"premade_source_history": "Εκτίμηση από κοινό ιστορικό",
"players": "παίκτες",
+ "objectives_title": "Στόχοι και συμβάντα",
+ "objectives_estimate": "Οι χρόνοι επανεμφάνισης είναι εκτιμήσεις για το τρέχον patch, όχι τιμές από το παιχνίδι.",
+ "objective_baron": "Βαρόνος",
+ "objective_dragon": "Δράκος",
+ "objective_inhibitor": "Αναστολέας",
+ "event_kill": "Εξόντωση:",
+ "event_turret": "Πύργος έπεσε:",
+ "event_inhib": "Αναστολέας έπεσε:",
+ "event_dragon": "Δράκος από",
+ "event_baron": "Βαρόνος από",
+ "event_herald": "Herald από",
+ "event_multikill": "Πολλαπλή εξόντωση:",
+ "event_ace": "Ace από",
+ "event_first_turret": "Πρώτος πύργος:",
+ "event_first_blood": "Πρώτο αίμα:",
"gold_title": "Ζωντανή οικονομία",
"gold_unavailable": "Μπες σε αγώνα για να δεις χρυσό και διαφορές lane.",
"your_team": "Η ομάδα σου",
@@ -236,6 +251,12 @@
"ranked_flex": "Κατάταξη Flex",
"unranked": "Χωρίς κατάταξη",
"history_title": "Πρόσφατοι αγώνες",
+ "filter_queue": "Φίλτρο ανά ουρά",
+ "filter_all": "Όλες",
+ "summary_games": "παιχνίδια",
+ "summary_win_short": "Ν",
+ "summary_loss_short": "Η",
+ "summary_remakes": "τα remakes δεν μετρούν",
"history_empty": "Δεν βρέθηκαν αγώνες ακόμα.",
"refresh": "Ανανέωση",
"victory": "Νίκη",
diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json
index 47a65874..4ebeb8f4 100644
--- a/src/lib/i18n/en.json
+++ b/src/lib/i18n/en.json
@@ -133,6 +133,21 @@
"premade_source_party": "Reported by the game",
"premade_source_history": "Estimated from shared history",
"players": "players",
+ "objectives_title": "Objectives and events",
+ "objectives_estimate": "Respawn windows are estimates based on the current patch, not values reported by the game.",
+ "objective_baron": "Baron",
+ "objective_dragon": "Dragon",
+ "objective_inhibitor": "Inhibitor",
+ "event_kill": "Kill:",
+ "event_turret": "Turret down:",
+ "event_inhib": "Inhibitor down:",
+ "event_dragon": "Dragon taken by",
+ "event_baron": "Baron taken by",
+ "event_herald": "Herald taken by",
+ "event_multikill": "Multikill:",
+ "event_ace": "Ace by",
+ "event_first_turret": "First turret:",
+ "event_first_blood": "First blood:",
"gold_title": "Live economy",
"gold_unavailable": "Open a game to see live gold and lane differences.",
"your_team": "Your team",
@@ -254,6 +269,12 @@
"ranked_flex": "Ranked Flex",
"unranked": "Unranked",
"history_title": "Recent matches",
+ "filter_queue": "Filter by queue",
+ "filter_all": "All",
+ "summary_games": "games",
+ "summary_win_short": "W",
+ "summary_loss_short": "L",
+ "summary_remakes": "remakes not counted",
"history_empty": "No matches found yet.",
"refresh": "Refresh",
"victory": "Victory",
diff --git a/src/lib/i18n/es.json b/src/lib/i18n/es.json
index 7886535e..4db8f9db 100644
--- a/src/lib/i18n/es.json
+++ b/src/lib/i18n/es.json
@@ -115,6 +115,21 @@
"premade_source_party": "Informado por el juego",
"premade_source_history": "Estimado por el historial compartido",
"players": "jugadores",
+ "objectives_title": "Objetivos y eventos",
+ "objectives_estimate": "Los tiempos de reaparición son estimaciones del parche actual, no valores informados por el juego.",
+ "objective_baron": "Barón",
+ "objective_dragon": "Dragón",
+ "objective_inhibitor": "Inhibidor",
+ "event_kill": "Baja:",
+ "event_turret": "Torre destruida:",
+ "event_inhib": "Inhibidor destruido:",
+ "event_dragon": "Dragón derrotado por",
+ "event_baron": "Barón derrotado por",
+ "event_herald": "Heraldo derrotado por",
+ "event_multikill": "Multiasesinato:",
+ "event_ace": "Ace de",
+ "event_first_turret": "Primera torre:",
+ "event_first_blood": "Primera sangre:",
"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",
@@ -236,6 +251,12 @@
"ranked_flex": "Clasificatoria Flexible",
"unranked": "Sin clasificar",
"history_title": "Partidas recientes",
+ "filter_queue": "Filtrar por cola",
+ "filter_all": "Todas",
+ "summary_games": "partidas",
+ "summary_win_short": "V",
+ "summary_loss_short": "D",
+ "summary_remakes": "remakes no contados",
"history_empty": "Aún no se han encontrado partidas.",
"refresh": "Actualizar",
"victory": "Victoria",
diff --git a/src/lib/i18n/fr.json b/src/lib/i18n/fr.json
index df3d21e1..3bee073a 100644
--- a/src/lib/i18n/fr.json
+++ b/src/lib/i18n/fr.json
@@ -115,6 +115,21 @@
"premade_source_party": "Indiqué par le jeu",
"premade_source_history": "Estimé d'après l'historique commun",
"players": "joueurs",
+ "objectives_title": "Objectifs et événements",
+ "objectives_estimate": "Les temps de réapparition sont des estimations basées sur le patch actuel, pas des valeurs fournies par le jeu.",
+ "objective_baron": "Baron",
+ "objective_dragon": "Dragon",
+ "objective_inhibitor": "Inhibiteur",
+ "event_kill": "Élimination :",
+ "event_turret": "Tourelle détruite :",
+ "event_inhib": "Inhibiteur détruit :",
+ "event_dragon": "Dragon tué par",
+ "event_baron": "Baron tué par",
+ "event_herald": "Héraut tué par",
+ "event_multikill": "Multi-kill :",
+ "event_ace": "Ace de",
+ "event_first_turret": "Première tourelle :",
+ "event_first_blood": "Premier sang :",
"gold_title": "Économie en direct",
"gold_unavailable": "Lancez une partie pour voir l'or et les écarts de voie.",
"your_team": "Votre équipe",
@@ -236,6 +251,12 @@
"ranked_flex": "Classée Flexible",
"unranked": "Non classé",
"history_title": "Parties récentes",
+ "filter_queue": "Filtrer par file",
+ "filter_all": "Toutes",
+ "summary_games": "parties",
+ "summary_win_short": "V",
+ "summary_loss_short": "D",
+ "summary_remakes": "remakes non comptés",
"history_empty": "Aucune partie trouvée pour l'instant.",
"refresh": "Actualiser",
"victory": "Victoire",
diff --git a/src/lib/i18n/it.json b/src/lib/i18n/it.json
index 6a2c3f5a..f979d121 100644
--- a/src/lib/i18n/it.json
+++ b/src/lib/i18n/it.json
@@ -115,6 +115,21 @@
"premade_source_party": "Riportato dal gioco",
"premade_source_history": "Stimato dalla cronologia condivisa",
"players": "giocatori",
+ "objectives_title": "Obiettivi ed eventi",
+ "objectives_estimate": "I tempi di ricomparsa sono stime basate sulla patch attuale, non valori forniti dal gioco.",
+ "objective_baron": "Barone",
+ "objective_dragon": "Drago",
+ "objective_inhibitor": "Inibitore",
+ "event_kill": "Uccisione:",
+ "event_turret": "Torre distrutta:",
+ "event_inhib": "Inibitore distrutto:",
+ "event_dragon": "Drago preso da",
+ "event_baron": "Barone preso da",
+ "event_herald": "Araldo preso da",
+ "event_multikill": "Multiuccisione:",
+ "event_ace": "Ace di",
+ "event_first_turret": "Prima torre:",
+ "event_first_blood": "Primo sangue:",
"gold_title": "Economia in diretta",
"gold_unavailable": "Entra in partita per vedere oro e differenze di corsia.",
"your_team": "La tua squadra",
@@ -236,6 +251,12 @@
"ranked_flex": "Classificata Flessibile",
"unranked": "Non classificato",
"history_title": "Partite recenti",
+ "filter_queue": "Filtra per coda",
+ "filter_all": "Tutte",
+ "summary_games": "partite",
+ "summary_win_short": "V",
+ "summary_loss_short": "S",
+ "summary_remakes": "remake non conteggiati",
"history_empty": "Nessuna partita trovata finora.",
"refresh": "Aggiorna",
"victory": "Vittoria",
diff --git a/src/lib/i18n/ja.json b/src/lib/i18n/ja.json
index d81f5120..bcb90452 100644
--- a/src/lib/i18n/ja.json
+++ b/src/lib/i18n/ja.json
@@ -115,6 +115,21 @@
"premade_source_party": "ゲームからの情報",
"premade_source_history": "共通の試合履歴からの推定",
"players": "人",
+ "objectives_title": "オブジェクトとイベント",
+ "objectives_estimate": "リスポーン時間は現行パッチに基づく推定値で、ゲームから提供された値ではありません。",
+ "objective_baron": "バロン",
+ "objective_dragon": "ドラゴン",
+ "objective_inhibitor": "インヒビター",
+ "event_kill": "キル:",
+ "event_turret": "タワー破壊:",
+ "event_inhib": "インヒビター破壊:",
+ "event_dragon": "ドラゴン討伐",
+ "event_baron": "バロン討伐",
+ "event_herald": "ヘラルド討伐",
+ "event_multikill": "マルチキル:",
+ "event_ace": "エース",
+ "event_first_turret": "ファーストタワー:",
+ "event_first_blood": "ファーストブラッド:",
"gold_title": "ライブ経済",
"gold_unavailable": "試合に入るとゴールドとレーン差が表示されます。",
"your_team": "自チーム",
@@ -236,6 +251,12 @@
"ranked_flex": "ランク フレックス",
"unranked": "アンランク",
"history_title": "最近のマッチ",
+ "filter_queue": "キューで絞り込む",
+ "filter_all": "すべて",
+ "summary_games": "試合",
+ "summary_win_short": "勝",
+ "summary_loss_short": "敗",
+ "summary_remakes": "リメイクは除外",
"history_empty": "まだマッチが見つかりません。",
"refresh": "更新",
"victory": "勝利",
diff --git a/src/lib/i18n/keys.ts b/src/lib/i18n/keys.ts
index 09697343..4a8b1a11 100644
--- a/src/lib/i18n/keys.ts
+++ b/src/lib/i18n/keys.ts
@@ -453,6 +453,18 @@ export type TranslationKeys =
| 'league.duos_title'
| 'league.early_deaths_label'
| 'league.enemy_team'
+ | 'league.event_ace'
+ | 'league.event_baron'
+ | 'league.event_dragon'
+ | 'league.event_first_blood'
+ | 'league.event_first_turret'
+ | 'league.event_herald'
+ | 'league.event_inhib'
+ | 'league.event_kill'
+ | 'league.event_multikill'
+ | 'league.event_turret'
+ | 'league.filter_all'
+ | 'league.filter_queue'
| 'league.games_short'
| 'league.goal_cs'
| 'league.goal_gold'
@@ -482,6 +494,11 @@ export type TranslationKeys =
| 'league.match_damage'
| 'league.match_detail_unavailable'
| 'league.nav'
+ | 'league.objective_baron'
+ | 'league.objective_dragon'
+ | 'league.objective_inhibitor'
+ | 'league.objectives_estimate'
+ | 'league.objectives_title'
| 'league.open_settings'
| 'league.phase_champ_select'
| 'league.phase_end_of_game'
@@ -556,6 +573,10 @@ export type TranslationKeys =
| 'league.start_queue'
| 'league.stat_winrate'
| 'league.stop_queue'
+ | 'league.summary_games'
+ | 'league.summary_loss_short'
+ | 'league.summary_remakes'
+ | 'league.summary_win_short'
| 'league.swap'
| 'league.tab_analysis'
| 'league.tab_automation'
diff --git a/src/lib/i18n/pt.json b/src/lib/i18n/pt.json
index c0a38c7d..e425450a 100644
--- a/src/lib/i18n/pt.json
+++ b/src/lib/i18n/pt.json
@@ -115,6 +115,21 @@
"premade_source_party": "Informado pelo jogo",
"premade_source_history": "Estimado pelo histórico em comum",
"players": "jogadores",
+ "objectives_title": "Objetivos e eventos",
+ "objectives_estimate": "Os tempos de renascimento são estimativas do patch atual, não valores informados pelo jogo.",
+ "objective_baron": "Barão",
+ "objective_dragon": "Dragão",
+ "objective_inhibitor": "Inibidor",
+ "event_kill": "Abate:",
+ "event_turret": "Torre destruída:",
+ "event_inhib": "Inibidor destruído:",
+ "event_dragon": "Dragão morto por",
+ "event_baron": "Barão morto por",
+ "event_herald": "Arauto morto por",
+ "event_multikill": "Multi-abate:",
+ "event_ace": "Ace de",
+ "event_first_turret": "Primeira torre:",
+ "event_first_blood": "Primeiro abate:",
"gold_title": "Economia ao vivo",
"gold_unavailable": "Entre em uma partida para ver ouro e diferenças de lane.",
"your_team": "Seu time",
@@ -236,6 +251,12 @@
"ranked_flex": "Ranqueada Flexível",
"unranked": "Sem ranque",
"history_title": "Partidas recentes",
+ "filter_queue": "Filtrar por fila",
+ "filter_all": "Todas",
+ "summary_games": "partidas",
+ "summary_win_short": "V",
+ "summary_loss_short": "D",
+ "summary_remakes": "remakes não contados",
"history_empty": "Nenhuma partida encontrada ainda.",
"refresh": "Atualizar",
"victory": "Vitória",
diff --git a/src/lib/i18n/ru.json b/src/lib/i18n/ru.json
index 36784846..2b6cb7c8 100644
--- a/src/lib/i18n/ru.json
+++ b/src/lib/i18n/ru.json
@@ -115,6 +115,21 @@
"premade_source_party": "По данным игры",
"premade_source_history": "Оценка по общей истории матчей",
"players": "игроков",
+ "objectives_title": "Цели и события",
+ "objectives_estimate": "Время возрождения — оценка по текущему патчу, а не значение от игры.",
+ "objective_baron": "Барон",
+ "objective_dragon": "Дракон",
+ "objective_inhibitor": "Ингибитор",
+ "event_kill": "Убийство:",
+ "event_turret": "Башня разрушена:",
+ "event_inhib": "Ингибитор разрушен:",
+ "event_dragon": "Дракона забрал",
+ "event_baron": "Барона забрал",
+ "event_herald": "Вестника забрал",
+ "event_multikill": "Мультиубийство:",
+ "event_ace": "Эйс от",
+ "event_first_turret": "Первая башня:",
+ "event_first_blood": "Первая кровь:",
"gold_title": "Экономика в игре",
"gold_unavailable": "Зайдите в игру, чтобы увидеть золото и разницу на линии.",
"your_team": "Ваша команда",
@@ -236,6 +251,12 @@
"ranked_flex": "Ранговая Флекс",
"unranked": "Без ранга",
"history_title": "Недавние матчи",
+ "filter_queue": "Фильтр по режиму",
+ "filter_all": "Все",
+ "summary_games": "матчей",
+ "summary_win_short": "П",
+ "summary_loss_short": "Пр",
+ "summary_remakes": "переигровки не учтены",
"history_empty": "Матчи пока не найдены.",
"refresh": "Обновить",
"victory": "Победа",
diff --git a/src/lib/i18n/zh-TW.json b/src/lib/i18n/zh-TW.json
index 5bd83933..e022505d 100644
--- a/src/lib/i18n/zh-TW.json
+++ b/src/lib/i18n/zh-TW.json
@@ -115,6 +115,21 @@
"premade_source_party": "遊戲提供的資訊",
"premade_source_history": "根據共同戰績推測",
"players": "名玩家",
+ "objectives_title": "目標與事件",
+ "objectives_estimate": "重生時間是根據目前版本的估算,並非遊戲提供的數值。",
+ "objective_baron": "納什男爵",
+ "objective_dragon": "巨龍",
+ "objective_inhibitor": "水晶兵營",
+ "event_kill": "擊殺:",
+ "event_turret": "防禦塔被摧毀:",
+ "event_inhib": "水晶兵營被摧毀:",
+ "event_dragon": "擊殺巨龍",
+ "event_baron": "擊殺男爵",
+ "event_herald": "擊殺峽谷先鋒",
+ "event_multikill": "多殺:",
+ "event_ace": "團滅方",
+ "event_first_turret": "首塔:",
+ "event_first_blood": "一血:",
"gold_title": "即時經濟",
"gold_unavailable": "進入對戰後可查看經濟與對線差距。",
"your_team": "我方",
@@ -236,6 +251,12 @@
"ranked_flex": "彈性積分",
"unranked": "未定位",
"history_title": "最近對戰",
+ "filter_queue": "依隊列篩選",
+ "filter_all": "全部",
+ "summary_games": "場對局",
+ "summary_win_short": "勝",
+ "summary_loss_short": "敗",
+ "summary_remakes": "重開局未計入",
"history_empty": "尚未找到對戰。",
"refresh": "重新整理",
"victory": "勝利",
diff --git a/src/lib/i18n/zh.json b/src/lib/i18n/zh.json
index 5dc87987..1d4750c7 100644
--- a/src/lib/i18n/zh.json
+++ b/src/lib/i18n/zh.json
@@ -115,6 +115,21 @@
"premade_source_party": "游戏提供的信息",
"premade_source_history": "根据共同战绩推测",
"players": "名玩家",
+ "objectives_title": "目标与事件",
+ "objectives_estimate": "重生时间是基于当前版本的估算,并非游戏提供的数值。",
+ "objective_baron": "纳什男爵",
+ "objective_dragon": "巨龙",
+ "objective_inhibitor": "水晶兵营",
+ "event_kill": "击杀:",
+ "event_turret": "防御塔被摧毁:",
+ "event_inhib": "水晶兵营被摧毁:",
+ "event_dragon": "击杀巨龙",
+ "event_baron": "击杀男爵",
+ "event_herald": "击杀峡谷先锋",
+ "event_multikill": "多杀:",
+ "event_ace": "团灭方",
+ "event_first_turret": "首塔:",
+ "event_first_blood": "一血:",
"gold_title": "实时经济",
"gold_unavailable": "进入对局后可查看经济与对线差距。",
"your_team": "我方",
@@ -236,6 +251,12 @@
"ranked_flex": "灵活排位",
"unranked": "未定级",
"history_title": "最近对局",
+ "filter_queue": "按队列筛选",
+ "filter_all": "全部",
+ "summary_games": "场对局",
+ "summary_win_short": "胜",
+ "summary_loss_short": "负",
+ "summary_remakes": "重开局未计入",
"history_empty": "暂未找到对局。",
"refresh": "刷新",
"victory": "胜利",
diff --git a/src/lib/league-history.test.ts b/src/lib/league-history.test.ts
new file mode 100644
index 00000000..81b77348
--- /dev/null
+++ b/src/lib/league-history.test.ts
@@ -0,0 +1,80 @@
+import { describe, it, expect } from "vitest";
+import {
+ filterByQueue,
+ isRemake,
+ queuesInGames,
+ summarise,
+ type HistoryGame,
+} from "./league-history";
+
+function game(
+ queueId: number,
+ win: boolean,
+ kda: [number, number, number] = [5, 2, 5],
+ gameDuration = 1800,
+): HistoryGame {
+ return {
+ queueId,
+ gameDuration,
+ participants: [{ stats: { kills: kda[0], deaths: kda[1], assists: kda[2], win } }],
+ };
+}
+
+describe("queuesInGames", () => {
+ it("lists each queue once, most played first", () => {
+ const games = [game(420, true), game(450, false), game(420, false), game(440, true)];
+ expect(queuesInGames(games)).toEqual([420, 440, 450]);
+ });
+
+ it("ignores games without a usable queue id", () => {
+ expect(queuesInGames([{ queueId: 0 }, {}, { queueId: -1 }])).toEqual([]);
+ expect(queuesInGames([])).toEqual([]);
+ });
+});
+
+describe("filterByQueue", () => {
+ it("returns everything when no queue is selected", () => {
+ const games = [game(420, true), game(450, false)];
+ expect(filterByQueue(games, null)).toHaveLength(2);
+ });
+
+ it("keeps only the selected queue", () => {
+ const games = [game(420, true), game(450, false), game(420, false)];
+ expect(filterByQueue(games, 420)).toHaveLength(2);
+ expect(filterByQueue(games, 900)).toHaveLength(0);
+ });
+});
+
+describe("summarise", () => {
+ it("counts wins, losses and the aggregate KDA", () => {
+ const summary = summarise([
+ game(420, true, [10, 2, 4]),
+ game(420, false, [2, 6, 2]),
+ game(420, true, [6, 2, 6]),
+ ]);
+ expect(summary).toMatchObject({ total: 3, counted: 3, wins: 2, losses: 1, winrate: 67 });
+ // (18 kills + 12 assists) / 10 deaths
+ expect(summary.kda).toBeCloseTo(3, 5);
+ });
+
+ it("leaves remakes out of the aggregates but still counts them", () => {
+ const summary = summarise([game(420, true), game(420, false, [0, 0, 0], 120)]);
+ expect(summary).toMatchObject({ total: 2, counted: 1, wins: 1, losses: 0, remakes: 1 });
+ expect(isRemake(game(420, true, [0, 0, 0], 120))).toBe(true);
+ expect(isRemake(game(420, true))).toBe(false);
+ });
+
+ it("reports nothing instead of dividing by zero on an empty set", () => {
+ expect(summarise([])).toMatchObject({ total: 0, counted: 0, winrate: null, kda: null });
+ });
+
+ it("falls back to the raw sum when the player never died", () => {
+ const summary = summarise([game(420, true, [7, 0, 3])]);
+ expect(summary.kda).toBe(10);
+ });
+
+ it("survives games with no participant data", () => {
+ const summary = summarise([{ queueId: 420, gameDuration: 1800 }]);
+ expect(summary).toMatchObject({ total: 1, counted: 0, winrate: null });
+ });
+});
diff --git a/src/lib/league-history.ts b/src/lib/league-history.ts
new file mode 100644
index 00000000..3ba82f61
--- /dev/null
+++ b/src/lib/league-history.ts
@@ -0,0 +1,77 @@
+export type HistoryGame = {
+ gameId?: number;
+ queueId?: number;
+ gameMode?: string;
+ gameDuration?: number;
+ participants?: { stats?: { kills?: number; deaths?: number; assists?: number; win?: boolean } }[];
+};
+
+export type HistorySummary = {
+ total: number;
+ counted: number;
+ wins: number;
+ losses: number;
+ winrate: number | null;
+ kda: number | null;
+ remakes: number;
+};
+
+/// A game that ended before this mark was a remake: it carries no result worth
+/// averaging, so it is listed but kept out of the aggregates.
+const REMAKE_SECONDS = 180;
+
+export function isRemake(game: HistoryGame): boolean {
+ return (game.gameDuration ?? 0) < REMAKE_SECONDS;
+}
+
+export function queuesInGames(games: readonly HistoryGame[]): number[] {
+ const counts = new Map<number, number>();
+ for (const game of games) {
+ const id = game.queueId;
+ if (typeof id !== "number" || id <= 0) continue;
+ counts.set(id, (counts.get(id) ?? 0) + 1);
+ }
+ return [...counts.entries()]
+ .sort((a, b) => b[1] - a[1] || a[0] - b[0])
+ .map(([id]) => id);
+}
+
+export function filterByQueue<T extends HistoryGame>(games: readonly T[], queueId: number | null): T[] {
+ if (queueId === null) return [...games];
+ return games.filter((game) => game.queueId === queueId);
+}
+
+export function summarise(games: readonly HistoryGame[]): HistorySummary {
+ let wins = 0;
+ let losses = 0;
+ let kills = 0;
+ let deaths = 0;
+ let assists = 0;
+ let remakes = 0;
+
+ for (const game of games) {
+ if (isRemake(game)) {
+ remakes += 1;
+ continue;
+ }
+ const stats = game.participants?.[0]?.stats;
+ if (!stats) continue;
+ if (stats.win) wins += 1;
+ else losses += 1;
+ kills += stats.kills ?? 0;
+ deaths += stats.deaths ?? 0;
+ assists += stats.assists ?? 0;
+ }
+
+ const counted = wins + losses;
+ return {
+ total: games.length,
+ counted,
+ wins,
+ losses,
+ winrate: counted > 0 ? Math.round((wins / counted) * 100) : null,
+ // A deathless streak has no ratio to report, so it falls back to the sum.
+ kda: counted > 0 ? (deaths > 0 ? (kills + assists) / deaths : kills + assists) : null,
+ remakes,
+ };
+}
diff --git a/src/routes/league/+page.svelte b/src/routes/league/+page.svelte
index dbbd6af6..a8570c2b 100644
--- a/src/routes/league/+page.svelte
+++ b/src/routes/league/+page.svelte
@@ -135,6 +135,7 @@
let analysisLoading = $state(false);
let liveMetrics = $state<any>(null);
let cooldowns = $state<any>(null);
+ let liveEvents = $state<any>(null);
const GOALS_KEY = "league-role-goals";
@@ -194,6 +195,14 @@
}
}
+ async function loadLiveEvents() {
+ try {
+ liveEvents = await invoke<any>("league_live_events");
+ } catch {
+ liveEvents = null;
+ }
+ }
+
async function loadCooldowns() {
try {
cooldowns = await invoke<any>("league_ability_cooldowns");
@@ -276,9 +285,11 @@
if (phase === "InProgress") {
loadLiveMetrics();
loadCooldowns();
+ loadLiveEvents();
} else if (liveMetrics) {
liveMetrics = null;
cooldowns = null;
+ liveEvents = null;
}
if (phase === "Lobby" || phase === "Matchmaking") {
try {
@@ -451,7 +462,7 @@
<SearchTab {championById} />
</div>
<div class="tab-panel" class:active={tab === "live"}>
- <LiveTab {liveMetrics} {cooldowns} {goalValue} />
+ <LiveTab {liveMetrics} {cooldowns} {liveEvents} {goalValue} />
</div>
<div class="tab-panel" class:active={tab === "goals"}>
<GoalsTab {goalValue} {setGoal} {resetGoals} />
@@ -820,6 +831,82 @@
color: var(--gray);
}
+ .league-page :global(.queue-filter) {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ margin-bottom: 8px;
+ }
+
+ .league-page :global(.queue-chip) {
+ padding: 3px 10px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ background: transparent;
+ color: var(--text-secondary);
+ font-size: 12px;
+ cursor: pointer;
+ }
+
+ .league-page :global(.queue-chip:hover) {
+ background: var(--surface-hover);
+ }
+
+ .league-page :global(.queue-chip.on) {
+ border-color: var(--accent);
+ color: var(--text);
+ }
+
+ .league-page :global(.history-summary) {
+ font-size: 12.5px;
+ color: var(--text-secondary);
+ margin: 0 0 10px;
+ }
+
+ .league-page :global(.objective-row) {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+ }
+
+ .league-page :global(.objective-chip) {
+ display: inline-flex;
+ align-items: baseline;
+ gap: 6px;
+ padding: 4px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--border-radius);
+ font-variant-numeric: tabular-nums;
+ font-size: 12.5px;
+ }
+
+ .league-page :global(.event-feed) {
+ list-style: none;
+ margin: 12px 0 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+
+ .league-page :global(.event-item) {
+ display: flex;
+ gap: 8px;
+ font-size: 12.5px;
+ }
+
+ .league-page :global(.event-time) {
+ color: var(--gray);
+ font-variant-numeric: tabular-nums;
+ min-width: 42px;
+ }
+
+ .league-page :global(.event-text) {
+ display: flex;
+ gap: 4px;
+ flex-wrap: wrap;
+ }
+
.league-page :global(.delay-block) {
display: flex;
flex-direction: column;