Add Friends by their Riot ID from the Account selector (#116)
CI / core (pull_request) Successful in 1m42s
CI / core (pull_request) Successful in 1m42s
- The selector lists « Vos Comptes », « Amis » (when there are some) and a last entry « Ajouter un ami… » that opens a Pseudo#TAG field validated by Entrée; refusals are shown with the field, the missing key with a way to « Paramètres ». - A Friend's history is imported on its own below-normal thread, one import at a time (the latest asked for wins), when it is added, chosen in the selector and on « Actualiser » while it is shown; never at launch or on a timer. - The Défi reloads as Matches arrive (at most once a second) and the header says « Import de Pseudo : n / N Parties »; a failure shows as one alert line, an import of a deleted Friend ends silently. - Tests with a simulated Riot source, docs/interface.md and the user guide updated. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d601d30605
commit
0f13ecbc80
16 files changed
+942
-36
No files matched your search
@@ -35,7 +35,7 @@ use gpui_kit::base::async_util::{Sender, unbounded};
|
||||
use gpui_kit::component::*;
|
||||
use gpui_kit::*;
|
||||
|
||||
use page::{ChampionSortChosen, Launch, LiveMatchStarted, Page, RecapOpened};
|
||||
use page::{ChampionSortChosen, Launch, LiveMatchStarted, Page, RecapOpened, SettingsRequested};
|
||||
use settings::{KeyEvent, KeyForm, KeyStore, apply_theme};
|
||||
use title_bar::{MIN_WINDOW_SIZE, refresh_button, settings_button, title_bar, update_button};
|
||||
use worker::{CatalogRefresh, Msg, spawn_follower};
|
||||
@@ -65,6 +65,7 @@ struct RootView {
|
||||
_champ_select: Subscription,
|
||||
_recap: Subscription,
|
||||
_live_match: Subscription,
|
||||
_settings: Subscription,
|
||||
_sort: Subscription,
|
||||
}
|
||||
|
||||
@@ -158,6 +159,12 @@ impl RootView {
|
||||
this.show_page(window, cx);
|
||||
}
|
||||
});
|
||||
// A Friend was refused for want of a key.
|
||||
let settings = cx.subscribe_in(
|
||||
&page,
|
||||
window,
|
||||
|this, _, _: &SettingsRequested, window, cx| this.open_settings(window, cx),
|
||||
);
|
||||
// A Live Match started: « Paramètres » gives way, and a window minimised or hidden in the
|
||||
// notification area opens again without the focus; unlike a champ select, it is not
|
||||
// brought above the others, the game's included (#109).
|
||||
@@ -215,6 +222,7 @@ impl RootView {
|
||||
_champ_select: champ_select,
|
||||
_recap: recap,
|
||||
_live_match: live_match,
|
||||
_settings: settings,
|
||||
_sort: sort,
|
||||
}
|
||||
}
|
||||
|
||||
+16
-3
@@ -17,7 +17,7 @@ use arena_tracker_core::{
|
||||
};
|
||||
use gpui_kit::base::async_util::Sender;
|
||||
use gpui_kit::component::input::InputState;
|
||||
use gpui_kit::component::select::{SelectItem, SelectState};
|
||||
use gpui_kit::component::select::{SearchableVec, SelectGroup, SelectItem, SelectState};
|
||||
use gpui_kit::*;
|
||||
use profiling::shown;
|
||||
use scrollbar::PageScrollbar;
|
||||
@@ -31,6 +31,7 @@ mod cards;
|
||||
mod champ_select;
|
||||
mod display;
|
||||
mod displayed;
|
||||
mod friends;
|
||||
mod home;
|
||||
mod hover;
|
||||
mod in_game;
|
||||
@@ -72,13 +73,18 @@ fn now_ms() -> i64 {
|
||||
.map_or(0, |d| d.as_millis() as i64)
|
||||
}
|
||||
|
||||
/// One Account in the selector; its value is the puuid.
|
||||
/// One Account in the selector; its value is the puuid. The last entry, « Ajouter un ami… », has
|
||||
/// `friends::ADD_FRIEND` instead.
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct AccountItem {
|
||||
puuid: String,
|
||||
title: SharedString,
|
||||
friend: bool,
|
||||
}
|
||||
|
||||
/// The selector's entries, in groups: your Accounts, the Friends, then « Ajouter un ami… ».
|
||||
type AccountList = SearchableVec<SelectGroup<AccountItem>>;
|
||||
|
||||
impl SelectItem for AccountItem {
|
||||
type Value = String;
|
||||
|
||||
@@ -113,6 +119,10 @@ impl EventEmitter<ChampSelectTransition> for Page {}
|
||||
pub struct RecapOpened;
|
||||
impl EventEmitter<RecapOpened> for Page {}
|
||||
|
||||
/// The Account selector's field refused a Friend for want of a key: « Paramètres » opens.
|
||||
pub struct SettingsRequested;
|
||||
impl EventEmitter<SettingsRequested> for Page {}
|
||||
|
||||
/// The player chose a sort for the cards: to be saved with the other preferences.
|
||||
pub struct ChampionSortChosen(pub ChampionSort);
|
||||
impl EventEmitter<ChampionSortChosen> for Page {}
|
||||
@@ -328,8 +338,11 @@ pub struct Page {
|
||||
#[cfg(test)]
|
||||
reorders: usize,
|
||||
stored: Option<usize>,
|
||||
account_select: Entity<SelectState<Vec<AccountItem>>>,
|
||||
account_select: Entity<SelectState<AccountList>>,
|
||||
/// The Accounts of the selector in its order, without « Ajouter un ami… ».
|
||||
account_items: Vec<AccountItem>,
|
||||
/// The Friends: « Ajouter un ami… », their import.
|
||||
friends: friends::Friends,
|
||||
season_select: Entity<SelectState<Vec<SharedString>>>,
|
||||
format_select: Entity<SelectState<Vec<SharedString>>>,
|
||||
format_names: Vec<SharedString>,
|
||||
|
||||
@@ -23,6 +23,9 @@ impl Page {
|
||||
_ => Alert::error("problem", message),
|
||||
});
|
||||
}
|
||||
if let Some(error) = self.friend_error() {
|
||||
banners.push(Alert::error("friend", error.clone()));
|
||||
}
|
||||
if let Some(ProgressCheck::Differs { app, official }) = self.official() {
|
||||
banners.push(Alert::warning(
|
||||
"official",
|
||||
@@ -103,7 +106,8 @@ impl Render for Page {
|
||||
.map(|progress| stage::sweep(progress, window.viewport_size(), cx));
|
||||
let muted = cx.theme().muted_foreground;
|
||||
let busy = self.busy();
|
||||
let status_line = sync_line(busy, self.progress, self.crashed, self.stored);
|
||||
let status_line = (self.friend_status().filter(|_| !busy))
|
||||
.unwrap_or_else(|| sync_line(busy, self.progress, self.crashed, self.stored));
|
||||
|
||||
div()
|
||||
// The pointer takes over from the keyboard: the card it lifted goes down.
|
||||
@@ -163,6 +167,7 @@ impl Render for Page {
|
||||
),
|
||||
)
|
||||
})
|
||||
.children(self.friend_field(cx))
|
||||
.when(shown("banners"), |page| {
|
||||
page.child(div().v_flex().gap_1().children(self.status_alerts()))
|
||||
})
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
//! Friends (#116): the selector's groups and its last entry « Ajouter un ami… », the field that
|
||||
//! takes a Riot ID, and the import of a Friend's history. Nothing here runs on a timer: a Friend's
|
||||
//! Matches are fetched when it is added, when it is chosen in the selector and on « Actualiser ».
|
||||
|
||||
use super::{AccountItem, AccountList, Page, RELOAD_EVERY, SettingsRequested};
|
||||
use crate::text::friend_sync_line;
|
||||
use crate::worker::{spawn_add_friend, spawn_friend_import};
|
||||
use arena_tracker_core::{AddFriendError, AddedFriend, SyncProgress};
|
||||
use gpui_kit::component::button::Button;
|
||||
use gpui_kit::component::input::{Escape, InputEvent, InputState};
|
||||
use gpui_kit::component::select::{SearchableVec, SelectGroup};
|
||||
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
|
||||
use gpui_kit::*;
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// The value of the selector's last entry: no puuid can take it.
|
||||
pub(super) const ADD_FRIEND: &str = "+";
|
||||
|
||||
/// What the Friends need from the page.
|
||||
pub(super) struct Friends {
|
||||
/// The field that takes a Riot ID.
|
||||
pub(super) input: Entity<InputState>,
|
||||
pub(super) open: bool,
|
||||
/// The Riot ID is being looked up: Enter does nothing meanwhile.
|
||||
pub(super) pending: bool,
|
||||
/// Why the last Riot ID was refused, and whether « Paramètres » is the way out.
|
||||
pub(super) refusal: Option<(String, bool)>,
|
||||
/// The puuids of the Friends, as of the last read of the Accounts.
|
||||
pub(super) ids: HashSet<String>,
|
||||
pub(super) import: Import,
|
||||
}
|
||||
|
||||
/// At most one Friend's import at a time, so the key's limits are shared with the active Account
|
||||
/// and no more than one thread waits on the network.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Import {
|
||||
pub(super) running: Option<String>,
|
||||
/// Asked for while another ran: the latest Friend asked for wins.
|
||||
pub(super) queued: Option<String>,
|
||||
pub(super) progress: Option<SyncProgress>,
|
||||
/// The Friend whose last import failed, and why.
|
||||
pub(super) error: Option<(String, String)>,
|
||||
}
|
||||
|
||||
impl Friends {
|
||||
pub(super) fn new(window: &mut Window, cx: &mut Context<Page>) -> (Friends, Subscription) {
|
||||
let input = cx.new(|cx| InputState::new(window, cx).placeholder("Pseudo#TAG"));
|
||||
let enter = cx.subscribe(&input, |page, _, event: &InputEvent, cx| {
|
||||
if matches!(event, InputEvent::PressEnter { .. }) {
|
||||
page.submit_friend(cx);
|
||||
}
|
||||
});
|
||||
let friends = Friends {
|
||||
input,
|
||||
open: false,
|
||||
pending: false,
|
||||
refusal: None,
|
||||
ids: HashSet::new(),
|
||||
import: Import::default(),
|
||||
};
|
||||
(friends, enter)
|
||||
}
|
||||
}
|
||||
|
||||
/// The selector's groups. « Ajouter un ami… » stands alone at the bottom.
|
||||
pub(super) fn account_groups(items: &[AccountItem]) -> AccountList {
|
||||
let (friends, yours): (Vec<_>, Vec<_>) = items.iter().cloned().partition(|a| a.friend);
|
||||
let mut groups = Vec::new();
|
||||
for (title, items) in [("Vos Comptes", yours), ("Amis", friends)] {
|
||||
if !items.is_empty() {
|
||||
groups.push(SelectGroup::new(title).items(items));
|
||||
}
|
||||
}
|
||||
groups.push(SelectGroup::new("").item(AccountItem {
|
||||
puuid: ADD_FRIEND.into(),
|
||||
title: "Ajouter un ami…".into(),
|
||||
friend: false,
|
||||
}));
|
||||
SearchableVec::new(groups)
|
||||
}
|
||||
|
||||
impl Page {
|
||||
/// The Accounts of the selector, yours then the Friends, the active one first in its group.
|
||||
pub(in crate::page) fn account_items(&mut self) -> Vec<AccountItem> {
|
||||
let friends = self.tracker.friends().unwrap_or_default();
|
||||
self.friends.ids = friends.into_iter().map(|a| a.puuid).collect();
|
||||
let active = self.active_account().map(|a| a.puuid.clone());
|
||||
let mut ordered: Vec<&arena_tracker_core::Account> = self.accounts.iter().collect();
|
||||
ordered.sort_by_key(|a| {
|
||||
(
|
||||
self.friends.ids.contains(&a.puuid),
|
||||
Some(&a.puuid) != active.as_ref(),
|
||||
)
|
||||
});
|
||||
ordered
|
||||
.into_iter()
|
||||
.map(|a| AccountItem {
|
||||
puuid: a.puuid.clone(),
|
||||
title: arena_tracker_core::account_riot_id(a).into(),
|
||||
friend: self.friends.ids.contains(&a.puuid),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// An entry of the selector was confirmed.
|
||||
pub(in crate::page) fn account_chosen(
|
||||
&mut self,
|
||||
value: &str,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
if value == ADD_FRIEND {
|
||||
self.open_friend_field(window, cx);
|
||||
} else {
|
||||
self.choose_account(value, window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the Account `puuid` (the active one: following it again) and, for a Friend, imports
|
||||
/// its new Matches.
|
||||
pub(in crate::page) fn choose_account(
|
||||
&mut self,
|
||||
puuid: &str,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let following = self.active_account().is_some_and(|a| a.puuid == puuid);
|
||||
let pinned = (!following).then(|| puuid.to_string());
|
||||
if pinned != self.pinned {
|
||||
self.show_account(pinned, window, cx);
|
||||
}
|
||||
if self.is_imported_friend(puuid) {
|
||||
self.import_friend(puuid, cx);
|
||||
}
|
||||
}
|
||||
|
||||
/// A Friend the follower does not keep up to date: only its import fetches its Matches.
|
||||
fn is_imported_friend(&self, puuid: &str) -> bool {
|
||||
let followed = (self.status.updating.as_ref()).or(self.last_active.as_ref());
|
||||
self.friends.ids.contains(puuid) && followed.is_none_or(|a| a.puuid != puuid)
|
||||
}
|
||||
|
||||
/// The Friend shown, when « Actualiser » imports it.
|
||||
pub(in crate::page) fn shown_friend(&self) -> Option<String> {
|
||||
let shown = self.displayed()?;
|
||||
self.is_imported_friend(&shown.puuid)
|
||||
.then(|| shown.puuid.clone())
|
||||
}
|
||||
|
||||
fn open_friend_field(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.friends.open = true;
|
||||
self.friends.refusal = None;
|
||||
// The selector keeps showing the Account of the screen.
|
||||
self.select_shown_account(window, cx);
|
||||
self.friends.input.update(cx, |input, cx| {
|
||||
input.set_value("", window, cx);
|
||||
input.focus(window, cx);
|
||||
});
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub(in crate::page) fn close_friend_field(&mut self, cx: &mut Context<Self>) {
|
||||
self.friends.open = false;
|
||||
self.friends.refusal = None;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn submit_friend(&mut self, cx: &mut Context<Self>) {
|
||||
if self.friends.pending {
|
||||
return;
|
||||
}
|
||||
let riot_id = self.friends.input.read(cx).value().to_string();
|
||||
self.friends.pending = true;
|
||||
self.friends.refusal = None;
|
||||
spawn_add_friend(self.tracker.clone(), riot_id, self.tx.clone());
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// The Riot ID was looked up: its Account is shown, or the field says why not.
|
||||
pub(in crate::page) fn friend_added(
|
||||
&mut self,
|
||||
result: Result<AddedFriend, AddFriendError>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.friends.pending = false;
|
||||
match result {
|
||||
Ok(AddedFriend::Added(account) | AddedFriend::Known(account)) => {
|
||||
self.close_friend_field(cx);
|
||||
self.reload_accounts(window, cx);
|
||||
self.choose_account(&account.puuid, window, cx);
|
||||
}
|
||||
Err(refused) => {
|
||||
let missing_key = matches!(refused, AddFriendError::MissingKey);
|
||||
self.friends.refusal = Some((refused.message(), missing_key));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Imports the Matches of the Friend `puuid` not stored yet, now or when the import running
|
||||
/// has ended.
|
||||
pub(in crate::page) fn import_friend(&mut self, puuid: &str, cx: &mut Context<Self>) {
|
||||
let import = &mut self.friends.import;
|
||||
match &import.running {
|
||||
Some(running) if running == puuid => import.queued = None,
|
||||
Some(_) => import.queued = Some(puuid.to_string()),
|
||||
None => self.start_friend_import(puuid.to_string()),
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn start_friend_import(&mut self, puuid: String) {
|
||||
let import = &mut self.friends.import;
|
||||
import.error.take_if(|(failed, _)| *failed == puuid);
|
||||
import.queued = None;
|
||||
import.progress = None;
|
||||
import.running = Some(puuid.clone());
|
||||
spawn_friend_import(self.tracker.clone(), puuid, self.tx.clone());
|
||||
}
|
||||
|
||||
/// The Matches arrive: the Challenge of the Friend shown fills as they do.
|
||||
pub(in crate::page) fn friend_progress(
|
||||
&mut self,
|
||||
puuid: &str,
|
||||
progress: SyncProgress,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
if self.friends.import.running.as_deref() != Some(puuid) {
|
||||
return;
|
||||
}
|
||||
self.friends.import.progress = Some(progress);
|
||||
if self.last_reload.elapsed() >= RELOAD_EVERY && self.shows(puuid) {
|
||||
self.reload_in_background(window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
/// The import ended: the Challenge reads the stored Matches once, and the next import starts.
|
||||
pub(in crate::page) fn friend_imported(
|
||||
&mut self,
|
||||
puuid: String,
|
||||
outcome: Result<(), String>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let import = &mut self.friends.import;
|
||||
import.running = None;
|
||||
import.progress = None;
|
||||
if let Err(message) = outcome {
|
||||
import.error = Some((puuid.clone(), message));
|
||||
}
|
||||
if self.shows(&puuid) {
|
||||
self.reload_in_background(window, cx);
|
||||
}
|
||||
if let Some(next) = self.friends.import.queued.take() {
|
||||
self.start_friend_import(next);
|
||||
}
|
||||
}
|
||||
|
||||
/// A Friend's addition or import panicked: nothing is known to run any more.
|
||||
pub(in crate::page) fn friend_crashed(&mut self) {
|
||||
self.friends.pending = false;
|
||||
self.friends.import = Import::default();
|
||||
}
|
||||
|
||||
fn shows(&self, puuid: &str) -> bool {
|
||||
self.viewed().is_some_and(|a| a.puuid == puuid)
|
||||
}
|
||||
|
||||
/// The header's status line while a Friend's history is imported.
|
||||
pub(in crate::page) fn friend_status(&self) -> Option<String> {
|
||||
let import = &self.friends.import;
|
||||
let running = import.running.as_ref()?;
|
||||
let name = &self
|
||||
.accounts
|
||||
.iter()
|
||||
.find(|a| a.puuid == *running)?
|
||||
.game_name;
|
||||
Some(friend_sync_line(name, import.progress))
|
||||
}
|
||||
|
||||
/// Why the import of the Friend shown failed.
|
||||
pub(in crate::page) fn friend_error(&self) -> Option<&String> {
|
||||
let (puuid, message) = self.friends.import.error.as_ref()?;
|
||||
self.shows(puuid).then_some(message)
|
||||
}
|
||||
|
||||
/// The field under the header while « Ajouter un ami… » is open.
|
||||
pub(in crate::page) fn friend_field(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
|
||||
if !self.friends.open {
|
||||
return None;
|
||||
}
|
||||
let (muted, danger) = (cx.theme().muted_foreground, cx.theme().danger);
|
||||
let missing_key = matches!(self.friends.refusal, Some((_, true)));
|
||||
Some(
|
||||
div()
|
||||
.h_flex()
|
||||
.flex_wrap()
|
||||
.items_center()
|
||||
.gap_x_3()
|
||||
.gap_y_2()
|
||||
.on_action(cx.listener(|page, _: &Escape, _, cx| page.close_friend_field(cx)))
|
||||
.child(
|
||||
div()
|
||||
.w(px(260.))
|
||||
.child(gpui_kit::component::input::Input::new(&self.friends.input)),
|
||||
)
|
||||
.child(
|
||||
Button::new("friend-cancel")
|
||||
.label("Annuler")
|
||||
.on_click(cx.listener(|page, _, _, cx| page.close_friend_field(cx))),
|
||||
)
|
||||
.children(self.friends.pending.then(|| {
|
||||
div()
|
||||
.text_sm()
|
||||
.text_color(muted)
|
||||
.child("Recherche du Compte…")
|
||||
}))
|
||||
.children(
|
||||
(self.friends.refusal.as_ref()).map(|(message, _)| {
|
||||
div().text_sm().text_color(danger).child(message.clone())
|
||||
}),
|
||||
)
|
||||
.children(missing_key.then(|| {
|
||||
Button::new("friend-settings")
|
||||
.label("Paramètres")
|
||||
.on_click(cx.listener(|_, _, _, cx| cx.emit(SettingsRequested)))
|
||||
}))
|
||||
.into_any_element(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -34,8 +34,12 @@ impl Page {
|
||||
self.start_entry(window, cx);
|
||||
}
|
||||
|
||||
/// Starts a refresh, or queues one behind the refresh already running.
|
||||
/// Starts a refresh, or queues one behind the refresh already running. A Friend is shown:
|
||||
/// its new Matches are imported instead, the follower has nothing to refresh for it.
|
||||
pub(crate) fn request_refresh(&mut self, cx: &mut Context<Self>) {
|
||||
if let Some(friend) = self.shown_friend() {
|
||||
return self.import_friend(&friend, cx);
|
||||
}
|
||||
if self.refresh.request() {
|
||||
spawn_refresh(self.tracker.clone(), self.tx.clone());
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use super::friends::Friends;
|
||||
use super::scrollbar::PageScrollbar;
|
||||
use super::statistics::ChartsRow;
|
||||
use super::{
|
||||
ALL_FORMATS, ALL_SEASONS, AccountItem, Launch, MatchPlayback, Page, SORTS, Tab, home, in_game,
|
||||
ALL_FORMATS, ALL_SEASONS, AccountList, Launch, MatchPlayback, Page, SORTS, Tab, home, in_game,
|
||||
now_ms,
|
||||
};
|
||||
use crate::banner_art::BannerArt;
|
||||
@@ -54,7 +55,8 @@ impl Page {
|
||||
SeasonScope::AllSeasons => Some(seasons.len() - 1),
|
||||
};
|
||||
let account_select =
|
||||
cx.new(|cx| SelectState::new(Vec::<AccountItem>::new(), None, window, cx));
|
||||
cx.new(|cx| SelectState::new(AccountList::new(Vec::new()), None, window, cx));
|
||||
let (friends, friend_field) = Friends::new(window, cx);
|
||||
let season_select =
|
||||
cx.new(|cx| SelectState::new(seasons, selected.map(IndexPath::new), window, cx));
|
||||
let format_names = vec![SharedString::from(ALL_FORMATS)];
|
||||
@@ -93,6 +95,7 @@ impl Page {
|
||||
subscriptions.extend(Self::light_on_hover(&home_grid, cx));
|
||||
subscriptions.extend(Self::light_on_hover(&anvil_grid, cx));
|
||||
subscriptions.extend([
|
||||
friend_field,
|
||||
// The Windows setting turned off: a transition running ends, a card lifting is
|
||||
// lifted, and nothing waits.
|
||||
cx.observe_global_in::<AnimationSetting>(window, |this, window, cx| {
|
||||
@@ -140,15 +143,9 @@ impl Page {
|
||||
cx.subscribe_in(
|
||||
&account_select,
|
||||
window,
|
||||
|this, _, event: &SelectEvent<Vec<AccountItem>>, window, cx| {
|
||||
let SelectEvent::Confirm(Some(puuid)) = event else {
|
||||
return;
|
||||
};
|
||||
// Picking the active Account is following it again.
|
||||
let following = this.active_account().is_some_and(|a| a.puuid == *puuid);
|
||||
let pinned = (!following).then(|| puuid.clone());
|
||||
if pinned != this.pinned {
|
||||
this.show_account(pinned, window, cx);
|
||||
|this, _, event: &SelectEvent<AccountList>, window, cx| {
|
||||
if let SelectEvent::Confirm(Some(puuid)) = event {
|
||||
this.account_chosen(puuid, window, cx);
|
||||
}
|
||||
},
|
||||
),
|
||||
@@ -276,6 +273,7 @@ impl Page {
|
||||
stored: None,
|
||||
account_select,
|
||||
account_items: Vec::new(),
|
||||
friends,
|
||||
season_select,
|
||||
format_select,
|
||||
format_names,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use crate::card::Card;
|
||||
use crate::page::{ALL_FORMATS, AccountItem, NextHome, Page, now_ms};
|
||||
use crate::page::friends::account_groups;
|
||||
use crate::page::{ALL_FORMATS, NextHome, Page, now_ms};
|
||||
use crate::worker::{compute_statistics, spawn_statistics};
|
||||
use arena_tracker_core::{Account, Scope, SeasonScope, StateFilter, account_riot_id};
|
||||
use arena_tracker_core::{Scope, SeasonScope, StateFilter};
|
||||
use gpui_kit::component::IndexPath;
|
||||
use gpui_kit::*;
|
||||
use std::time::Instant;
|
||||
@@ -26,23 +27,13 @@ impl Page {
|
||||
}
|
||||
|
||||
/// Re-reads the Accounts and selects the one shown.
|
||||
fn reload_accounts(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
pub(in crate::page) fn reload_accounts(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.accounts = self.tracker.accounts().unwrap_or_default();
|
||||
self.last_active = self.tracker.last_active_account().ok().flatten();
|
||||
if self.pinned.as_ref() == self.status.updating.as_ref().map(|a| &a.puuid) {
|
||||
self.pinned = None;
|
||||
}
|
||||
// The active Account first, the others by Riot ID.
|
||||
let active = self.active_account().map(|a| a.puuid.clone());
|
||||
let mut ordered: Vec<&Account> = self.accounts.iter().collect();
|
||||
ordered.sort_by_key(|a| Some(&a.puuid) != active.as_ref());
|
||||
let items: Vec<AccountItem> = ordered
|
||||
.into_iter()
|
||||
.map(|a| AccountItem {
|
||||
puuid: a.puuid.clone(),
|
||||
title: account_riot_id(a).into(),
|
||||
})
|
||||
.collect();
|
||||
let items = self.account_items();
|
||||
let changed = items != self.account_items;
|
||||
self.account_items = items.clone();
|
||||
if changed {
|
||||
@@ -50,7 +41,9 @@ impl Page {
|
||||
self.phase_riot_id = None;
|
||||
}
|
||||
if changed {
|
||||
(self.account_select).update(cx, |select, cx| select.set_items(items, window, cx));
|
||||
(self.account_select).update(cx, |select, cx| {
|
||||
select.set_items(account_groups(&items), window, cx)
|
||||
});
|
||||
}
|
||||
self.select_shown_account(window, cx);
|
||||
// The stored Matches may have changed, or the Account.
|
||||
|
||||
@@ -15,6 +15,8 @@ mod champ_select_others;
|
||||
mod champ_select_scroll;
|
||||
mod champ_select_tab;
|
||||
mod client_fixtures;
|
||||
mod friends;
|
||||
mod friends_fixtures;
|
||||
mod grid;
|
||||
mod home;
|
||||
mod in_game;
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
//! Friends added by their Riot ID from the Account selector (#116): the selector's entries, the
|
||||
//! field and its refusals, and the import of a Friend's Matches when it is added, chosen again
|
||||
//! and on « Actualiser ». The Riot source is simulated (`friends_fixtures`).
|
||||
|
||||
use super::friends_fixtures::{CARL, Handles, tracker};
|
||||
use super::page_fixtures::{draw, open_page_with_tracker};
|
||||
use crate::page::Page;
|
||||
use crate::page::friends::ADD_FRIEND;
|
||||
use crate::worker::Msg;
|
||||
use gpui_kit::component::input::InputEvent;
|
||||
use gpui_kit::component::select::SelectEvent;
|
||||
use gpui_kit::{Entity, TestAppContext, VisualTestContext};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
async fn on_alice(cx: &mut TestAppContext) -> (Entity<Page>, VisualTestContext, Handles) {
|
||||
cx.executor().allow_parking();
|
||||
let (tracker, _, handles) = tracker();
|
||||
let (page, window) = open_page_with_tracker(cx, tracker);
|
||||
cx.condition(&page, |p, _| p.stats.is_some()).await;
|
||||
(page, window, handles)
|
||||
}
|
||||
|
||||
fn pick(page: &Entity<Page>, cx: &mut VisualTestContext, value: &str) {
|
||||
let select = page.read_with(cx, |p, _| p.account_select.clone());
|
||||
let value = value.to_string();
|
||||
cx.update(|_, cx| select.update(cx, |_, cx| cx.emit(SelectEvent::Confirm(Some(value)))));
|
||||
draw(cx);
|
||||
}
|
||||
|
||||
fn selected(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<String> {
|
||||
page.read_with(cx, |p, cx| {
|
||||
(p.account_select.read(cx).selected_value()).map(|v| v.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
/// The field opened by « Ajouter un ami… », `riot_id` typed and validated with Enter.
|
||||
fn add(page: &Entity<Page>, cx: &mut VisualTestContext, riot_id: &str) {
|
||||
pick(page, cx, ADD_FRIEND);
|
||||
let input = page.read_with(cx, |p, _| p.friends.input.clone());
|
||||
cx.update(|window, cx| input.update(cx, |input, cx| input.set_value(riot_id, window, cx)));
|
||||
submit(page, cx);
|
||||
}
|
||||
|
||||
fn submit(page: &Entity<Page>, cx: &mut VisualTestContext) {
|
||||
let input = page.read_with(cx, |p, _| p.friends.input.clone());
|
||||
cx.update(|_, cx| {
|
||||
input.update(cx, |_, cx| {
|
||||
cx.emit(InputEvent::PressEnter {
|
||||
secondary: false,
|
||||
shift: false,
|
||||
})
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
fn refusal(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<String> {
|
||||
page.read_with(cx, |p, _| {
|
||||
p.friends.refusal.as_ref().map(|(m, _)| m.clone())
|
||||
})
|
||||
}
|
||||
|
||||
fn status_line(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<String> {
|
||||
page.read_with(cx, |p, _| p.friend_status())
|
||||
}
|
||||
|
||||
/// Waits for the import of the Friend `puuid` to have ended, and for the statistics of the
|
||||
/// page to count `stored` Matches.
|
||||
async fn imported(page: &Entity<Page>, cx: &mut TestAppContext, stored: usize) {
|
||||
cx.condition(page, move |p, _| {
|
||||
p.friends.import.running.is_none() && p.stored == Some(stored) && p.stats.is_some()
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Carl added and imported, the page on him.
|
||||
async fn on_carl(cx: &mut TestAppContext) -> (Entity<Page>, VisualTestContext, Handles) {
|
||||
let (page, mut window, handles) = on_alice(cx).await;
|
||||
add(&page, &mut window, "Carl#EUW");
|
||||
imported(&page, cx, 2).await;
|
||||
(page, window, handles)
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn the_selector_ends_with_the_entry_that_adds_a_friend(cx: &mut TestAppContext) {
|
||||
let (page, mut window, _) = on_alice(cx).await;
|
||||
let groups = |page: &Entity<Page>, window: &mut VisualTestContext| {
|
||||
page.read_with(window, |p, _| {
|
||||
crate::page::friends::account_groups(&p.account_items)
|
||||
})
|
||||
};
|
||||
use gpui_kit::component::select::SelectDelegate as _;
|
||||
// Your Accounts, then the entry alone.
|
||||
let list = groups(&page, &mut window);
|
||||
window.update(|_, cx| {
|
||||
assert_eq!(list.sections_count(cx), 2);
|
||||
assert_eq!((list.items_count(0), list.items_count(1)), (2, 1));
|
||||
});
|
||||
|
||||
// Carl is a Friend: « Amis » comes between them.
|
||||
add(&page, &mut window, "Carl#EUW");
|
||||
imported(&page, cx, 2).await;
|
||||
let list = groups(&page, &mut window);
|
||||
window.update(|_, cx| {
|
||||
assert_eq!(list.sections_count(cx), 3);
|
||||
let counts = [0, 1, 2].map(|section| list.items_count(section));
|
||||
assert_eq!(counts, [2, 1, 1]);
|
||||
});
|
||||
page.read_with(&window, |p, _| {
|
||||
let friends: Vec<_> = p.account_items.iter().map(|a| a.friend).collect();
|
||||
assert_eq!(friends, [false, false, true]);
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn choosing_the_entry_opens_the_field_and_keeps_the_account_shown(cx: &mut TestAppContext) {
|
||||
let (page, mut window, _) = on_alice(cx).await;
|
||||
pick(&page, &mut window, ADD_FRIEND);
|
||||
page.read_with(&window, |p, _| {
|
||||
assert!(p.friends.open);
|
||||
assert_eq!(p.pinned, None);
|
||||
});
|
||||
assert_eq!(selected(&page, &mut window).as_deref(), Some("Alice"));
|
||||
// The field is drawn, then closed by « Annuler » or Escape.
|
||||
draw(&mut window);
|
||||
window.update(|_, cx| page.update(cx, |p, cx| p.close_friend_field(cx)));
|
||||
page.read_with(&window, |p, _| assert!(!p.friends.open));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn a_valid_riot_id_adds_the_friend_shows_its_challenge_filling_and_imports_it(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let (page, mut window, handles) = on_alice(cx).await;
|
||||
handles.gate.set(false);
|
||||
add(&page, &mut window, "Carl#EUW");
|
||||
// Enter again while the look-up runs does nothing.
|
||||
submit(&page, &mut window);
|
||||
|
||||
// The first Match is awaited: the line says how far the import is.
|
||||
cx.condition(&page, |p, _| {
|
||||
p.friends.import.progress.is_some_and(|g| g.to_fetch == 2)
|
||||
})
|
||||
.await;
|
||||
draw(&mut window);
|
||||
assert_eq!(
|
||||
status_line(&page, &mut window).as_deref(),
|
||||
Some("Import de Carl : 0 / 2 Parties")
|
||||
);
|
||||
page.read_with(&window, |p, _| {
|
||||
assert!(!p.friends.open && !p.friends.pending);
|
||||
assert_eq!(p.pinned.as_deref(), Some("Carl"));
|
||||
assert_eq!(p.viewed().map(|a| a.puuid.as_str()), Some("Carl"));
|
||||
assert!(p.friends.ids.contains("Carl"));
|
||||
});
|
||||
assert_eq!(selected(&page, &mut window).as_deref(), Some("Carl"));
|
||||
|
||||
// The Matches arrive: the Challenge fills.
|
||||
handles.gate.set(true);
|
||||
imported(&page, cx, 2).await;
|
||||
assert_eq!(status_line(&page, &mut window), None);
|
||||
assert_eq!(handles.fetched.lock().unwrap().len(), 2);
|
||||
page.read_with(&window, |p, _| {
|
||||
let challenge = p.stats.as_ref().unwrap().challenge.as_ref().unwrap();
|
||||
assert_eq!(challenge.attempts, 2);
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn a_riot_id_that_cannot_be_added_says_why_and_keeps_the_text(cx: &mut TestAppContext) {
|
||||
let (page, mut window, handles) = on_alice(cx).await;
|
||||
let cases = [
|
||||
("Carl", "Saisissez un Riot ID de la forme Pseudo#TAG."),
|
||||
("Zed#EUW", "Aucun Compte ne porte ce Riot ID."),
|
||||
("Dora#EUW", "Ce Compte joue dans une autre région."),
|
||||
];
|
||||
for (riot_id, message) in cases {
|
||||
add(&page, &mut window, riot_id);
|
||||
cx.condition(&page, |p, _| !p.friends.pending).await;
|
||||
assert_eq!(refusal(&page, &mut window).as_deref(), Some(message));
|
||||
page.read_with(&window, |p, cx| {
|
||||
assert!(p.friends.open);
|
||||
assert_eq!(p.friends.input.read(cx).value().as_ref(), riot_id);
|
||||
assert!(p.friends.ids.is_empty());
|
||||
});
|
||||
draw(&mut window);
|
||||
}
|
||||
|
||||
// Without a key, « Paramètres » is the way out.
|
||||
handles.no_key.store(true, Ordering::SeqCst);
|
||||
add(&page, &mut window, "Carl#EUW");
|
||||
cx.condition(&page, |p, _| !p.friends.pending).await;
|
||||
page.read_with(&window, |p, _| {
|
||||
let (message, settings) = p.friends.refusal.clone().unwrap();
|
||||
assert_eq!(
|
||||
message,
|
||||
"Ajoutez une clé API Riot dans « Paramètres » pour ajouter un Ami."
|
||||
);
|
||||
assert!(settings);
|
||||
});
|
||||
draw(&mut window);
|
||||
assert_eq!(selected(&page, &mut window).as_deref(), Some("Alice"));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn an_account_already_stored_is_selected_not_added(cx: &mut TestAppContext) {
|
||||
let (page, mut window, _) = on_alice(cx).await;
|
||||
add(&page, &mut window, "bob#euw");
|
||||
cx.condition(&page, |p, _| p.pinned.as_deref() == Some("Bob"))
|
||||
.await;
|
||||
cx.condition(&page, |p, _| p.stats.is_some()).await;
|
||||
page.read_with(&window, |p, _| {
|
||||
assert!(!p.friends.open);
|
||||
assert!(p.friends.ids.is_empty());
|
||||
assert!(p.friends.import.running.is_none());
|
||||
});
|
||||
assert_eq!(selected(&page, &mut window).as_deref(), Some("Bob"));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn choosing_a_friend_again_imports_only_its_new_matches(cx: &mut TestAppContext) {
|
||||
let (page, mut window, handles) = on_carl(cx).await;
|
||||
pick(&page, &mut window, "Alice");
|
||||
cx.condition(&page, |p, _| p.stats.is_some()).await;
|
||||
// Choosing Alice (the active Account) imports nothing.
|
||||
page.read_with(&window, |p, _| assert!(p.friends.import.running.is_none()));
|
||||
|
||||
handles.third.store(true, Ordering::SeqCst);
|
||||
pick(&page, &mut window, "Carl");
|
||||
imported(&page, cx, 3).await;
|
||||
// Fetched once each: the first import's, then only the new one.
|
||||
assert_eq!(
|
||||
*handles.fetched.lock().unwrap(),
|
||||
[CARL[1], CARL[2], CARL[0]]
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn refresh_imports_the_friend_shown_and_not_the_active_account(cx: &mut TestAppContext) {
|
||||
let (page, mut window, handles) = on_carl(cx).await;
|
||||
handles.third.store(true, Ordering::SeqCst);
|
||||
window.update(|_, cx| page.update(cx, |p, cx| p.request_refresh(cx)));
|
||||
page.read_with(&window, |p, _| {
|
||||
assert_eq!(p.friends.import.running.as_deref(), Some("Carl"));
|
||||
assert!(!p.refresh.running());
|
||||
});
|
||||
imported(&page, cx, 3).await;
|
||||
assert_eq!(handles.fetched.lock().unwrap().len(), 3);
|
||||
|
||||
// On the active Account, « Actualiser » is the follower's refresh.
|
||||
pick(&page, &mut window, "Alice");
|
||||
window.update(|_, cx| page.update(cx, |p, cx| p.request_refresh(cx)));
|
||||
page.read_with(&window, |p, _| {
|
||||
assert!(p.refresh.running());
|
||||
assert!(p.friends.import.running.is_none());
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn the_latest_friend_asked_for_waits_for_the_import_running(cx: &mut TestAppContext) {
|
||||
let (page, mut window, handles) = on_alice(cx).await;
|
||||
handles.gate.set(false);
|
||||
add(&page, &mut window, "Carl#EUW");
|
||||
cx.condition(&page, |p, _| p.friends.import.running.is_some())
|
||||
.await;
|
||||
window.update(|_, cx| {
|
||||
page.update(cx, |p, cx| {
|
||||
p.import_friend("Carl", cx);
|
||||
p.import_friend("Dora", cx);
|
||||
p.import_friend("Zed", cx);
|
||||
assert_eq!(p.friends.import.queued.as_deref(), Some("Zed"));
|
||||
})
|
||||
});
|
||||
handles.gate.set(true);
|
||||
// Zed is not stored: its import ends silently, and nothing is left waiting.
|
||||
cx.condition(&page, |p, _| {
|
||||
p.friends.import.running.is_none() && p.friends.import.queued.is_none()
|
||||
})
|
||||
.await;
|
||||
page.read_with(&window, |p, _| assert!(p.friend_error().is_none()));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn an_import_of_a_deleted_friend_ends_silently(cx: &mut TestAppContext) {
|
||||
let (page, mut window, handles) = on_alice(cx).await;
|
||||
handles.gate.set(false);
|
||||
add(&page, &mut window, "Carl#EUW");
|
||||
cx.condition(&page, |p, _| p.friends.import.progress.is_some())
|
||||
.await;
|
||||
let tracker = page.read_with(&window, |p, _| p.tracker.clone());
|
||||
tracker.delete_account("Carl").unwrap();
|
||||
handles.gate.set(true);
|
||||
cx.condition(&page, |p, _| p.friends.import.running.is_none())
|
||||
.await;
|
||||
page.read_with(&window, |p, _| {
|
||||
assert!(p.friend_error().is_none() && p.friends.import.error.is_none());
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn a_friend_who_signs_in_to_the_client_stays_a_friend_and_is_not_imported(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
cx.executor().allow_parking();
|
||||
let (tracker, signed_in, _) = tracker();
|
||||
let (page, mut window) = open_page_with_tracker(cx, tracker);
|
||||
cx.condition(&page, |p, _| p.stats.is_some()).await;
|
||||
add(&page, &mut window, "Carl#EUW");
|
||||
imported(&page, cx, 2).await;
|
||||
|
||||
*signed_in.lock().unwrap() = "Carl".into();
|
||||
window.update(|window, cx| {
|
||||
page.update(cx, |page, cx| {
|
||||
page.tracker.follow_client(0, None, &mut |_| {});
|
||||
let status = page.tracker.status();
|
||||
assert_eq!(status.updating.as_ref().unwrap().puuid, "Carl");
|
||||
let round = Msg::Round {
|
||||
status,
|
||||
reload: true,
|
||||
matches: Vec::new(),
|
||||
game_end: None,
|
||||
};
|
||||
page.apply(round, window, cx);
|
||||
// The follower keeps him up to date: « Actualiser » is its refresh.
|
||||
assert_eq!(page.shown_friend(), None);
|
||||
})
|
||||
});
|
||||
page.read_with(&window, |p, _| {
|
||||
let items: Vec<_> = p
|
||||
.account_items
|
||||
.iter()
|
||||
.map(|a| (&*a.puuid, a.friend))
|
||||
.collect();
|
||||
assert_eq!(items, [("Alice", false), ("Bob", false), ("Carl", true)]);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! The Riot source of the Friends' tests: Alice and Bob as in `TwoAccounts`, and Carl (a Friend
|
||||
//! of the key's region, two Matches) and Dora (another region). A gate holds Carl's Matches
|
||||
//! back, so a test sees an import under way.
|
||||
|
||||
use super::client_fixtures::FakeClient;
|
||||
use super::matches_fixtures::TwoAccounts;
|
||||
use super::page_fixtures::{MATCH_1750, season};
|
||||
use arena_tracker_core::{Account, MatchHistorySource, SourceError, Tracker};
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex};
|
||||
|
||||
pub(super) const CARL: [&str; 3] = ["EUW1_9100000003", "EUW1_9100000002", "EUW1_9100000001"];
|
||||
|
||||
/// Carl's Matches are fetched while it is open.
|
||||
pub(super) struct Gate {
|
||||
open: Mutex<bool>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
impl Gate {
|
||||
pub(super) fn set(&self, open: bool) {
|
||||
*self.open.lock().unwrap() = open;
|
||||
self.changed.notify_all();
|
||||
}
|
||||
|
||||
fn pass(&self) {
|
||||
let mut open = self.open.lock().unwrap();
|
||||
while !*open {
|
||||
open = self.changed.wait(open).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the test watches and changes while the source runs inside the tracker.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Handles {
|
||||
pub(super) gate: Arc<Gate>,
|
||||
/// The Matches of Carl fetched, in order.
|
||||
pub(super) fetched: Arc<Mutex<Vec<String>>>,
|
||||
/// Carl has played a third Match.
|
||||
pub(super) third: Arc<AtomicBool>,
|
||||
/// The key is gone: Riot answers for no Riot ID.
|
||||
pub(super) no_key: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
struct Riot {
|
||||
inner: TwoAccounts,
|
||||
handles: Handles,
|
||||
}
|
||||
|
||||
impl MatchHistorySource for Riot {
|
||||
fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result<Account, SourceError> {
|
||||
if self.handles.no_key.load(Ordering::SeqCst) {
|
||||
return Err(SourceError::MissingKey);
|
||||
}
|
||||
match game_name {
|
||||
"Alice" | "Bob" | "Carl" | "Dora" => self.inner.resolve_account(game_name, tag_line),
|
||||
_ => Err(SourceError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
fn match_ids(
|
||||
&self,
|
||||
puuid: &str,
|
||||
queue_id: u32,
|
||||
start: usize,
|
||||
count: usize,
|
||||
since: Option<i64>,
|
||||
) -> Result<Vec<String>, SourceError> {
|
||||
if puuid != "Carl" {
|
||||
return self.inner.match_ids(puuid, queue_id, start, count, since);
|
||||
}
|
||||
if queue_id != 1750 || start != 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let skip = usize::from(!self.handles.third.load(Ordering::SeqCst));
|
||||
Ok(CARL[skip..].iter().map(|id| id.to_string()).collect())
|
||||
}
|
||||
|
||||
fn fetch_match(&self, id: &str) -> Result<String, SourceError> {
|
||||
let Some(at) = CARL.iter().position(|carl| *carl == id) else {
|
||||
return self.inner.fetch_match(id);
|
||||
};
|
||||
self.handles.gate.pass();
|
||||
self.handles.fetched.lock().unwrap().push(id.into());
|
||||
let start = ["1794000000000", "1792000000000", "1790000000000"][at];
|
||||
Ok(MATCH_1750
|
||||
.replace("EUW1_9000000006", id)
|
||||
.replace("1794763752767", start)
|
||||
.replace("fixture-puuid-self", "Carl"))
|
||||
}
|
||||
|
||||
fn account_platform(&self, puuid: &str) -> Result<String, SourceError> {
|
||||
Ok(if puuid == "Dora" { "NA1" } else { "euw1" }.into())
|
||||
}
|
||||
|
||||
fn serves_platform(&self, platform: &str) -> bool {
|
||||
platform.eq_ignore_ascii_case("EUW1")
|
||||
}
|
||||
}
|
||||
|
||||
/// A tracker that knows Alice (signed in to the client, the name signs another in) and Bob,
|
||||
/// with the Season `Saison` that began in 2020.
|
||||
pub(super) fn tracker() -> (Tracker, Arc<Mutex<String>>, Handles) {
|
||||
let handles = Handles {
|
||||
gate: Arc::new(Gate {
|
||||
open: Mutex::new(true),
|
||||
changed: Condvar::new(),
|
||||
}),
|
||||
fetched: Arc::default(),
|
||||
third: Arc::default(),
|
||||
no_key: Arc::default(),
|
||||
};
|
||||
let client = FakeClient::new("Alice");
|
||||
let source = Riot {
|
||||
inner: TwoAccounts { more: false },
|
||||
handles: handles.clone(),
|
||||
};
|
||||
let tracker = Tracker::open(Path::new(":memory:"), Box::new(source))
|
||||
.unwrap()
|
||||
.with_seasons(vec![season("Saison", 2020)])
|
||||
.with_client(Box::new(client.clone()));
|
||||
tracker.sync("Bob#EUW", &mut |_| {}).unwrap();
|
||||
tracker.follow_client(0, None, &mut |_| {});
|
||||
(tracker, client.name, handles)
|
||||
}
|
||||
@@ -131,6 +131,17 @@ impl Page {
|
||||
catalog,
|
||||
} => self.apply_death_recap(match_id, fetched, result, &catalog, cx),
|
||||
Msg::DeathRecapStored(match_id) => self.death_recap_stored(&match_id),
|
||||
Msg::FriendAdded(result) => self.friend_added(result, window, cx),
|
||||
Msg::FriendProgress { puuid, progress } => {
|
||||
self.friend_progress(&puuid, progress, window, cx)
|
||||
}
|
||||
Msg::FriendImported { puuid, outcome } => {
|
||||
self.friend_imported(puuid, outcome, window, cx)
|
||||
}
|
||||
Msg::FriendCrashed => {
|
||||
self.friend_crashed();
|
||||
self.mark_crashed();
|
||||
}
|
||||
Msg::Crashed => self.mark_crashed(),
|
||||
Msg::RefreshCrashed => {
|
||||
self.refresh.reset();
|
||||
|
||||
@@ -127,6 +127,16 @@ pub fn sync_line(
|
||||
}
|
||||
}
|
||||
|
||||
/// The status line while the history of the Friend `name` is imported.
|
||||
pub fn friend_sync_line(name: &str, progress: Option<SyncProgress>) -> String {
|
||||
match progress {
|
||||
Some(p) if p.to_fetch > 0 => {
|
||||
format!("Import de {name} : {} / {} Parties", p.fetched, p.to_fetch)
|
||||
}
|
||||
_ => format!("Import de {name}…"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -217,6 +227,19 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_friend_line_names_the_friend() {
|
||||
let progress = SyncProgress {
|
||||
fetched: 3,
|
||||
to_fetch: 10,
|
||||
};
|
||||
assert_eq!(
|
||||
friend_sync_line("Bob", Some(progress)),
|
||||
"Import de Bob : 3 / 10 Parties"
|
||||
);
|
||||
assert_eq!(friend_sync_line("Bob", None), "Import de Bob…");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sync_line_follows_what_is_running() {
|
||||
let progress = SyncProgress {
|
||||
|
||||
@@ -8,17 +8,19 @@ use std::thread;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use arena_tracker_core::{
|
||||
ChampSelect, ClientEvent, DeathRecapState, GameCatalog, LiveMatch, MatchRecap, Scope,
|
||||
Statistics, Status, SyncProgress, Tracker, UpdateChannel,
|
||||
AddFriendError, AddedFriend, ChampSelect, ClientEvent, DeathRecapState, GameCatalog, LiveMatch,
|
||||
MatchRecap, Scope, Statistics, Status, SyncProgress, Tracker, UpdateChannel,
|
||||
};
|
||||
use gpui_kit::base::async_util::Sender;
|
||||
|
||||
mod death_recap;
|
||||
mod friends;
|
||||
pub(crate) mod game_data;
|
||||
mod matches;
|
||||
|
||||
pub use death_recap::spawn_death_recap;
|
||||
use death_recap::spawn_death_recap_queue;
|
||||
pub use friends::{spawn_add_friend, spawn_friend_import};
|
||||
pub use game_data::CatalogRefresh;
|
||||
pub use matches::{MatchEntry, RecentQuery, spawn_match_list, spawn_recap, spawn_recent_matches};
|
||||
|
||||
@@ -84,6 +86,20 @@ pub enum Msg {
|
||||
DeathRecapStored(String),
|
||||
/// The names and icons of the items and augments, read again from the cache on disk.
|
||||
GameData(Arc<GameCatalog>),
|
||||
/// A Riot ID was looked up: the Friend is stored, or why it was not.
|
||||
FriendAdded(Result<AddedFriend, AddFriendError>),
|
||||
/// A Friend's import fetched Matches.
|
||||
FriendProgress {
|
||||
puuid: String,
|
||||
progress: SyncProgress,
|
||||
},
|
||||
/// A Friend's import ended (`Err`: what to say, a deleted Friend is not one).
|
||||
FriendImported {
|
||||
puuid: String,
|
||||
outcome: Result<(), String>,
|
||||
},
|
||||
/// The thread of a Friend's addition or import panicked.
|
||||
FriendCrashed,
|
||||
/// A worker thread panicked.
|
||||
Crashed,
|
||||
/// The refresh worker panicked.
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
//! A Friend's addition and history, on their own below-normal threads: both wait on the network,
|
||||
//! and the import also on the follower's rounds, so neither can run on the UI thread or the
|
||||
//! follower's.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use arena_tracker_core::{Error, Tracker, UpdateProblem};
|
||||
use gpui_kit::base::async_util::Sender;
|
||||
|
||||
use super::{Msg, spawn_guarded};
|
||||
|
||||
/// Looks the Riot ID up and stores the Friend; the page answers `Msg::FriendAdded`.
|
||||
pub fn spawn_add_friend(tracker: Arc<Tracker>, riot_id: String, tx: Sender<Msg>) {
|
||||
spawn_guarded(tx, Msg::FriendCrashed, move |tx| {
|
||||
let _ = tx.try_send(Msg::FriendAdded(tracker.add_friend(&riot_id)));
|
||||
});
|
||||
}
|
||||
|
||||
/// Imports the Matches of the Friend `puuid` not stored yet (all of them for a first import),
|
||||
/// then its Mastery Points. A Friend deleted meanwhile ends silently.
|
||||
pub fn spawn_friend_import(tracker: Arc<Tracker>, puuid: String, tx: Sender<Msg>) {
|
||||
spawn_guarded(tx, Msg::FriendCrashed, move |tx| {
|
||||
let result = tracker.import_friend(&puuid, &mut |progress| {
|
||||
let _ = tx.try_send(Msg::FriendProgress {
|
||||
puuid: puuid.clone(),
|
||||
progress,
|
||||
});
|
||||
});
|
||||
let outcome = match result {
|
||||
Ok(_) | Err(Error::UnknownAccount(_)) => Ok(()),
|
||||
Err(e) => Err(UpdateProblem::from(&e).message()),
|
||||
};
|
||||
let _ = tx.try_send(Msg::FriendImported { puuid, outcome });
|
||||
});
|
||||
}
|
||||
@@ -2,12 +2,16 @@
|
||||
|
||||
## Défi et Statistiques
|
||||
|
||||
L’appli s’ouvre sur **Défi** : la bannière du Défi de la Saison, puis les cartes de vos champions. À côté des onglets, le sélecteur de **Compte** liste les Comptes déjà connectés au client sur ce PC, le Compte actif (celui du client) en premier, et choisit le Compte que montrent **Défi**, **Statistiques** et **Parties**. Pour un autre Compte, la bannière commence par « Défi de Pseudo · », et la Progression officielle et l’animation de fin de Partie sont réservées au Compte actif. Le filtre **Tous** revient à chaque changement de Compte ; le tri et le thème restent les mêmes. L’appli revient sur le Compte actif quand une Sélection ou une Partie en cours commence, et à la fin d’une Partie suivie. Pour l’analyse détaillée (courbe des champions validés, Placements, Tentatives, tableau des champions, avec les sélecteurs de Saison et de Format), ouvrez **Statistiques ›**, le lien au bout de la ligne de la Saison, en haut de la bannière. La page porte **‹ Défi** en haut à gauche, qui ramène au Défi ; l’onglet **Défi** de la barre du haut y ramène aussi. Au clavier, Tab atteint le lien et le retour, Entrée ou Espace les active. Survolez l’anneau de la bannière : la graduation visée s’allume et la bannière présente ce champion (« X · validé le 12 nov. · 3 Tentatives », « X · 2 Parties · meilleur Placement 3ᵉ » ou « X · jamais joué ») ; elle revient à son état habituel quand vous quittez l’anneau.
|
||||
L’appli s’ouvre sur **Défi** : la bannière du Défi de la Saison, puis les cartes de vos champions. À côté des onglets, le sélecteur de **Compte** liste les Comptes déjà connectés au client sur ce PC, le Compte actif (celui du client) en premier, et choisit le Compte que montrent **Défi**, **Statistiques** et **Parties** (les Comptes sous « Vos Comptes », vos Amis sous « Amis »). Pour un autre Compte, la bannière commence par « Défi de Pseudo · », et la Progression officielle et l’animation de fin de Partie sont réservées au Compte actif. Le filtre **Tous** revient à chaque changement de Compte ; le tri et le thème restent les mêmes. L’appli revient sur le Compte actif quand une Sélection ou une Partie en cours commence, et à la fin d’une Partie suivie. Pour l’analyse détaillée (courbe des champions validés, Placements, Tentatives, tableau des champions, avec les sélecteurs de Saison et de Format), ouvrez **Statistiques ›**, le lien au bout de la ligne de la Saison, en haut de la bannière. La page porte **‹ Défi** en haut à gauche, qui ramène au Défi ; l’onglet **Défi** de la barre du haut y ramène aussi. Au clavier, Tab atteint le lien et le retour, Entrée ou Espace les active. Survolez l’anneau de la bannière : la graduation visée s’allume et la bannière présente ce champion (« X · validé le 12 nov. · 3 Tentatives », « X · 2 Parties · meilleur Placement 3ᵉ » ou « X · jamais joué ») ; elle revient à son état habituel quand vous quittez l’anneau.
|
||||
|
||||
Au début d’une Sélection des champions Arena, l’onglet **Sélection** apparaît à droite de **Défi** et **Parties** et l’appli l’affiche d’elle-même, où que vous soyez. Il montre les Champions de l’Enclume et « Autres champions ». Pendant la sélection, l’onglet **Défi** montre l’accueil habituel (et **Statistiques ›**) ; revenez sur **Sélection** quand vous voulez, la main y est posée. Les bans et les choix des alliés ne vous ramènent pas sur **Sélection**. À la fin de la sélection, l’onglet disparaît et l’appli affiche le Défi, ou **En partie** si la partie est lancée.
|
||||
|
||||
Au lancement d’une Partie Arena, y compris quand l’appli démarre ou retrouve le client en pleine partie, l’onglet **En partie** apparaît à la place de **Sélection** et l’appli l’affiche, où que vous soyez. Sa bannière montre le champion que vous jouez sur son illustration, avec la Saison et le compteur du Défi, l’anneau où sa graduation est allumée, et l’enjeu : « Un top 1 validerait X : 88 / 172 », ou le jour où il a été validé. Dessous, sa fiche (Parties, Victoires, meilleur Placement, Tentatives, points de maîtrise, premier top 1) et ses 5 dernières Parties de la Saison, avec date, Format et Placement. Tant que le client n’a pas dit quel champion vous jouez (en Bravery, par exemple), la bannière indique « Champion en cours d’identification ». **Défi** et **Statistiques** restent accessibles pendant la partie. L’onglet reste jusqu’au résultat de la Partie ; une partie hors Arena ne fait rien apparaître.
|
||||
|
||||
## Amis
|
||||
|
||||
Pour consulter le Défi d’un autre joueur, ouvrez le sélecteur de Compte, choisissez **Ajouter un ami…** tout en bas, saisissez son Riot ID sous la forme `Pseudo#TAG` et appuyez sur Entrée (Échap ou **Annuler** referme le champ). Il doit jouer dans la même région que votre clé API Riot ; sans clé, ouvrez **Paramètres** pour en ajouter une. Si le Compte est déjà l’un des vôtres ou un Ami, il est simplement sélectionné. Votre ami n’a rien à installer : ses Parties Arena viennent de l’API Riot, avec votre clé. À l’ajout, tout son historique disponible est importé en arrière-plan, la Saison en cours d’abord et après les besoins de votre Compte actif ; son Défi se remplit au fur et à mesure, et la ligne en haut à droite affiche « Import de Pseudo : n / N Parties ». Ensuite, seules ses nouvelles Parties sont récupérées, quand vous le choisissez dans le sélecteur ou que vous appuyez sur **Actualiser** pendant que son Défi est affiché ; l’appli ne le fait jamais d’elle-même. Si l’import est interrompu, il reprend de la même façon sans refaire ce qui est enregistré. Un Ami qui se connecte au client sur votre PC reste un Ami, suivi comme votre Compte actif.
|
||||
|
||||
## Parties
|
||||
|
||||
L’onglet **Parties** liste vos Parties enregistrées, de la plus récente à la plus ancienne, pour le Compte choisi dans le sélecteur de la barre du haut (le Compte connecté au client au démarrage). Chaque ligne montre le champion, la date et l’heure, et le Placement, en or pour un top 1, en vert pour une autre Victoire, en rouge sinon. Au-dessus de la liste, des filtres se combinent : la **Saison** (la Saison actuelle par défaut, ou toutes les Saisons s’il n’y en a pas) et le **Format**, les mêmes sélecteurs que sur **Statistiques** : en changer sur une page le change sur l’autre ; le **Placement** (**Tous**, **Top 1** ou **Victoires**, les Parties que le jeu compte comme gagnées) ; et une recherche de champion, comme sur l’accueil (nom, abréviation connue comme « TF », sans tenir compte des accents ni des majuscules). Le Placement et la recherche sont gardés tant que l’appli reste ouverte. Si aucune Partie ne correspond, la liste le dit et le récapitulatif reste vide. À l’ouverture, la Partie la plus récente que les filtres laissent est choisie et son récapitulatif s’affiche à côté : les équipes rangées par Placement, votre ligne encadrée d’or, et pour chaque joueur son Riot ID, son niveau, son K/D/A, ses objets, ses améliorations et ses dégâts aux champions (une barre comparée au meilleur de la Partie, partagée entre physiques, magiques et bruts, le total à côté). Les objets et les améliorations montrent leur icône dans une case, leur nom dans la bulle de survol, toujours en français, quelle que soit la langue du client (les objets viennent de Data Dragon, les améliorations de CommunityDragon) ; sans eux (première ouverture hors ligne, objet très récent), une icône neutre et « Objet n » ou « Amélioration n ». Survoler un objet ou une amélioration, dans le récapitulatif ou dans **Dégâts observés dans les récaps de mort**, affiche une bulle avec son nom et sa description ; un « ? » marque une valeur que le jeu calcule pendant la Partie, et « Description indisponible » une description que le catalogue n’a pas. Ces noms, descriptions et icônes sont gardés sur le disque : ils restent lisibles hors ligne. L’appli regarde si le jeu a changé de patch à son lancement et à chaque ouverture du client, jamais en continu, et ne télécharge de nouveau que dans ce cas ; au premier téléchargement, les icônes apparaissent au fur et à mesure ; si CommunityDragon n’a pas encore le nouveau patch, les noms précédents restent jusqu’à la vérification suivante. Cliquez une autre Partie, ou parcourez la liste avec les flèches haut et bas. Cliquez la ligne d’un joueur (ou atteignez-la avec Tab, puis Entrée ou Espace) pour déplier ses détails, en barres avec leur valeur à côté : dégâts aux champions et reçus (une barre partagée entre physiques, magiques et bruts), puis dégâts atténués, soins et boucliers sur les alliés, or gagné et dépensé, contrôle (une barre par valeur, pleine pour le meilleur joueur de la Partie) ; recliquez pour les replier. Les totaux sont ceux de Riot, tels quels. Une valeur que Riot ne donne pas s’affiche « Indisponible ». Sous ces valeurs, la section **Dégâts observés dans les récaps de mort** détaille, par objet et par amélioration du joueur (puis « Autres effets »), les dégâts que les récaps de mort des champions éliminés lui attribuent : c’est la seule source de dégâts par effet, si bien que les dégâts infligés à un champion qui survit n’y figurent jamais et que le total de la Partie par effet reste indisponible. Les récaps sont récupérés chez Riot une fois par Partie, à la fin d’une Partie suivie ou à la première ouverture d’une Partie plus ancienne ; une Partie provisoire affiche « En attente », une Partie dont Riot refuse les récaps « Indisponible », et en cas d’échec passager le bouton **Réessayer** les redemande. Une bannière, la même que celle du Défi (Saison, compteur, anneau), surmonte la liste et le récapitulatif : son illustration est le champion de la Partie choisie, dont la graduation est allumée sur l’anneau. Dans une fenêtre étroite, la liste et ses filtres s’ouvrent avec le bouton **Parties** au-dessus du récapitulatif. Si la Partie affichée n’est plus laissée par un filtre, la première Partie de la liste prend sa place.
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ L’identité « L’Anneau » (itération « La Bannière ») habille ensuite c
|
||||
1. À chaque ouverture, « Tous » est sélectionné. La grille présente tous les champions, y compris ceux jamais joués et ceux déjà validés. La recherche par nom et les filtres « Restants » et « Validés » permettent de réduire la grille.
|
||||
2. La bannière ouvre l’accueil. Elle porte l’anneau, un titre-compteur « N / total champions validés » surmonté de la Saison (précédée de « Défi de Pseudo · » pour un Compte autre que le Compte actif), et deux lignes : « Dernier champion validé : X, le … » et « Dernière Partie : … ». La seconde est permanente : elle se calcule à partir des Parties enregistrées, pas des seules Parties suivies pendant la session. Le titre « Défi de saison » disparaît. Le total reste celui du Défi quand on recherche un champion, filtre la grille ou passe en sélection. La section « Identité » décrit la bannière et l’anneau.
|
||||
3. Lorsqu’aucune préférence de tri n’a encore été enregistrée, les champions sont classés par points de maîtrise décroissants. Le joueur peut choisir A–Z. Le même choix s’applique aux deux écrans et à toutes leurs sections de cartes, puis à la prochaine ouverture. L’anneau n’est pas une section de cartes : c’est une jauge à l’ordre fixe, qui ne suit pas le tri choisi.
|
||||
4. **Compte.** Un seul sélecteur de Compte, à côté des onglets dans la barre du haut, choisit le Compte que montrent « Défi » (bannière, anneau, grille, fiches), « Statistiques » et « Parties » : il liste les Comptes déjà connectés au client sur ce PC, le Compte actif (celui du client, ou le dernier connu quand il est fermé) en premier. L’appli démarre sur le Compte actif et y revient à l’entrée dans une phase (sélection, Partie en cours), où le sélecteur est grisé, et quand une Partie suivie s’ouvre en fin de Partie. Un autre Compte rétablit « Tous » dans le filtre de l’accueil et dans celui de « Statistiques » ; le tri et le thème sont communs à tous les Comptes. Ses statistiques sont calculées une fois, hors du thread d’interface. La Progression officielle et les animations de fin de Partie ne concernent que le Compte actif.
|
||||
4. **Compte.** Un seul sélecteur de Compte, à côté des onglets dans la barre du haut, choisit le Compte que montrent « Défi » (bannière, anneau, grille, fiches), « Statistiques » et « Parties » : il liste, sous « Vos Comptes », les Comptes déjà connectés au client sur ce PC, le Compte actif (celui du client, ou le dernier connu quand il est fermé) en premier, puis, sous « Amis » (seulement s’il y en a), les Amis ; sa dernière entrée, seule, est « Ajouter un ami… ». L’appli démarre sur le Compte actif et y revient à l’entrée dans une phase (sélection, Partie en cours), où le sélecteur est grisé, et quand une Partie suivie s’ouvre en fin de Partie. Un autre Compte rétablit « Tous » dans le filtre de l’accueil et dans celui de « Statistiques » ; le tri et le thème sont communs à tous les Comptes. Ses statistiques sont calculées une fois, hors du thread d’interface. La Progression officielle et les animations de fin de Partie ne concernent que le Compte actif. **Amis.** Un Ami est un Compte ajouté par son Riot ID pour consulter son Défi ; ses Parties viennent de l’API Riot avec la clé de l’utilisateur, il n’a rien à installer. « Ajouter un ami… » laisse le Compte affiché sélectionné et ouvre sous l’en-tête un champ « Pseudo#TAG » (avec « Annuler » ; Échap le ferme aussi), validé par Entrée : la recherche tourne hors du thread d’interface, à basse priorité, « Recherche du Compte… » l’indique et Entrée est ignorée en attendant. Un refus s’affiche à côté du champ, qui garde son texte : Riot ID mal formé (« Saisissez un Riot ID de la forme Pseudo#TAG. »), « Aucun Compte ne porte ce Riot ID. », « Ce Compte joue dans une autre région. », ou, sans clé API Riot, un message qui renvoie à « Paramètres » et un bouton « Paramètres » qui les ouvre. Un Compte déjà connu (le vôtre ou un Ami) est simplement sélectionné. Une fois l’Ami ajouté, il est sélectionné et son Défi s’affiche. L’import de son historique Arena disponible tourne en arrière-plan, à basse priorité, après les requêtes du Compte actif et dans les limites de la clé : la Saison en cours d’abord, puis les autres ; le Défi se remplit au fur et à mesure (rechargé au plus une fois par seconde) et la ligne d’état de l’en-tête dit « Import de Pseudo : n / N Parties » (« Import de Pseudo… » pendant la recherche des Parties) ; ses points de maîtrise sont récupérés à la fin. Une erreur de l’import s’affiche en une ligne d’alerte sans masquer les données enregistrées, et l’import d’un Ami supprimé s’arrête sans rien dire. Ensuite seules les nouvelles Parties sont récupérées, quand on choisit l’Ami dans le sélecteur ou avec « Actualiser » pendant qu’il est affiché (qui n’actualise alors que lui) : jamais à intervalle régulier ni au lancement. Un import interrompu reprend à l’une de ces deux occasions, sans réimporter les Parties déjà enregistrées. Un seul import tourne à la fois ; la demande faite pendant l’un attend sa fin, la dernière gagne. Un Ami qui se connecte au client sur ce PC reste un Ami, sous « Amis » : l’appli le suit alors comme tout Compte actif (le premier de son groupe), ses Parties en direct comprises, et « Actualiser » est celle du suivi.
|
||||
|
||||
### Carte de champion
|
||||
|
||||
|
||||
Reference in new issue
Block a user